1 // Copyright (c) 2015-2016 The Khronos Group Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <sstream>
16 #include <string>
17 #include <tuple>
18 #include <vector>
19 
20 #include "gmock/gmock.h"
21 #include "source/spirv_constant.h"
22 #include "test/test_fixture.h"
23 #include "test/unit_spirv.h"
24 
25 namespace spvtools {
26 namespace {
27 
28 using spvtest::AutoText;
29 using spvtest::ScopedContext;
30 using spvtest::TextToBinaryTest;
31 using ::testing::Combine;
32 using ::testing::Eq;
33 using ::testing::HasSubstr;
34 
35 class BinaryToText : public ::testing::Test {
36  public:
BinaryToText()37   BinaryToText()
38       : context(spvContextCreate(SPV_ENV_UNIVERSAL_1_0)), binary(nullptr) {}
~BinaryToText()39   ~BinaryToText() {
40     spvBinaryDestroy(binary);
41     spvContextDestroy(context);
42   }
43 
SetUp()44   virtual void SetUp() {
45     const char* textStr = R"(
46       OpSource OpenCL_C 12
47       OpMemoryModel Physical64 OpenCL
48       OpSourceExtension "PlaceholderExtensionName"
49       OpEntryPoint Kernel %1 "foo"
50       OpExecutionMode %1 LocalSizeHint 1 1 1
51  %2 = OpTypeVoid
52  %3 = OpTypeBool
53  %4 = OpTypeInt 8 0
54  %5 = OpTypeInt 8 1
55  %6 = OpTypeInt 16 0
56  %7 = OpTypeInt 16 1
57  %8 = OpTypeInt 32 0
58  %9 = OpTypeInt 32 1
59 %10 = OpTypeInt 64 0
60 %11 = OpTypeInt 64 1
61 %12 = OpTypeFloat 16
62 %13 = OpTypeFloat 32
63 %14 = OpTypeFloat 64
64 %15 = OpTypeVector %4 2
65 )";
66     spv_text_t text = {textStr, strlen(textStr)};
67     spv_diagnostic diagnostic = nullptr;
68     spv_result_t error =
69         spvTextToBinary(context, text.str, text.length, &binary, &diagnostic);
70     spvDiagnosticPrint(diagnostic);
71     spvDiagnosticDestroy(diagnostic);
72     ASSERT_EQ(SPV_SUCCESS, error);
73   }
74 
TearDown()75   virtual void TearDown() {
76     spvBinaryDestroy(binary);
77     binary = nullptr;
78   }
79 
80   // Compiles the given assembly text, and saves it into 'binary'.
CompileSuccessfully(std::string text)81   void CompileSuccessfully(std::string text) {
82     spvBinaryDestroy(binary);
83     binary = nullptr;
84     spv_diagnostic diagnostic = nullptr;
85     EXPECT_EQ(SPV_SUCCESS, spvTextToBinary(context, text.c_str(), text.size(),
86                                            &binary, &diagnostic));
87   }
88 
89   spv_context context;
90   spv_binary binary;
91 };
92 
TEST_F(BinaryToText,Default)93 TEST_F(BinaryToText, Default) {
94   spv_text text = nullptr;
95   spv_diagnostic diagnostic = nullptr;
96   ASSERT_EQ(
97       SPV_SUCCESS,
98       spvBinaryToText(context, binary->code, binary->wordCount,
99                       SPV_BINARY_TO_TEXT_OPTION_NONE, &text, &diagnostic));
100   printf("%s", text->str);
101   spvTextDestroy(text);
102 }
103 
TEST_F(BinaryToText,MissingModule)104 TEST_F(BinaryToText, MissingModule) {
105   spv_text text;
106   spv_diagnostic diagnostic = nullptr;
107   EXPECT_EQ(
108       SPV_ERROR_INVALID_BINARY,
109       spvBinaryToText(context, nullptr, 42, SPV_BINARY_TO_TEXT_OPTION_NONE,
110                       &text, &diagnostic));
111   EXPECT_THAT(diagnostic->error, Eq(std::string("Missing module.")));
112   if (diagnostic) {
113     spvDiagnosticPrint(diagnostic);
114     spvDiagnosticDestroy(diagnostic);
115   }
116 }
117 
TEST_F(BinaryToText,TruncatedModule)118 TEST_F(BinaryToText, TruncatedModule) {
119   // Make a valid module with zero instructions.
120   CompileSuccessfully("");
121   EXPECT_EQ(SPV_INDEX_INSTRUCTION, binary->wordCount);
122 
123   for (size_t length = 0; length < SPV_INDEX_INSTRUCTION; length++) {
124     spv_text text = nullptr;
125     spv_diagnostic diagnostic = nullptr;
126     EXPECT_EQ(
127         SPV_ERROR_INVALID_BINARY,
128         spvBinaryToText(context, binary->code, length,
129                         SPV_BINARY_TO_TEXT_OPTION_NONE, &text, &diagnostic));
130     ASSERT_NE(nullptr, diagnostic);
131     std::stringstream expected;
132     expected << "Module has incomplete header: only " << length
133              << " words instead of " << SPV_INDEX_INSTRUCTION;
134     EXPECT_THAT(diagnostic->error, Eq(expected.str()));
135     spvDiagnosticDestroy(diagnostic);
136   }
137 }
138 
TEST_F(BinaryToText,InvalidMagicNumber)139 TEST_F(BinaryToText, InvalidMagicNumber) {
140   CompileSuccessfully("");
141   std::vector<uint32_t> damaged_binary(binary->code,
142                                        binary->code + binary->wordCount);
143   damaged_binary[SPV_INDEX_MAGIC_NUMBER] ^= 123;
144 
145   spv_diagnostic diagnostic = nullptr;
146   spv_text text;
147   EXPECT_EQ(
148       SPV_ERROR_INVALID_BINARY,
149       spvBinaryToText(context, damaged_binary.data(), damaged_binary.size(),
150                       SPV_BINARY_TO_TEXT_OPTION_NONE, &text, &diagnostic));
151   ASSERT_NE(nullptr, diagnostic);
152   std::stringstream expected;
153   expected << "Invalid SPIR-V magic number '" << std::hex
154            << damaged_binary[SPV_INDEX_MAGIC_NUMBER] << "'.";
155   EXPECT_THAT(diagnostic->error, Eq(expected.str()));
156   spvDiagnosticDestroy(diagnostic);
157 }
158 
159 struct FailedDecodeCase {
160   std::string source_text;
161   std::vector<uint32_t> appended_instruction;
162   std::string expected_error_message;
163 };
164 
165 using BinaryToTextFail =
166     spvtest::TextToBinaryTestBase<::testing::TestWithParam<FailedDecodeCase>>;
167 
TEST_P(BinaryToTextFail,EncodeSuccessfullyDecodeFailed)168 TEST_P(BinaryToTextFail, EncodeSuccessfullyDecodeFailed) {
169   EXPECT_THAT(EncodeSuccessfullyDecodeFailed(GetParam().source_text,
170                                              GetParam().appended_instruction),
171               Eq(GetParam().expected_error_message));
172 }
173 
174 INSTANTIATE_TEST_SUITE_P(
175     InvalidIds, BinaryToTextFail,
176     ::testing::ValuesIn(std::vector<FailedDecodeCase>{
177         {"", spvtest::MakeInstruction(SpvOpTypeVoid, {0}),
178          "Error: Result Id is 0"},
179         {"", spvtest::MakeInstruction(SpvOpConstant, {0, 1, 42}),
180          "Error: Type Id is 0"},
181         {"%1 = OpTypeVoid", spvtest::MakeInstruction(SpvOpTypeVoid, {1}),
182          "Id 1 is defined more than once"},
183         {"%1 = OpTypeVoid\n"
184          "%2 = OpNot %1 %foo",
185          spvtest::MakeInstruction(SpvOpNot, {1, 2, 3}),
186          "Id 2 is defined more than once"},
187         {"%1 = OpTypeVoid\n"
188          "%2 = OpNot %1 %foo",
189          spvtest::MakeInstruction(SpvOpNot, {1, 1, 3}),
190          "Id 1 is defined more than once"},
191         // The following are the two failure cases for
192         // Parser::setNumericTypeInfoForType.
193         {"", spvtest::MakeInstruction(SpvOpConstant, {500, 1, 42}),
194          "Type Id 500 is not a type"},
195         {"%1 = OpTypeInt 32 0\n"
196          "%2 = OpTypeVector %1 4",
197          spvtest::MakeInstruction(SpvOpConstant, {2, 3, 999}),
198          "Type Id 2 is not a scalar numeric type"},
199     }));
200 
201 INSTANTIATE_TEST_SUITE_P(
202     InvalidIdsCheckedDuringLiteralCaseParsing, BinaryToTextFail,
203     ::testing::ValuesIn(std::vector<FailedDecodeCase>{
204         {"", spvtest::MakeInstruction(SpvOpSwitch, {1, 2, 3, 4}),
205          "Invalid OpSwitch: selector id 1 has no type"},
206         {"%1 = OpTypeVoid\n",
207          spvtest::MakeInstruction(SpvOpSwitch, {1, 2, 3, 4}),
208          "Invalid OpSwitch: selector id 1 is a type, not a value"},
209         {"%1 = OpConstantTrue !500",
210          spvtest::MakeInstruction(SpvOpSwitch, {1, 2, 3, 4}),
211          "Type Id 500 is not a type"},
212         {"%1 = OpTypeFloat 32\n%2 = OpConstant %1 1.5",
213          spvtest::MakeInstruction(SpvOpSwitch, {2, 3, 4, 5}),
214          "Invalid OpSwitch: selector id 2 is not a scalar integer"},
215     }));
216 
TEST_F(TextToBinaryTest,OneInstruction)217 TEST_F(TextToBinaryTest, OneInstruction) {
218   const std::string input = "OpSource OpenCL_C 12\n";
219   EXPECT_EQ(input, EncodeAndDecodeSuccessfully(input));
220 }
221 
222 // Exercise the case where an operand itself has operands.
223 // This could detect problems in updating the expected-set-of-operands
224 // list.
TEST_F(TextToBinaryTest,OperandWithOperands)225 TEST_F(TextToBinaryTest, OperandWithOperands) {
226   const std::string input = R"(OpEntryPoint Kernel %1 "foo"
227 OpExecutionMode %1 LocalSizeHint 100 200 300
228 %2 = OpTypeVoid
229 %3 = OpTypeFunction %2
230 %1 = OpFunction %1 None %3
231 )";
232   EXPECT_EQ(input, EncodeAndDecodeSuccessfully(input));
233 }
234 
235 using RoundTripInstructionsTest = spvtest::TextToBinaryTestBase<
236     ::testing::TestWithParam<std::tuple<spv_target_env, std::string>>>;
237 
TEST_P(RoundTripInstructionsTest,Sample)238 TEST_P(RoundTripInstructionsTest, Sample) {
239   EXPECT_THAT(EncodeAndDecodeSuccessfully(std::get<1>(GetParam()),
240                                           SPV_BINARY_TO_TEXT_OPTION_NONE,
241                                           std::get<0>(GetParam())),
242               Eq(std::get<1>(GetParam())));
243 }
244 
245 // clang-format off
246 INSTANTIATE_TEST_SUITE_P(
247     NumericLiterals, RoundTripInstructionsTest,
248     // This test is independent of environment, so just test the one.
249     Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
250                               SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_3),
251             ::testing::ValuesIn(std::vector<std::string>{
252                 "%1 = OpTypeInt 12 0\n%2 = OpConstant %1 1867\n",
253                 "%1 = OpTypeInt 12 1\n%2 = OpConstant %1 1867\n",
254                 "%1 = OpTypeInt 12 1\n%2 = OpConstant %1 -1867\n",
255                 "%1 = OpTypeInt 32 0\n%2 = OpConstant %1 1867\n",
256                 "%1 = OpTypeInt 32 1\n%2 = OpConstant %1 1867\n",
257                 "%1 = OpTypeInt 32 1\n%2 = OpConstant %1 -1867\n",
258                 "%1 = OpTypeInt 64 0\n%2 = OpConstant %1 18446744073709551615\n",
259                 "%1 = OpTypeInt 64 1\n%2 = OpConstant %1 9223372036854775807\n",
260                 "%1 = OpTypeInt 64 1\n%2 = OpConstant %1 -9223372036854775808\n",
261                 // 16-bit floats print as hex floats.
262                 "%1 = OpTypeFloat 16\n%2 = OpConstant %1 0x1.ff4p+16\n",
263                 "%1 = OpTypeFloat 16\n%2 = OpConstant %1 -0x1.d2cp-10\n",
264                 // 32-bit floats
265                 "%1 = OpTypeFloat 32\n%2 = OpConstant %1 -3.125\n",
266                 "%1 = OpTypeFloat 32\n%2 = OpConstant %1 0x1.8p+128\n", // NaN
267                 "%1 = OpTypeFloat 32\n%2 = OpConstant %1 -0x1.0002p+128\n", // NaN
268                 "%1 = OpTypeFloat 32\n%2 = OpConstant %1 0x1p+128\n", // Inf
269                 "%1 = OpTypeFloat 32\n%2 = OpConstant %1 -0x1p+128\n", // -Inf
270                 // 64-bit floats
271                 "%1 = OpTypeFloat 64\n%2 = OpConstant %1 -3.125\n",
272                 "%1 = OpTypeFloat 64\n%2 = OpConstant %1 0x1.ffffffffffffap-1023\n", // small normal
273                 "%1 = OpTypeFloat 64\n%2 = OpConstant %1 -0x1.ffffffffffffap-1023\n",
274                 "%1 = OpTypeFloat 64\n%2 = OpConstant %1 0x1.8p+1024\n", // NaN
275                 "%1 = OpTypeFloat 64\n%2 = OpConstant %1 -0x1.0002p+1024\n", // NaN
276                 "%1 = OpTypeFloat 64\n%2 = OpConstant %1 0x1p+1024\n", // Inf
277                 "%1 = OpTypeFloat 64\n%2 = OpConstant %1 -0x1p+1024\n", // -Inf
278             })));
279 // clang-format on
280 
281 INSTANTIATE_TEST_SUITE_P(
282     MemoryAccessMasks, RoundTripInstructionsTest,
283     Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
284                               SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_3),
285             ::testing::ValuesIn(std::vector<std::string>{
286                 "OpStore %1 %2\n",       // 3 words long.
287                 "OpStore %1 %2 None\n",  // 4 words long, explicit final 0.
288                 "OpStore %1 %2 Volatile\n",
289                 "OpStore %1 %2 Aligned 8\n",
290                 "OpStore %1 %2 Nontemporal\n",
291                 // Combinations show the names from LSB to MSB
292                 "OpStore %1 %2 Volatile|Aligned 16\n",
293                 "OpStore %1 %2 Volatile|Nontemporal\n",
294                 "OpStore %1 %2 Volatile|Aligned|Nontemporal 32\n",
295             })));
296 
297 INSTANTIATE_TEST_SUITE_P(
298     FPFastMathModeMasks, RoundTripInstructionsTest,
299     Combine(
300         ::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
301                           SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_3),
302         ::testing::ValuesIn(std::vector<std::string>{
303             "OpDecorate %1 FPFastMathMode None\n",
304             "OpDecorate %1 FPFastMathMode NotNaN\n",
305             "OpDecorate %1 FPFastMathMode NotInf\n",
306             "OpDecorate %1 FPFastMathMode NSZ\n",
307             "OpDecorate %1 FPFastMathMode AllowRecip\n",
308             "OpDecorate %1 FPFastMathMode Fast\n",
309             // Combinations show the names from LSB to MSB
310             "OpDecorate %1 FPFastMathMode NotNaN|NotInf\n",
311             "OpDecorate %1 FPFastMathMode NSZ|AllowRecip\n",
312             "OpDecorate %1 FPFastMathMode NotNaN|NotInf|NSZ|AllowRecip|Fast\n",
313         })));
314 
315 INSTANTIATE_TEST_SUITE_P(
316     LoopControlMasks, RoundTripInstructionsTest,
317     Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
318                               SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_2),
319             ::testing::ValuesIn(std::vector<std::string>{
320                 "OpLoopMerge %1 %2 None\n",
321                 "OpLoopMerge %1 %2 Unroll\n",
322                 "OpLoopMerge %1 %2 DontUnroll\n",
323                 "OpLoopMerge %1 %2 Unroll|DontUnroll\n",
324             })));
325 
326 INSTANTIATE_TEST_SUITE_P(LoopControlMasksV11, RoundTripInstructionsTest,
327                          Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_1,
328                                                    SPV_ENV_UNIVERSAL_1_2,
329                                                    SPV_ENV_UNIVERSAL_1_3),
330                                  ::testing::ValuesIn(std::vector<std::string>{
331                                      "OpLoopMerge %1 %2 DependencyInfinite\n",
332                                      "OpLoopMerge %1 %2 DependencyLength 8\n",
333                                  })));
334 
335 INSTANTIATE_TEST_SUITE_P(
336     SelectionControlMasks, RoundTripInstructionsTest,
337     Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
338                               SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_2),
339             ::testing::ValuesIn(std::vector<std::string>{
340                 "OpSelectionMerge %1 None\n",
341                 "OpSelectionMerge %1 Flatten\n",
342                 "OpSelectionMerge %1 DontFlatten\n",
343                 "OpSelectionMerge %1 Flatten|DontFlatten\n",
344             })));
345 
346 INSTANTIATE_TEST_SUITE_P(
347     FunctionControlMasks, RoundTripInstructionsTest,
348     Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
349                               SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_3),
350             ::testing::ValuesIn(std::vector<std::string>{
351                 "%2 = OpFunction %1 None %3\n",
352                 "%2 = OpFunction %1 Inline %3\n",
353                 "%2 = OpFunction %1 DontInline %3\n",
354                 "%2 = OpFunction %1 Pure %3\n",
355                 "%2 = OpFunction %1 Const %3\n",
356                 "%2 = OpFunction %1 Inline|Pure|Const %3\n",
357                 "%2 = OpFunction %1 DontInline|Const %3\n",
358             })));
359 
360 INSTANTIATE_TEST_SUITE_P(
361     ImageMasks, RoundTripInstructionsTest,
362     Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
363                               SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_3),
364             ::testing::ValuesIn(std::vector<std::string>{
365                 "%2 = OpImageFetch %1 %3 %4\n",
366                 "%2 = OpImageFetch %1 %3 %4 None\n",
367                 "%2 = OpImageFetch %1 %3 %4 Bias %5\n",
368                 "%2 = OpImageFetch %1 %3 %4 Lod %5\n",
369                 "%2 = OpImageFetch %1 %3 %4 Grad %5 %6\n",
370                 "%2 = OpImageFetch %1 %3 %4 ConstOffset %5\n",
371                 "%2 = OpImageFetch %1 %3 %4 Offset %5\n",
372                 "%2 = OpImageFetch %1 %3 %4 ConstOffsets %5\n",
373                 "%2 = OpImageFetch %1 %3 %4 Sample %5\n",
374                 "%2 = OpImageFetch %1 %3 %4 MinLod %5\n",
375                 "%2 = OpImageFetch %1 %3 %4 Bias|Lod|Grad %5 %6 %7 %8\n",
376                 "%2 = OpImageFetch %1 %3 %4 ConstOffset|Offset|ConstOffsets"
377                 " %5 %6 %7\n",
378                 "%2 = OpImageFetch %1 %3 %4 Sample|MinLod %5 %6\n",
379                 "%2 = OpImageFetch %1 %3 %4"
380                 " Bias|Lod|Grad|ConstOffset|Offset|ConstOffsets|Sample|MinLod"
381                 " %5 %6 %7 %8 %9 %10 %11 %12 %13\n"})));
382 
383 INSTANTIATE_TEST_SUITE_P(
384     NewInstructionsInSPIRV1_2, RoundTripInstructionsTest,
385     Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_3),
386             ::testing::ValuesIn(std::vector<std::string>{
387                 "OpExecutionModeId %1 SubgroupsPerWorkgroupId %2\n",
388                 "OpExecutionModeId %1 LocalSizeId %2 %3 %4\n",
389                 "OpExecutionModeId %1 LocalSizeHintId %2\n",
390                 "OpDecorateId %1 AlignmentId %2\n",
391                 "OpDecorateId %1 MaxByteOffsetId %2\n",
392             })));
393 
394 using MaskSorting = TextToBinaryTest;
395 
TEST_F(MaskSorting,MasksAreSortedFromLSBToMSB)396 TEST_F(MaskSorting, MasksAreSortedFromLSBToMSB) {
397   EXPECT_THAT(EncodeAndDecodeSuccessfully(
398                   "OpStore %1 %2 Nontemporal|Aligned|Volatile 32"),
399               Eq("OpStore %1 %2 Volatile|Aligned|Nontemporal 32\n"));
400   EXPECT_THAT(
401       EncodeAndDecodeSuccessfully(
402           "OpDecorate %1 FPFastMathMode NotInf|Fast|AllowRecip|NotNaN|NSZ"),
403       Eq("OpDecorate %1 FPFastMathMode NotNaN|NotInf|NSZ|AllowRecip|Fast\n"));
404   EXPECT_THAT(
405       EncodeAndDecodeSuccessfully("OpLoopMerge %1 %2 DontUnroll|Unroll"),
406       Eq("OpLoopMerge %1 %2 Unroll|DontUnroll\n"));
407   EXPECT_THAT(
408       EncodeAndDecodeSuccessfully("OpSelectionMerge %1 DontFlatten|Flatten"),
409       Eq("OpSelectionMerge %1 Flatten|DontFlatten\n"));
410   EXPECT_THAT(EncodeAndDecodeSuccessfully(
411                   "%2 = OpFunction %1 DontInline|Const|Pure|Inline %3"),
412               Eq("%2 = OpFunction %1 Inline|DontInline|Pure|Const %3\n"));
413   EXPECT_THAT(EncodeAndDecodeSuccessfully(
414                   "%2 = OpImageFetch %1 %3 %4"
415                   " MinLod|Sample|Offset|Lod|Grad|ConstOffsets|ConstOffset|Bias"
416                   " %5 %6 %7 %8 %9 %10 %11 %12 %13\n"),
417               Eq("%2 = OpImageFetch %1 %3 %4"
418                  " Bias|Lod|Grad|ConstOffset|Offset|ConstOffsets|Sample|MinLod"
419                  " %5 %6 %7 %8 %9 %10 %11 %12 %13\n"));
420 }
421 
422 using OperandTypeTest = TextToBinaryTest;
423 
TEST_F(OperandTypeTest,OptionalTypedLiteralNumber)424 TEST_F(OperandTypeTest, OptionalTypedLiteralNumber) {
425   const std::string input =
426       "%1 = OpTypeInt 32 0\n"
427       "%2 = OpConstant %1 42\n"
428       "OpSwitch %2 %3 100 %4\n";
429   EXPECT_EQ(input, EncodeAndDecodeSuccessfully(input));
430 }
431 
432 using IndentTest = spvtest::TextToBinaryTest;
433 
TEST_F(IndentTest,Sample)434 TEST_F(IndentTest, Sample) {
435   const std::string input = R"(
436 OpCapability Shader
437 OpMemoryModel Logical GLSL450
438 %1 = OpTypeInt 32 0
439 %2 = OpTypeStruct %1 %3 %4 %5 %6 %7 %8 %9 %10 ; force IDs into double digits
440 %11 = OpConstant %1 42
441 OpStore %2 %3 Aligned|Volatile 4 ; bogus, but not indented
442 )";
443   const std::string expected =
444       R"(               OpCapability Shader
445                OpMemoryModel Logical GLSL450
446           %1 = OpTypeInt 32 0
447           %2 = OpTypeStruct %1 %3 %4 %5 %6 %7 %8 %9 %10
448          %11 = OpConstant %1 42
449                OpStore %2 %3 Volatile|Aligned 4
450 )";
451   EXPECT_THAT(
452       EncodeAndDecodeSuccessfully(input, SPV_BINARY_TO_TEXT_OPTION_INDENT),
453       expected);
454 }
455 
456 using FriendlyNameDisassemblyTest = spvtest::TextToBinaryTest;
457 
TEST_F(FriendlyNameDisassemblyTest,Sample)458 TEST_F(FriendlyNameDisassemblyTest, Sample) {
459   const std::string input = R"(
460 OpCapability Shader
461 OpMemoryModel Logical GLSL450
462 %1 = OpTypeInt 32 0
463 %2 = OpTypeStruct %1 %3 %4 %5 %6 %7 %8 %9 %10 ; force IDs into double digits
464 %11 = OpConstant %1 42
465 )";
466   const std::string expected =
467       R"(OpCapability Shader
468 OpMemoryModel Logical GLSL450
469 %uint = OpTypeInt 32 0
470 %_struct_2 = OpTypeStruct %uint %3 %4 %5 %6 %7 %8 %9 %10
471 %uint_42 = OpConstant %uint 42
472 )";
473   EXPECT_THAT(EncodeAndDecodeSuccessfully(
474                   input, SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES),
475               expected);
476 }
477 
TEST_F(TextToBinaryTest,ShowByteOffsetsWhenRequested)478 TEST_F(TextToBinaryTest, ShowByteOffsetsWhenRequested) {
479   const std::string input = R"(
480 OpCapability Shader
481 OpMemoryModel Logical GLSL450
482 %1 = OpTypeInt 32 0
483 %2 = OpTypeVoid
484 )";
485   const std::string expected =
486       R"(OpCapability Shader ; 0x00000014
487 OpMemoryModel Logical GLSL450 ; 0x0000001c
488 %1 = OpTypeInt 32 0 ; 0x00000028
489 %2 = OpTypeVoid ; 0x00000038
490 )";
491   EXPECT_THAT(EncodeAndDecodeSuccessfully(
492                   input, SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET),
493               expected);
494 }
495 
496 // Test version string.
TEST_F(TextToBinaryTest,VersionString)497 TEST_F(TextToBinaryTest, VersionString) {
498   auto words = CompileSuccessfully("");
499   spv_text decoded_text = nullptr;
500   EXPECT_THAT(spvBinaryToText(ScopedContext().context, words.data(),
501                               words.size(), SPV_BINARY_TO_TEXT_OPTION_NONE,
502                               &decoded_text, &diagnostic),
503               Eq(SPV_SUCCESS));
504   EXPECT_EQ(nullptr, diagnostic);
505 
506   EXPECT_THAT(decoded_text->str, HasSubstr("Version: 1.0\n"))
507       << EncodeAndDecodeSuccessfully("");
508   spvTextDestroy(decoded_text);
509 }
510 
511 // Test generator string.
512 
513 // A test case for the generator string.  This allows us to
514 // test both of the 16-bit components of the generator word.
515 struct GeneratorStringCase {
516   uint16_t generator;
517   uint16_t misc;
518   std::string expected;
519 };
520 
521 using GeneratorStringTest = spvtest::TextToBinaryTestBase<
522     ::testing::TestWithParam<GeneratorStringCase>>;
523 
TEST_P(GeneratorStringTest,Sample)524 TEST_P(GeneratorStringTest, Sample) {
525   auto words = CompileSuccessfully("");
526   EXPECT_EQ(2u, SPV_INDEX_GENERATOR_NUMBER);
527   words[SPV_INDEX_GENERATOR_NUMBER] =
528       SPV_GENERATOR_WORD(GetParam().generator, GetParam().misc);
529 
530   spv_text decoded_text = nullptr;
531   EXPECT_THAT(spvBinaryToText(ScopedContext().context, words.data(),
532                               words.size(), SPV_BINARY_TO_TEXT_OPTION_NONE,
533                               &decoded_text, &diagnostic),
534               Eq(SPV_SUCCESS));
535   EXPECT_THAT(diagnostic, Eq(nullptr));
536   EXPECT_THAT(std::string(decoded_text->str), HasSubstr(GetParam().expected));
537   spvTextDestroy(decoded_text);
538 }
539 
540 INSTANTIATE_TEST_SUITE_P(GeneratorStrings, GeneratorStringTest,
541                          ::testing::ValuesIn(std::vector<GeneratorStringCase>{
542                              {SPV_GENERATOR_KHRONOS, 12, "Khronos; 12"},
543                              {SPV_GENERATOR_LUNARG, 99, "LunarG; 99"},
544                              {SPV_GENERATOR_VALVE, 1, "Valve; 1"},
545                              {SPV_GENERATOR_CODEPLAY, 65535, "Codeplay; 65535"},
546                              {SPV_GENERATOR_NVIDIA, 19, "NVIDIA; 19"},
547                              {SPV_GENERATOR_ARM, 1000, "ARM; 1000"},
548                              {SPV_GENERATOR_KHRONOS_LLVM_TRANSLATOR, 38,
549                               "Khronos LLVM/SPIR-V Translator; 38"},
550                              {SPV_GENERATOR_KHRONOS_ASSEMBLER, 2,
551                               "Khronos SPIR-V Tools Assembler; 2"},
552                              {SPV_GENERATOR_KHRONOS_GLSLANG, 1,
553                               "Khronos Glslang Reference Front End; 1"},
554                              {1000, 18, "Unknown(1000); 18"},
555                              {65535, 32767, "Unknown(65535); 32767"},
556                          }));
557 
558 // TODO(dneto): Test new instructions and enums in SPIR-V 1.3
559 
560 }  // namespace
561 }  // namespace spvtools
562