• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2018 Google 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 "source/opt/ir_builder.h"
16 
17 #include <memory>
18 #include <vector>
19 
20 #include "effcee/effcee.h"
21 #include "gtest/gtest.h"
22 #include "source/opt/basic_block.h"
23 #include "source/opt/build_module.h"
24 #include "source/opt/instruction.h"
25 #include "source/opt/type_manager.h"
26 #include "spirv-tools/libspirv.hpp"
27 
28 namespace spvtools {
29 namespace opt {
30 namespace {
31 
32 using Analysis = IRContext::Analysis;
33 using IRBuilderTest = ::testing::Test;
34 
Validate(const std::vector<uint32_t> & bin)35 bool Validate(const std::vector<uint32_t>& bin) {
36   spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
37   spv_context spvContext = spvContextCreate(target_env);
38   spv_diagnostic diagnostic = nullptr;
39   spv_const_binary_t binary = {bin.data(), bin.size()};
40   spv_result_t error = spvValidate(spvContext, &binary, &diagnostic);
41   if (error != 0) spvDiagnosticPrint(diagnostic);
42   spvDiagnosticDestroy(diagnostic);
43   spvContextDestroy(spvContext);
44   return error == 0;
45 }
46 
Match(const std::string & original,IRContext * context,bool do_validation=true)47 void Match(const std::string& original, IRContext* context,
48            bool do_validation = true) {
49   std::vector<uint32_t> bin;
50   context->module()->ToBinary(&bin, true);
51   if (do_validation) {
52     EXPECT_TRUE(Validate(bin));
53   }
54   std::string assembly;
55   SpirvTools tools(SPV_ENV_UNIVERSAL_1_2);
56   EXPECT_TRUE(
57       tools.Disassemble(bin, &assembly, SpirvTools::kDefaultDisassembleOption))
58       << "Disassembling failed for shader:\n"
59       << assembly << std::endl;
60   auto match_result = effcee::Match(assembly, original);
61   EXPECT_EQ(effcee::Result::Status::Ok, match_result.status())
62       << match_result.message() << "\nChecking result:\n"
63       << assembly;
64 }
65 
TEST_F(IRBuilderTest,TestInsnAddition)66 TEST_F(IRBuilderTest, TestInsnAddition) {
67   const std::string text = R"(
68 ; CHECK: %18 = OpLabel
69 ; CHECK: OpPhi %int %int_0 %14
70 ; CHECK: OpPhi %bool %16 %14
71 ; CHECK: OpBranch %17
72                OpCapability Shader
73           %1 = OpExtInstImport "GLSL.std.450"
74                OpMemoryModel Logical GLSL450
75                OpEntryPoint Fragment %2 "main" %3
76                OpExecutionMode %2 OriginUpperLeft
77                OpSource GLSL 330
78                OpName %2 "main"
79                OpName %4 "i"
80                OpName %3 "c"
81                OpDecorate %3 Location 0
82           %5 = OpTypeVoid
83           %6 = OpTypeFunction %5
84           %7 = OpTypeInt 32 1
85           %8 = OpTypePointer Function %7
86           %9 = OpConstant %7 0
87          %10 = OpTypeBool
88          %11 = OpTypeFloat 32
89          %12 = OpTypeVector %11 4
90          %13 = OpTypePointer Output %12
91           %3 = OpVariable %13 Output
92           %2 = OpFunction %5 None %6
93          %14 = OpLabel
94           %4 = OpVariable %8 Function
95                OpStore %4 %9
96          %15 = OpLoad %7 %4
97          %16 = OpINotEqual %10 %15 %9
98                OpSelectionMerge %17 None
99                OpBranchConditional %16 %18 %17
100          %18 = OpLabel
101                OpBranch %17
102          %17 = OpLabel
103                OpReturn
104                OpFunctionEnd
105 )";
106 
107   {
108     std::unique_ptr<IRContext> context =
109         BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
110 
111     BasicBlock* bb = context->cfg()->block(18);
112 
113     // Build managers.
114     context->get_def_use_mgr();
115     context->get_instr_block(nullptr);
116 
117     InstructionBuilder builder(context.get(), &*bb->begin());
118     Instruction* phi1 = builder.AddPhi(7, {9, 14});
119     Instruction* phi2 = builder.AddPhi(10, {16, 14});
120 
121     // Make sure the InstructionBuilder did not update the def/use manager.
122     EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr);
123     EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr);
124     EXPECT_EQ(context->get_instr_block(phi1), nullptr);
125     EXPECT_EQ(context->get_instr_block(phi2), nullptr);
126 
127     Match(text, context.get());
128   }
129 
130   {
131     std::unique_ptr<IRContext> context =
132         BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
133 
134     // Build managers.
135     context->get_def_use_mgr();
136     context->get_instr_block(nullptr);
137 
138     BasicBlock* bb = context->cfg()->block(18);
139     InstructionBuilder builder(
140         context.get(), &*bb->begin(),
141         IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
142     Instruction* phi1 = builder.AddPhi(7, {9, 14});
143     Instruction* phi2 = builder.AddPhi(10, {16, 14});
144 
145     // Make sure InstructionBuilder updated the def/use manager
146     EXPECT_NE(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr);
147     EXPECT_NE(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr);
148     EXPECT_NE(context->get_instr_block(phi1), nullptr);
149     EXPECT_NE(context->get_instr_block(phi2), nullptr);
150 
151     Match(text, context.get());
152   }
153 }
154 
TEST_F(IRBuilderTest,TestCondBranchAddition)155 TEST_F(IRBuilderTest, TestCondBranchAddition) {
156   const std::string text = R"(
157 ; CHECK: %main = OpFunction %void None %6
158 ; CHECK-NEXT: %15 = OpLabel
159 ; CHECK-NEXT: OpSelectionMerge %13 None
160 ; CHECK-NEXT: OpBranchConditional %true %14 %13
161 ; CHECK-NEXT: %14 = OpLabel
162 ; CHECK-NEXT: OpBranch %13
163 ; CHECK-NEXT: %13 = OpLabel
164 ; CHECK-NEXT: OpReturn
165                OpCapability Shader
166           %1 = OpExtInstImport "GLSL.std.450"
167                OpMemoryModel Logical GLSL450
168                OpEntryPoint Fragment %2 "main" %3
169                OpExecutionMode %2 OriginUpperLeft
170                OpSource GLSL 330
171                OpName %2 "main"
172                OpName %4 "i"
173                OpName %3 "c"
174                OpDecorate %3 Location 0
175           %5 = OpTypeVoid
176           %6 = OpTypeFunction %5
177           %7 = OpTypeBool
178           %8 = OpTypePointer Private %7
179           %9 = OpConstantTrue %7
180          %10 = OpTypeFloat 32
181          %11 = OpTypeVector %10 4
182          %12 = OpTypePointer Output %11
183           %3 = OpVariable %12 Output
184           %4 = OpVariable %8 Private
185           %2 = OpFunction %5 None %6
186          %13 = OpLabel
187                OpReturn
188                OpFunctionEnd
189 )";
190 
191   {
192     std::unique_ptr<IRContext> context =
193         BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
194 
195     Function& fn = *context->module()->begin();
196 
197     BasicBlock& bb_merge = *fn.begin();
198 
199     // TODO(1841): Handle id overflow.
200     fn.begin().InsertBefore(std::unique_ptr<BasicBlock>(
201         new BasicBlock(std::unique_ptr<Instruction>(new Instruction(
202             context.get(), spv::Op::OpLabel, 0, context->TakeNextId(), {})))));
203     BasicBlock& bb_true = *fn.begin();
204     {
205       InstructionBuilder builder(context.get(), &*bb_true.begin());
206       builder.AddBranch(bb_merge.id());
207     }
208 
209     // TODO(1841): Handle id overflow.
210     fn.begin().InsertBefore(std::unique_ptr<BasicBlock>(
211         new BasicBlock(std::unique_ptr<Instruction>(new Instruction(
212             context.get(), spv::Op::OpLabel, 0, context->TakeNextId(), {})))));
213     BasicBlock& bb_cond = *fn.begin();
214 
215     InstructionBuilder builder(context.get(), &bb_cond);
216     // This also test consecutive instruction insertion: merge selection +
217     // branch.
218     builder.AddConditionalBranch(9, bb_true.id(), bb_merge.id(), bb_merge.id());
219 
220     Match(text, context.get());
221   }
222 }
223 
TEST_F(IRBuilderTest,AddSelect)224 TEST_F(IRBuilderTest, AddSelect) {
225   const std::string text = R"(
226 ; CHECK: [[bool:%\w+]] = OpTypeBool
227 ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0
228 ; CHECK: [[true:%\w+]] = OpConstantTrue [[bool]]
229 ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0
230 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1
231 ; CHECK: OpSelect [[uint]] [[true]] [[u0]] [[u1]]
232 OpCapability Kernel
233 OpCapability Linkage
234 OpMemoryModel Logical OpenCL
235 %1 = OpTypeVoid
236 %2 = OpTypeBool
237 %3 = OpTypeInt 32 0
238 %4 = OpConstantTrue %2
239 %5 = OpConstant %3 0
240 %6 = OpConstant %3 1
241 %7 = OpTypeFunction %1
242 %8 = OpFunction %1 None %7
243 %9 = OpLabel
244 OpReturn
245 OpFunctionEnd
246 )";
247 
248   std::unique_ptr<IRContext> context =
249       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
250   EXPECT_NE(nullptr, context);
251 
252   InstructionBuilder builder(context.get(),
253                              &*context->module()->begin()->begin()->begin());
254   EXPECT_NE(nullptr, builder.AddSelect(3u, 4u, 5u, 6u));
255 
256   Match(text, context.get());
257 }
258 
TEST_F(IRBuilderTest,AddVariable)259 TEST_F(IRBuilderTest, AddVariable) {
260   // Use Private beacuse its' enun is 7 which is higher
261   // than the ID limit.
262   const std::string text = R"(
263 ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0
264 ; CHECK: [[ptr:%\w+]] = OpTypePointer Private [[uint]]
265 ; CHECK: [[var:%\w+]] = OpVariable [[ptr]] Private
266 ; CHECK: OpTypeFloat
267 OpCapability Kernel
268 OpCapability VectorComputeINTEL
269 OpCapability Linkage
270 OpExtension "SPV_INTEL_vector_compute"
271 OpMemoryModel Logical OpenCL
272 %1 = OpTypeInt 32 0
273 %2 = OpTypePointer Private %1
274 %3 = OpTypeFloat 32
275 )";
276 
277   std::unique_ptr<IRContext> context =
278       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
279   EXPECT_NE(nullptr, context) << text;
280 
281   auto* float_ty = context->get_def_use_mgr()->GetDef(3);
282   InstructionBuilder builder(context.get(), float_ty);
283   auto* var = builder.AddVariable(2u, uint32_t(spv::StorageClass::Private));
284   EXPECT_NE(nullptr, var);
285 
286   context->get_def_use_mgr()->AnalyzeInstDefUse(var);  // should not assert
287 
288   Match(text, context.get());
289 }
290 
TEST_F(IRBuilderTest,AddCompositeConstruct)291 TEST_F(IRBuilderTest, AddCompositeConstruct) {
292   const std::string text = R"(
293 ; CHECK: [[uint:%\w+]] = OpTypeInt
294 ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0
295 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1
296 ; CHECK: [[struct:%\w+]] = OpTypeStruct [[uint]] [[uint]] [[uint]] [[uint]]
297 ; CHECK: OpCompositeConstruct [[struct]] [[u0]] [[u1]] [[u1]] [[u0]]
298 OpCapability Kernel
299 OpCapability Linkage
300 OpMemoryModel Logical OpenCL
301 %1 = OpTypeVoid
302 %2 = OpTypeInt 32 0
303 %3 = OpConstant %2 0
304 %4 = OpConstant %2 1
305 %5 = OpTypeStruct %2 %2 %2 %2
306 %6 = OpTypeFunction %1
307 %7 = OpFunction %1 None %6
308 %8 = OpLabel
309 OpReturn
310 OpFunctionEnd
311 )";
312 
313   std::unique_ptr<IRContext> context =
314       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
315   EXPECT_NE(nullptr, context);
316 
317   InstructionBuilder builder(context.get(),
318                              &*context->module()->begin()->begin()->begin());
319   std::vector<uint32_t> ids = {3u, 4u, 4u, 3u};
320   EXPECT_NE(nullptr, builder.AddCompositeConstruct(5u, ids));
321 
322   Match(text, context.get());
323 }
324 
TEST_F(IRBuilderTest,ConstantAdder)325 TEST_F(IRBuilderTest, ConstantAdder) {
326   const std::string text = R"(
327 ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0
328 ; CHECK: OpConstant [[uint]] 13
329 ; CHECK: [[sint:%\w+]] = OpTypeInt 32 1
330 ; CHECK: OpConstant [[sint]] -1
331 ; CHECK: OpConstant [[uint]] 1
332 ; CHECK: OpConstant [[sint]] 34
333 ; CHECK: OpConstant [[uint]] 0
334 ; CHECK: OpConstant [[sint]] 0
335 OpCapability Shader
336 OpCapability Linkage
337 OpMemoryModel Logical GLSL450
338 %1 = OpTypeVoid
339 %2 = OpTypeFunction %1
340 %3 = OpFunction %1 None %2
341 %4 = OpLabel
342 OpReturn
343 OpFunctionEnd
344 )";
345 
346   std::unique_ptr<IRContext> context =
347       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
348   EXPECT_NE(nullptr, context);
349 
350   InstructionBuilder builder(context.get(),
351                              &*context->module()->begin()->begin()->begin());
352   EXPECT_NE(nullptr, builder.GetUintConstant(13));
353   EXPECT_NE(nullptr, builder.GetSintConstant(-1));
354 
355   // Try adding the same constants again to make sure they aren't added.
356   EXPECT_NE(nullptr, builder.GetUintConstant(13));
357   EXPECT_NE(nullptr, builder.GetSintConstant(-1));
358 
359   // Try adding different constants to make sure the type is reused.
360   EXPECT_NE(nullptr, builder.GetUintConstant(1));
361   EXPECT_NE(nullptr, builder.GetSintConstant(34));
362 
363   // Try adding 0 as both signed and unsigned.
364   EXPECT_NE(nullptr, builder.GetUintConstant(0));
365   EXPECT_NE(nullptr, builder.GetSintConstant(0));
366 
367   Match(text, context.get());
368 }
369 
TEST_F(IRBuilderTest,ConstantAdderTypeAlreadyExists)370 TEST_F(IRBuilderTest, ConstantAdderTypeAlreadyExists) {
371   const std::string text = R"(
372 ; CHECK: OpConstant %uint 13
373 ; CHECK: OpConstant %int -1
374 ; CHECK: OpConstant %uint 1
375 ; CHECK: OpConstant %int 34
376 ; CHECK: OpConstant %uint 0
377 ; CHECK: OpConstant %int 0
378 OpCapability Shader
379 OpCapability Linkage
380 OpMemoryModel Logical GLSL450
381 %1 = OpTypeVoid
382 %uint = OpTypeInt 32 0
383 %int = OpTypeInt 32 1
384 %4 = OpTypeFunction %1
385 %5 = OpFunction %1 None %4
386 %6 = OpLabel
387 OpReturn
388 OpFunctionEnd
389 )";
390 
391   std::unique_ptr<IRContext> context =
392       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
393   EXPECT_NE(nullptr, context);
394 
395   InstructionBuilder builder(context.get(),
396                              &*context->module()->begin()->begin()->begin());
397   Instruction* const_1 = builder.GetUintConstant(13);
398   Instruction* const_2 = builder.GetSintConstant(-1);
399 
400   EXPECT_NE(nullptr, const_1);
401   EXPECT_NE(nullptr, const_2);
402 
403   // Try adding the same constants again to make sure they aren't added.
404   EXPECT_EQ(const_1, builder.GetUintConstant(13));
405   EXPECT_EQ(const_2, builder.GetSintConstant(-1));
406 
407   Instruction* const_3 = builder.GetUintConstant(1);
408   Instruction* const_4 = builder.GetSintConstant(34);
409 
410   // Try adding different constants to make sure the type is reused.
411   EXPECT_NE(nullptr, const_3);
412   EXPECT_NE(nullptr, const_4);
413 
414   Instruction* const_5 = builder.GetUintConstant(0);
415   Instruction* const_6 = builder.GetSintConstant(0);
416 
417   // Try adding 0 as both signed and unsigned.
418   EXPECT_NE(nullptr, const_5);
419   EXPECT_NE(nullptr, const_6);
420 
421   // They have the same value but different types so should be unique.
422   EXPECT_NE(const_5, const_6);
423 
424   // Check the types are correct.
425   uint32_t type_id_unsigned = const_1->GetSingleWordOperand(0);
426   uint32_t type_id_signed = const_2->GetSingleWordOperand(0);
427 
428   EXPECT_NE(type_id_unsigned, type_id_signed);
429 
430   EXPECT_EQ(const_3->GetSingleWordOperand(0), type_id_unsigned);
431   EXPECT_EQ(const_5->GetSingleWordOperand(0), type_id_unsigned);
432 
433   EXPECT_EQ(const_4->GetSingleWordOperand(0), type_id_signed);
434   EXPECT_EQ(const_6->GetSingleWordOperand(0), type_id_signed);
435 
436   Match(text, context.get());
437 }
438 
TEST_F(IRBuilderTest,AccelerationStructureNV)439 TEST_F(IRBuilderTest, AccelerationStructureNV) {
440   const std::string text = R"(
441 ; CHECK: OpTypeAccelerationStructureKHR
442 OpCapability Shader
443 OpCapability RayTracingNV
444 OpExtension "SPV_NV_ray_tracing"
445 OpMemoryModel Logical GLSL450
446 OpEntryPoint Fragment %8 "main"
447 OpExecutionMode %8 OriginUpperLeft
448 %1 = OpTypeVoid
449 %2 = OpTypeBool
450 %3 = OpTypeAccelerationStructureNV
451 %7 = OpTypeFunction %1
452 %8 = OpFunction %1 None %7
453 %9 = OpLabel
454 OpReturn
455 OpFunctionEnd
456 )";
457 
458   std::unique_ptr<IRContext> context =
459       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
460   EXPECT_NE(nullptr, context);
461 
462   InstructionBuilder builder(context.get(),
463                              &*context->module()->begin()->begin()->begin());
464   Match(text, context.get());
465 }
466 
467 }  // namespace
468 }  // namespace opt
469 }  // namespace spvtools
470