• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <algorithm>
16 #include <cassert>
17 #include <functional>
18 #include <iostream>
19 #include <iterator>
20 #include <map>
21 #include <string>
22 #include <tuple>
23 #include <unordered_map>
24 #include <unordered_set>
25 #include <utility>
26 #include <vector>
27 
28 #include "source/cfa.h"
29 #include "source/opcode.h"
30 #include "source/spirv_target_env.h"
31 #include "source/spirv_validator_options.h"
32 #include "source/val/basic_block.h"
33 #include "source/val/construct.h"
34 #include "source/val/function.h"
35 #include "source/val/validate.h"
36 #include "source/val/validation_state.h"
37 
38 namespace spvtools {
39 namespace val {
40 namespace {
41 
ValidatePhi(ValidationState_t & _,const Instruction * inst)42 spv_result_t ValidatePhi(ValidationState_t& _, const Instruction* inst) {
43   auto block = inst->block();
44   size_t num_in_ops = inst->words().size() - 3;
45   if (num_in_ops % 2 != 0) {
46     return _.diag(SPV_ERROR_INVALID_ID, inst)
47            << "OpPhi does not have an equal number of incoming values and "
48               "basic blocks.";
49   }
50 
51   if (_.IsVoidType(inst->type_id())) {
52     return _.diag(SPV_ERROR_INVALID_DATA, inst)
53            << "OpPhi must not have void result type";
54   }
55   if (_.IsPointerType(inst->type_id()) &&
56       _.addressing_model() == SpvAddressingModelLogical) {
57     if (!_.features().variable_pointers &&
58         !_.features().variable_pointers_storage_buffer) {
59       return _.diag(SPV_ERROR_INVALID_DATA, inst)
60              << "Using pointers with OpPhi requires capability "
61              << "VariablePointers or VariablePointersStorageBuffer";
62     }
63   }
64 
65   const Instruction* type_inst = _.FindDef(inst->type_id());
66   assert(type_inst);
67   const SpvOp type_opcode = type_inst->opcode();
68 
69   if (!_.options()->before_hlsl_legalization) {
70     if (type_opcode == SpvOpTypeSampledImage ||
71         (_.HasCapability(SpvCapabilityShader) &&
72          (type_opcode == SpvOpTypeImage || type_opcode == SpvOpTypeSampler))) {
73       return _.diag(SPV_ERROR_INVALID_ID, inst)
74              << "Result type cannot be Op" << spvOpcodeString(type_opcode);
75     }
76   }
77 
78   // Create a uniqued vector of predecessor ids for comparison against
79   // incoming values. OpBranchConditional %cond %label %label produces two
80   // predecessors in the CFG.
81   std::vector<uint32_t> pred_ids;
82   std::transform(block->predecessors()->begin(), block->predecessors()->end(),
83                  std::back_inserter(pred_ids),
84                  [](const BasicBlock* b) { return b->id(); });
85   std::sort(pred_ids.begin(), pred_ids.end());
86   pred_ids.erase(std::unique(pred_ids.begin(), pred_ids.end()), pred_ids.end());
87 
88   size_t num_edges = num_in_ops / 2;
89   if (num_edges != pred_ids.size()) {
90     return _.diag(SPV_ERROR_INVALID_ID, inst)
91            << "OpPhi's number of incoming blocks (" << num_edges
92            << ") does not match block's predecessor count ("
93            << block->predecessors()->size() << ").";
94   }
95 
96   std::unordered_set<uint32_t> observed_predecessors;
97 
98   for (size_t i = 3; i < inst->words().size(); ++i) {
99     auto inc_id = inst->word(i);
100     if (i % 2 == 1) {
101       // Incoming value type must match the phi result type.
102       auto inc_type_id = _.GetTypeId(inc_id);
103       if (inst->type_id() != inc_type_id) {
104         return _.diag(SPV_ERROR_INVALID_ID, inst)
105                << "OpPhi's result type <id> " << _.getIdName(inst->type_id())
106                << " does not match incoming value <id> " << _.getIdName(inc_id)
107                << " type <id> " << _.getIdName(inc_type_id) << ".";
108       }
109     } else {
110       if (_.GetIdOpcode(inc_id) != SpvOpLabel) {
111         return _.diag(SPV_ERROR_INVALID_ID, inst)
112                << "OpPhi's incoming basic block <id> " << _.getIdName(inc_id)
113                << " is not an OpLabel.";
114       }
115 
116       // Incoming basic block must be an immediate predecessor of the phi's
117       // block.
118       if (!std::binary_search(pred_ids.begin(), pred_ids.end(), inc_id)) {
119         return _.diag(SPV_ERROR_INVALID_ID, inst)
120                << "OpPhi's incoming basic block <id> " << _.getIdName(inc_id)
121                << " is not a predecessor of <id> " << _.getIdName(block->id())
122                << ".";
123       }
124 
125       // We must not have already seen this predecessor as one of the phi's
126       // operands.
127       if (observed_predecessors.count(inc_id) != 0) {
128         return _.diag(SPV_ERROR_INVALID_ID, inst)
129                << "OpPhi references incoming basic block <id> "
130                << _.getIdName(inc_id) << " multiple times.";
131       }
132 
133       // Note the fact that we have now observed this predecessor.
134       observed_predecessors.insert(inc_id);
135     }
136   }
137 
138   return SPV_SUCCESS;
139 }
140 
ValidateBranch(ValidationState_t & _,const Instruction * inst)141 spv_result_t ValidateBranch(ValidationState_t& _, const Instruction* inst) {
142   // target operands must be OpLabel
143   const auto id = inst->GetOperandAs<uint32_t>(0);
144   const auto target = _.FindDef(id);
145   if (!target || SpvOpLabel != target->opcode()) {
146     return _.diag(SPV_ERROR_INVALID_ID, inst)
147            << "'Target Label' operands for OpBranch must be the ID "
148               "of an OpLabel instruction";
149   }
150 
151   return SPV_SUCCESS;
152 }
153 
ValidateBranchConditional(ValidationState_t & _,const Instruction * inst)154 spv_result_t ValidateBranchConditional(ValidationState_t& _,
155                                        const Instruction* inst) {
156   // num_operands is either 3 or 5 --- if 5, the last two need to be literal
157   // integers
158   const auto num_operands = inst->operands().size();
159   if (num_operands != 3 && num_operands != 5) {
160     return _.diag(SPV_ERROR_INVALID_ID, inst)
161            << "OpBranchConditional requires either 3 or 5 parameters";
162   }
163 
164   // grab the condition operand and check that it is a bool
165   const auto cond_id = inst->GetOperandAs<uint32_t>(0);
166   const auto cond_op = _.FindDef(cond_id);
167   if (!cond_op || !cond_op->type_id() ||
168       !_.IsBoolScalarType(cond_op->type_id())) {
169     return _.diag(SPV_ERROR_INVALID_ID, inst) << "Condition operand for "
170                                                  "OpBranchConditional must be "
171                                                  "of boolean type";
172   }
173 
174   // target operands must be OpLabel
175   // note that we don't need to check that the target labels are in the same
176   // function,
177   // PerformCfgChecks already checks for that
178   const auto true_id = inst->GetOperandAs<uint32_t>(1);
179   const auto true_target = _.FindDef(true_id);
180   if (!true_target || SpvOpLabel != true_target->opcode()) {
181     return _.diag(SPV_ERROR_INVALID_ID, inst)
182            << "The 'True Label' operand for OpBranchConditional must be the "
183               "ID of an OpLabel instruction";
184   }
185 
186   const auto false_id = inst->GetOperandAs<uint32_t>(2);
187   const auto false_target = _.FindDef(false_id);
188   if (!false_target || SpvOpLabel != false_target->opcode()) {
189     return _.diag(SPV_ERROR_INVALID_ID, inst)
190            << "The 'False Label' operand for OpBranchConditional must be the "
191               "ID of an OpLabel instruction";
192   }
193 
194   return SPV_SUCCESS;
195 }
196 
ValidateSwitch(ValidationState_t & _,const Instruction * inst)197 spv_result_t ValidateSwitch(ValidationState_t& _, const Instruction* inst) {
198   const auto num_operands = inst->operands().size();
199   // At least two operands (selector, default), any more than that are
200   // literal/target.
201 
202   // target operands must be OpLabel
203   for (size_t i = 2; i < num_operands; i += 2) {
204     // literal, id
205     const auto id = inst->GetOperandAs<uint32_t>(i + 1);
206     const auto target = _.FindDef(id);
207     if (!target || SpvOpLabel != target->opcode()) {
208       return _.diag(SPV_ERROR_INVALID_ID, inst)
209              << "'Target Label' operands for OpSwitch must be IDs of an "
210                 "OpLabel instruction";
211     }
212   }
213 
214   return SPV_SUCCESS;
215 }
216 
ValidateReturnValue(ValidationState_t & _,const Instruction * inst)217 spv_result_t ValidateReturnValue(ValidationState_t& _,
218                                  const Instruction* inst) {
219   const auto value_id = inst->GetOperandAs<uint32_t>(0);
220   const auto value = _.FindDef(value_id);
221   if (!value || !value->type_id()) {
222     return _.diag(SPV_ERROR_INVALID_ID, inst)
223            << "OpReturnValue Value <id> '" << _.getIdName(value_id)
224            << "' does not represent a value.";
225   }
226   auto value_type = _.FindDef(value->type_id());
227   if (!value_type || SpvOpTypeVoid == value_type->opcode()) {
228     return _.diag(SPV_ERROR_INVALID_ID, inst)
229            << "OpReturnValue value's type <id> '"
230            << _.getIdName(value->type_id()) << "' is missing or void.";
231   }
232 
233   const bool uses_variable_pointer =
234       _.features().variable_pointers ||
235       _.features().variable_pointers_storage_buffer;
236 
237   if (_.addressing_model() == SpvAddressingModelLogical &&
238       SpvOpTypePointer == value_type->opcode() && !uses_variable_pointer &&
239       !_.options()->relax_logical_pointer) {
240     return _.diag(SPV_ERROR_INVALID_ID, inst)
241            << "OpReturnValue value's type <id> '"
242            << _.getIdName(value->type_id())
243            << "' is a pointer, which is invalid in the Logical addressing "
244               "model.";
245   }
246 
247   const auto function = inst->function();
248   const auto return_type = _.FindDef(function->GetResultTypeId());
249   if (!return_type || return_type->id() != value_type->id()) {
250     return _.diag(SPV_ERROR_INVALID_ID, inst)
251            << "OpReturnValue Value <id> '" << _.getIdName(value_id)
252            << "'s type does not match OpFunction's return type.";
253   }
254 
255   return SPV_SUCCESS;
256 }
257 
ValidateLoopMerge(ValidationState_t & _,const Instruction * inst)258 spv_result_t ValidateLoopMerge(ValidationState_t& _, const Instruction* inst) {
259   const auto merge_id = inst->GetOperandAs<uint32_t>(0);
260   const auto merge = _.FindDef(merge_id);
261   if (!merge || merge->opcode() != SpvOpLabel) {
262     return _.diag(SPV_ERROR_INVALID_ID, inst)
263            << "Merge Block " << _.getIdName(merge_id) << " must be an OpLabel";
264   }
265   if (merge_id == inst->block()->id()) {
266     return _.diag(SPV_ERROR_INVALID_ID, inst)
267            << "Merge Block may not be the block containing the OpLoopMerge\n";
268   }
269 
270   const auto continue_id = inst->GetOperandAs<uint32_t>(1);
271   const auto continue_target = _.FindDef(continue_id);
272   if (!continue_target || continue_target->opcode() != SpvOpLabel) {
273     return _.diag(SPV_ERROR_INVALID_ID, inst)
274            << "Continue Target " << _.getIdName(continue_id)
275            << " must be an OpLabel";
276   }
277 
278   if (merge_id == continue_id) {
279     return _.diag(SPV_ERROR_INVALID_ID, inst)
280            << "Merge Block and Continue Target must be different ids";
281   }
282 
283   const auto loop_control = inst->GetOperandAs<uint32_t>(2);
284   if ((loop_control >> SpvLoopControlUnrollShift) & 0x1 &&
285       (loop_control >> SpvLoopControlDontUnrollShift) & 0x1) {
286     return _.diag(SPV_ERROR_INVALID_DATA, inst)
287            << "Unroll and DontUnroll loop controls must not both be specified";
288   }
289   if ((loop_control >> SpvLoopControlDontUnrollShift) & 0x1 &&
290       (loop_control >> SpvLoopControlPeelCountShift) & 0x1) {
291     return _.diag(SPV_ERROR_INVALID_DATA, inst) << "PeelCount and DontUnroll "
292                                                    "loop controls must not "
293                                                    "both be specified";
294   }
295   if ((loop_control >> SpvLoopControlDontUnrollShift) & 0x1 &&
296       (loop_control >> SpvLoopControlPartialCountShift) & 0x1) {
297     return _.diag(SPV_ERROR_INVALID_DATA, inst) << "PartialCount and "
298                                                    "DontUnroll loop controls "
299                                                    "must not both be specified";
300   }
301 
302   uint32_t operand = 3;
303   if ((loop_control >> SpvLoopControlDependencyLengthShift) & 0x1) {
304     ++operand;
305   }
306   if ((loop_control >> SpvLoopControlMinIterationsShift) & 0x1) {
307     ++operand;
308   }
309   if ((loop_control >> SpvLoopControlMaxIterationsShift) & 0x1) {
310     ++operand;
311   }
312   if ((loop_control >> SpvLoopControlIterationMultipleShift) & 0x1) {
313     if (inst->operands().size() < operand ||
314         inst->GetOperandAs<uint32_t>(operand) == 0) {
315       return _.diag(SPV_ERROR_INVALID_DATA, inst) << "IterationMultiple loop "
316                                                      "control operand must be "
317                                                      "greater than zero";
318     }
319     ++operand;
320   }
321   if ((loop_control >> SpvLoopControlPeelCountShift) & 0x1) {
322     ++operand;
323   }
324   if ((loop_control >> SpvLoopControlPartialCountShift) & 0x1) {
325     ++operand;
326   }
327 
328   // That the right number of operands is present is checked by the parser. The
329   // above code tracks operands for expanded validation checking in the future.
330 
331   return SPV_SUCCESS;
332 }
333 
334 }  // namespace
335 
printDominatorList(const BasicBlock & b)336 void printDominatorList(const BasicBlock& b) {
337   std::cout << b.id() << " is dominated by: ";
338   const BasicBlock* bb = &b;
339   while (bb->immediate_dominator() != bb) {
340     bb = bb->immediate_dominator();
341     std::cout << bb->id() << " ";
342   }
343 }
344 
345 #define CFG_ASSERT(ASSERT_FUNC, TARGET) \
346   if (spv_result_t rcode = ASSERT_FUNC(_, TARGET)) return rcode
347 
FirstBlockAssert(ValidationState_t & _,uint32_t target)348 spv_result_t FirstBlockAssert(ValidationState_t& _, uint32_t target) {
349   if (_.current_function().IsFirstBlock(target)) {
350     return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(_.current_function().id()))
351            << "First block " << _.getIdName(target) << " of function "
352            << _.getIdName(_.current_function().id()) << " is targeted by block "
353            << _.getIdName(_.current_function().current_block()->id());
354   }
355   return SPV_SUCCESS;
356 }
357 
MergeBlockAssert(ValidationState_t & _,uint32_t merge_block)358 spv_result_t MergeBlockAssert(ValidationState_t& _, uint32_t merge_block) {
359   if (_.current_function().IsBlockType(merge_block, kBlockTypeMerge)) {
360     return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(_.current_function().id()))
361            << "Block " << _.getIdName(merge_block)
362            << " is already a merge block for another header";
363   }
364   return SPV_SUCCESS;
365 }
366 
367 /// Update the continue construct's exit blocks once the backedge blocks are
368 /// identified in the CFG.
UpdateContinueConstructExitBlocks(Function & function,const std::vector<std::pair<uint32_t,uint32_t>> & back_edges)369 void UpdateContinueConstructExitBlocks(
370     Function& function,
371     const std::vector<std::pair<uint32_t, uint32_t>>& back_edges) {
372   auto& constructs = function.constructs();
373   // TODO(umar): Think of a faster way to do this
374   for (auto& edge : back_edges) {
375     uint32_t back_edge_block_id;
376     uint32_t loop_header_block_id;
377     std::tie(back_edge_block_id, loop_header_block_id) = edge;
378     auto is_this_header = [=](Construct& c) {
379       return c.type() == ConstructType::kLoop &&
380              c.entry_block()->id() == loop_header_block_id;
381     };
382 
383     for (auto construct : constructs) {
384       if (is_this_header(construct)) {
385         Construct* continue_construct =
386             construct.corresponding_constructs().back();
387         assert(continue_construct->type() == ConstructType::kContinue);
388 
389         BasicBlock* back_edge_block;
390         std::tie(back_edge_block, std::ignore) =
391             function.GetBlock(back_edge_block_id);
392         continue_construct->set_exit(back_edge_block);
393       }
394     }
395   }
396 }
397 
ConstructNames(ConstructType type)398 std::tuple<std::string, std::string, std::string> ConstructNames(
399     ConstructType type) {
400   std::string construct_name, header_name, exit_name;
401 
402   switch (type) {
403     case ConstructType::kSelection:
404       construct_name = "selection";
405       header_name = "selection header";
406       exit_name = "merge block";
407       break;
408     case ConstructType::kLoop:
409       construct_name = "loop";
410       header_name = "loop header";
411       exit_name = "merge block";
412       break;
413     case ConstructType::kContinue:
414       construct_name = "continue";
415       header_name = "continue target";
416       exit_name = "back-edge block";
417       break;
418     case ConstructType::kCase:
419       construct_name = "case";
420       header_name = "case entry block";
421       exit_name = "case exit block";
422       break;
423     default:
424       assert(1 == 0 && "Not defined type");
425   }
426 
427   return std::make_tuple(construct_name, header_name, exit_name);
428 }
429 
430 /// Constructs an error message for construct validation errors
ConstructErrorString(const Construct & construct,const std::string & header_string,const std::string & exit_string,const std::string & dominate_text)431 std::string ConstructErrorString(const Construct& construct,
432                                  const std::string& header_string,
433                                  const std::string& exit_string,
434                                  const std::string& dominate_text) {
435   std::string construct_name, header_name, exit_name;
436   std::tie(construct_name, header_name, exit_name) =
437       ConstructNames(construct.type());
438 
439   // TODO(umar): Add header block for continue constructs to error message
440   return "The " + construct_name + " construct with the " + header_name + " " +
441          header_string + " " + dominate_text + " the " + exit_name + " " +
442          exit_string;
443 }
444 
445 // Finds the fall through case construct of |target_block| and records it in
446 // |case_fall_through|. Returns SPV_ERROR_INVALID_CFG if the case construct
447 // headed by |target_block| branches to multiple case constructs.
FindCaseFallThrough(ValidationState_t & _,BasicBlock * target_block,uint32_t * case_fall_through,const BasicBlock * merge,const std::unordered_set<uint32_t> & case_targets,Function * function)448 spv_result_t FindCaseFallThrough(
449     ValidationState_t& _, BasicBlock* target_block, uint32_t* case_fall_through,
450     const BasicBlock* merge, const std::unordered_set<uint32_t>& case_targets,
451     Function* function) {
452   std::vector<BasicBlock*> stack;
453   stack.push_back(target_block);
454   std::unordered_set<const BasicBlock*> visited;
455   bool target_reachable = target_block->reachable();
456   int target_depth = function->GetBlockDepth(target_block);
457   while (!stack.empty()) {
458     auto block = stack.back();
459     stack.pop_back();
460 
461     if (block == merge) continue;
462 
463     if (!visited.insert(block).second) continue;
464 
465     if (target_reachable && block->reachable() &&
466         target_block->dominates(*block)) {
467       // Still in the case construct.
468       for (auto successor : *block->successors()) {
469         stack.push_back(successor);
470       }
471     } else {
472       // Exiting the case construct to non-merge block.
473       if (!case_targets.count(block->id())) {
474         int depth = function->GetBlockDepth(block);
475         if ((depth < target_depth) ||
476             (depth == target_depth && block->is_type(kBlockTypeContinue))) {
477           continue;
478         }
479 
480         return _.diag(SPV_ERROR_INVALID_CFG, target_block->label())
481                << "Case construct that targets "
482                << _.getIdName(target_block->id())
483                << " has invalid branch to block " << _.getIdName(block->id())
484                << " (not another case construct, corresponding merge, outer "
485                   "loop merge or outer loop continue)";
486       }
487 
488       if (*case_fall_through == 0u) {
489         if (target_block != block) {
490           *case_fall_through = block->id();
491         }
492       } else if (*case_fall_through != block->id()) {
493         // Case construct has at most one branch to another case construct.
494         return _.diag(SPV_ERROR_INVALID_CFG, target_block->label())
495                << "Case construct that targets "
496                << _.getIdName(target_block->id())
497                << " has branches to multiple other case construct targets "
498                << _.getIdName(*case_fall_through) << " and "
499                << _.getIdName(block->id());
500       }
501     }
502   }
503 
504   return SPV_SUCCESS;
505 }
506 
StructuredSwitchChecks(ValidationState_t & _,Function * function,const Instruction * switch_inst,const BasicBlock * header,const BasicBlock * merge)507 spv_result_t StructuredSwitchChecks(ValidationState_t& _, Function* function,
508                                     const Instruction* switch_inst,
509                                     const BasicBlock* header,
510                                     const BasicBlock* merge) {
511   std::unordered_set<uint32_t> case_targets;
512   for (uint32_t i = 1; i < switch_inst->operands().size(); i += 2) {
513     uint32_t target = switch_inst->GetOperandAs<uint32_t>(i);
514     if (target != merge->id()) case_targets.insert(target);
515   }
516   // Tracks how many times each case construct is targeted by another case
517   // construct.
518   std::map<uint32_t, uint32_t> num_fall_through_targeted;
519   uint32_t default_case_fall_through = 0u;
520   uint32_t default_target = switch_inst->GetOperandAs<uint32_t>(1u);
521   bool default_appears_multiple_times = false;
522   for (uint32_t i = 3; i < switch_inst->operands().size(); i += 2) {
523     if (default_target == switch_inst->GetOperandAs<uint32_t>(i)) {
524       default_appears_multiple_times = true;
525       break;
526     }
527   }
528   std::unordered_map<uint32_t, uint32_t> seen_to_fall_through;
529   for (uint32_t i = 1; i < switch_inst->operands().size(); i += 2) {
530     uint32_t target = switch_inst->GetOperandAs<uint32_t>(i);
531     if (target == merge->id()) continue;
532 
533     uint32_t case_fall_through = 0u;
534     auto seen_iter = seen_to_fall_through.find(target);
535     if (seen_iter == seen_to_fall_through.end()) {
536       const auto target_block = function->GetBlock(target).first;
537       // OpSwitch must dominate all its case constructs.
538       if (header->reachable() && target_block->reachable() &&
539           !header->dominates(*target_block)) {
540         return _.diag(SPV_ERROR_INVALID_CFG, header->label())
541                << "Selection header " << _.getIdName(header->id())
542                << " does not dominate its case construct "
543                << _.getIdName(target);
544       }
545 
546       if (auto error = FindCaseFallThrough(_, target_block, &case_fall_through,
547                                            merge, case_targets, function)) {
548         return error;
549       }
550 
551       // Track how many time the fall through case has been targeted.
552       if (case_fall_through != 0u) {
553         auto where = num_fall_through_targeted.lower_bound(case_fall_through);
554         if (where == num_fall_through_targeted.end() ||
555             where->first != case_fall_through) {
556           num_fall_through_targeted.insert(
557               where, std::make_pair(case_fall_through, 1));
558         } else {
559           where->second++;
560         }
561       }
562       seen_to_fall_through.insert(std::make_pair(target, case_fall_through));
563     } else {
564       case_fall_through = seen_iter->second;
565     }
566 
567     if (case_fall_through == default_target &&
568         !default_appears_multiple_times) {
569       case_fall_through = default_case_fall_through;
570     }
571     if (case_fall_through != 0u) {
572       bool is_default = i == 1;
573       if (is_default) {
574         default_case_fall_through = case_fall_through;
575       } else {
576         // Allow code like:
577         // case x:
578         // case y:
579         //   ...
580         // case z:
581         //
582         // Where x and y target the same block and fall through to z.
583         uint32_t j = i;
584         while ((j + 2 < switch_inst->operands().size()) &&
585                target == switch_inst->GetOperandAs<uint32_t>(j + 2)) {
586           j += 2;
587         }
588         // If Target T1 branches to Target T2, or if Target T1 branches to the
589         // Default target and the Default target branches to Target T2, then T1
590         // must immediately precede T2 in the list of OpSwitch Target operands.
591         if ((switch_inst->operands().size() < j + 2) ||
592             (case_fall_through != switch_inst->GetOperandAs<uint32_t>(j + 2))) {
593           return _.diag(SPV_ERROR_INVALID_CFG, switch_inst)
594                  << "Case construct that targets " << _.getIdName(target)
595                  << " has branches to the case construct that targets "
596                  << _.getIdName(case_fall_through)
597                  << ", but does not immediately precede it in the "
598                     "OpSwitch's target list";
599         }
600       }
601     }
602   }
603 
604   // Each case construct must be branched to by at most one other case
605   // construct.
606   for (const auto& pair : num_fall_through_targeted) {
607     if (pair.second > 1) {
608       return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(pair.first))
609              << "Multiple case constructs have branches to the case construct "
610                 "that targets "
611              << _.getIdName(pair.first);
612     }
613   }
614 
615   return SPV_SUCCESS;
616 }
617 
618 // Validates that all CFG divergences (i.e. conditional branch or switch) are
619 // structured correctly. Either divergence is preceded by a merge instruction
620 // or the divergence introduces at most one unseen label.
ValidateStructuredSelections(ValidationState_t & _,const std::vector<const BasicBlock * > & postorder)621 spv_result_t ValidateStructuredSelections(
622     ValidationState_t& _, const std::vector<const BasicBlock*>& postorder) {
623   std::unordered_set<uint32_t> seen;
624   for (auto iter = postorder.rbegin(); iter != postorder.rend(); ++iter) {
625     const auto* block = *iter;
626     const auto* terminator = block->terminator();
627     if (!terminator) continue;
628     const auto index = terminator - &_.ordered_instructions()[0];
629     auto* merge = &_.ordered_instructions()[index - 1];
630     // Marks merges and continues as seen.
631     if (merge->opcode() == SpvOpSelectionMerge) {
632       seen.insert(merge->GetOperandAs<uint32_t>(0));
633     } else if (merge->opcode() == SpvOpLoopMerge) {
634       seen.insert(merge->GetOperandAs<uint32_t>(0));
635       seen.insert(merge->GetOperandAs<uint32_t>(1));
636     } else {
637       // Only track the pointer if it is a merge instruction.
638       merge = nullptr;
639     }
640 
641     // Skip unreachable blocks.
642     if (!block->reachable()) continue;
643 
644     if (terminator->opcode() == SpvOpBranchConditional) {
645       const auto true_label = terminator->GetOperandAs<uint32_t>(1);
646       const auto false_label = terminator->GetOperandAs<uint32_t>(2);
647       // Mark the upcoming blocks as seen now, but only error out if this block
648       // was missing a merge instruction and both labels hadn't been seen
649       // previously.
650       const bool both_unseen =
651           seen.insert(true_label).second && seen.insert(false_label).second;
652       if (!merge && both_unseen) {
653         return _.diag(SPV_ERROR_INVALID_CFG, terminator)
654                << "Selection must be structured";
655       }
656     } else if (terminator->opcode() == SpvOpSwitch) {
657       if (!merge) {
658         return _.diag(SPV_ERROR_INVALID_CFG, terminator)
659                << "OpSwitch must be preceeded by an OpSelectionMerge "
660                   "instruction";
661       }
662       // Mark the targets as seen.
663       for (uint32_t i = 1; i < terminator->operands().size(); i += 2) {
664         const auto target = terminator->GetOperandAs<uint32_t>(i);
665         seen.insert(target);
666       }
667     }
668   }
669 
670   return SPV_SUCCESS;
671 }
672 
StructuredControlFlowChecks(ValidationState_t & _,Function * function,const std::vector<std::pair<uint32_t,uint32_t>> & back_edges,const std::vector<const BasicBlock * > & postorder)673 spv_result_t StructuredControlFlowChecks(
674     ValidationState_t& _, Function* function,
675     const std::vector<std::pair<uint32_t, uint32_t>>& back_edges,
676     const std::vector<const BasicBlock*>& postorder) {
677   /// Check all backedges target only loop headers and have exactly one
678   /// back-edge branching to it
679 
680   // Map a loop header to blocks with back-edges to the loop header.
681   std::map<uint32_t, std::unordered_set<uint32_t>> loop_latch_blocks;
682   for (auto back_edge : back_edges) {
683     uint32_t back_edge_block;
684     uint32_t header_block;
685     std::tie(back_edge_block, header_block) = back_edge;
686     if (!function->IsBlockType(header_block, kBlockTypeLoop)) {
687       return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(back_edge_block))
688              << "Back-edges (" << _.getIdName(back_edge_block) << " -> "
689              << _.getIdName(header_block)
690              << ") can only be formed between a block and a loop header.";
691     }
692     loop_latch_blocks[header_block].insert(back_edge_block);
693   }
694 
695   // Check the loop headers have exactly one back-edge branching to it
696   for (BasicBlock* loop_header : function->ordered_blocks()) {
697     if (!loop_header->reachable()) continue;
698     if (!loop_header->is_type(kBlockTypeLoop)) continue;
699     auto loop_header_id = loop_header->id();
700     auto num_latch_blocks = loop_latch_blocks[loop_header_id].size();
701     if (num_latch_blocks != 1) {
702       return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(loop_header_id))
703              << "Loop header " << _.getIdName(loop_header_id)
704              << " is targeted by " << num_latch_blocks
705              << " back-edge blocks but the standard requires exactly one";
706     }
707   }
708 
709   // Check construct rules
710   for (const Construct& construct : function->constructs()) {
711     auto header = construct.entry_block();
712     auto merge = construct.exit_block();
713 
714     if (header->reachable() && !merge) {
715       std::string construct_name, header_name, exit_name;
716       std::tie(construct_name, header_name, exit_name) =
717           ConstructNames(construct.type());
718       return _.diag(SPV_ERROR_INTERNAL, _.FindDef(header->id()))
719              << "Construct " + construct_name + " with " + header_name + " " +
720                     _.getIdName(header->id()) + " does not have a " +
721                     exit_name + ". This may be a bug in the validator.";
722     }
723 
724     // If the exit block is reachable then it's dominated by the
725     // header.
726     if (merge && merge->reachable()) {
727       if (!header->dominates(*merge)) {
728         return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
729                << ConstructErrorString(construct, _.getIdName(header->id()),
730                                        _.getIdName(merge->id()),
731                                        "does not dominate");
732       }
733       // If it's really a merge block for a selection or loop, then it must be
734       // *strictly* dominated by the header.
735       if (construct.ExitBlockIsMergeBlock() && (header == merge)) {
736         return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
737                << ConstructErrorString(construct, _.getIdName(header->id()),
738                                        _.getIdName(merge->id()),
739                                        "does not strictly dominate");
740       }
741     }
742     // Check post-dominance for continue constructs.  But dominance and
743     // post-dominance only make sense when the construct is reachable.
744     if (header->reachable() && construct.type() == ConstructType::kContinue) {
745       if (!merge->postdominates(*header)) {
746         return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
747                << ConstructErrorString(construct, _.getIdName(header->id()),
748                                        _.getIdName(merge->id()),
749                                        "is not post dominated by");
750       }
751     }
752 
753     Construct::ConstructBlockSet construct_blocks = construct.blocks(function);
754     std::string construct_name, header_name, exit_name;
755     std::tie(construct_name, header_name, exit_name) =
756         ConstructNames(construct.type());
757     for (auto block : construct_blocks) {
758       // Check that all exits from the construct are via structured exits.
759       for (auto succ : *block->successors()) {
760         if (block->reachable() && !construct_blocks.count(succ) &&
761             !construct.IsStructuredExit(_, succ)) {
762           return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
763                  << "block <ID> " << _.getIdName(block->id()) << " exits the "
764                  << construct_name << " headed by <ID> "
765                  << _.getIdName(header->id())
766                  << ", but not via a structured exit";
767         }
768       }
769       if (block == header) continue;
770       // Check that for all non-header blocks, all predecessors are within this
771       // construct.
772       for (auto pred : *block->predecessors()) {
773         if (pred->reachable() && !construct_blocks.count(pred)) {
774           return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(pred->id()))
775                  << "block <ID> " << pred->id() << " branches to the "
776                  << construct_name << " construct, but not to the "
777                  << header_name << " <ID> " << header->id();
778         }
779       }
780 
781       if (block->is_type(BlockType::kBlockTypeSelection) ||
782           block->is_type(BlockType::kBlockTypeLoop)) {
783         size_t index = (block->terminator() - &_.ordered_instructions()[0]) - 1;
784         const auto& merge_inst = _.ordered_instructions()[index];
785         if (merge_inst.opcode() == SpvOpSelectionMerge ||
786             merge_inst.opcode() == SpvOpLoopMerge) {
787           uint32_t merge_id = merge_inst.GetOperandAs<uint32_t>(0);
788           auto merge_block = function->GetBlock(merge_id).first;
789           if (merge_block->reachable() &&
790               !construct_blocks.count(merge_block)) {
791             return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
792                    << "Header block " << _.getIdName(block->id())
793                    << " is contained in the " << construct_name
794                    << " construct headed by " << _.getIdName(header->id())
795                    << ", but its merge block " << _.getIdName(merge_id)
796                    << " is not";
797           }
798         }
799       }
800     }
801 
802     // Checks rules for case constructs.
803     if (construct.type() == ConstructType::kSelection &&
804         header->terminator()->opcode() == SpvOpSwitch) {
805       const auto terminator = header->terminator();
806       if (auto error =
807               StructuredSwitchChecks(_, function, terminator, header, merge)) {
808         return error;
809       }
810     }
811   }
812 
813   if (auto error = ValidateStructuredSelections(_, postorder)) {
814     return error;
815   }
816 
817   return SPV_SUCCESS;
818 }
819 
PerformCfgChecks(ValidationState_t & _)820 spv_result_t PerformCfgChecks(ValidationState_t& _) {
821   for (auto& function : _.functions()) {
822     // Check all referenced blocks are defined within a function
823     if (function.undefined_block_count() != 0) {
824       std::string undef_blocks("{");
825       bool first = true;
826       for (auto undefined_block : function.undefined_blocks()) {
827         undef_blocks += _.getIdName(undefined_block);
828         if (!first) {
829           undef_blocks += " ";
830         }
831         first = false;
832       }
833       return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(function.id()))
834              << "Block(s) " << undef_blocks << "}"
835              << " are referenced but not defined in function "
836              << _.getIdName(function.id());
837     }
838 
839     // Set each block's immediate dominator and immediate postdominator,
840     // and find all back-edges.
841     //
842     // We want to analyze all the blocks in the function, even in degenerate
843     // control flow cases including unreachable blocks.  So use the augmented
844     // CFG to ensure we cover all the blocks.
845     std::vector<const BasicBlock*> postorder;
846     std::vector<const BasicBlock*> postdom_postorder;
847     std::vector<std::pair<uint32_t, uint32_t>> back_edges;
848     auto ignore_block = [](const BasicBlock*) {};
849     auto ignore_edge = [](const BasicBlock*, const BasicBlock*) {};
850     if (!function.ordered_blocks().empty()) {
851       /// calculate dominators
852       CFA<BasicBlock>::DepthFirstTraversal(
853           function.first_block(), function.AugmentedCFGSuccessorsFunction(),
854           ignore_block, [&](const BasicBlock* b) { postorder.push_back(b); },
855           ignore_edge);
856       auto edges = CFA<BasicBlock>::CalculateDominators(
857           postorder, function.AugmentedCFGPredecessorsFunction());
858       for (auto edge : edges) {
859         if (edge.first != edge.second)
860           edge.first->SetImmediateDominator(edge.second);
861       }
862 
863       /// calculate post dominators
864       CFA<BasicBlock>::DepthFirstTraversal(
865           function.pseudo_exit_block(),
866           function.AugmentedCFGPredecessorsFunction(), ignore_block,
867           [&](const BasicBlock* b) { postdom_postorder.push_back(b); },
868           ignore_edge);
869       auto postdom_edges = CFA<BasicBlock>::CalculateDominators(
870           postdom_postorder, function.AugmentedCFGSuccessorsFunction());
871       for (auto edge : postdom_edges) {
872         edge.first->SetImmediatePostDominator(edge.second);
873       }
874       /// calculate back edges.
875       CFA<BasicBlock>::DepthFirstTraversal(
876           function.pseudo_entry_block(),
877           function
878               .AugmentedCFGSuccessorsFunctionIncludingHeaderToContinueEdge(),
879           ignore_block, ignore_block,
880           [&](const BasicBlock* from, const BasicBlock* to) {
881             back_edges.emplace_back(from->id(), to->id());
882           });
883     }
884     UpdateContinueConstructExitBlocks(function, back_edges);
885 
886     auto& blocks = function.ordered_blocks();
887     if (!blocks.empty()) {
888       // Check if the order of blocks in the binary appear before the blocks
889       // they dominate
890       for (auto block = begin(blocks) + 1; block != end(blocks); ++block) {
891         if (auto idom = (*block)->immediate_dominator()) {
892           if (idom != function.pseudo_entry_block() &&
893               block == std::find(begin(blocks), block, idom)) {
894             return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(idom->id()))
895                    << "Block " << _.getIdName((*block)->id())
896                    << " appears in the binary before its dominator "
897                    << _.getIdName(idom->id());
898           }
899         }
900       }
901       // If we have structed control flow, check that no block has a control
902       // flow nesting depth larger than the limit.
903       if (_.HasCapability(SpvCapabilityShader)) {
904         const int control_flow_nesting_depth_limit =
905             _.options()->universal_limits_.max_control_flow_nesting_depth;
906         for (auto block = begin(blocks); block != end(blocks); ++block) {
907           if (function.GetBlockDepth(*block) >
908               control_flow_nesting_depth_limit) {
909             return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef((*block)->id()))
910                    << "Maximum Control Flow nesting depth exceeded.";
911           }
912         }
913       }
914     }
915 
916     /// Structured control flow checks are only required for shader capabilities
917     if (_.HasCapability(SpvCapabilityShader)) {
918       if (auto error =
919               StructuredControlFlowChecks(_, &function, back_edges, postorder))
920         return error;
921     }
922   }
923   return SPV_SUCCESS;
924 }
925 
CfgPass(ValidationState_t & _,const Instruction * inst)926 spv_result_t CfgPass(ValidationState_t& _, const Instruction* inst) {
927   SpvOp opcode = inst->opcode();
928   switch (opcode) {
929     case SpvOpLabel:
930       if (auto error = _.current_function().RegisterBlock(inst->id()))
931         return error;
932 
933       // TODO(github:1661) This should be done in the
934       // ValidationState::RegisterInstruction method but because of the order of
935       // passes the OpLabel ends up not being part of the basic block it starts.
936       _.current_function().current_block()->set_label(inst);
937       break;
938     case SpvOpLoopMerge: {
939       uint32_t merge_block = inst->GetOperandAs<uint32_t>(0);
940       uint32_t continue_block = inst->GetOperandAs<uint32_t>(1);
941       CFG_ASSERT(MergeBlockAssert, merge_block);
942 
943       if (auto error = _.current_function().RegisterLoopMerge(merge_block,
944                                                               continue_block))
945         return error;
946     } break;
947     case SpvOpSelectionMerge: {
948       uint32_t merge_block = inst->GetOperandAs<uint32_t>(0);
949       CFG_ASSERT(MergeBlockAssert, merge_block);
950 
951       if (auto error = _.current_function().RegisterSelectionMerge(merge_block))
952         return error;
953     } break;
954     case SpvOpBranch: {
955       uint32_t target = inst->GetOperandAs<uint32_t>(0);
956       CFG_ASSERT(FirstBlockAssert, target);
957 
958       _.current_function().RegisterBlockEnd({target});
959     } break;
960     case SpvOpBranchConditional: {
961       uint32_t tlabel = inst->GetOperandAs<uint32_t>(1);
962       uint32_t flabel = inst->GetOperandAs<uint32_t>(2);
963       CFG_ASSERT(FirstBlockAssert, tlabel);
964       CFG_ASSERT(FirstBlockAssert, flabel);
965 
966       _.current_function().RegisterBlockEnd({tlabel, flabel});
967     } break;
968 
969     case SpvOpSwitch: {
970       std::vector<uint32_t> cases;
971       for (size_t i = 1; i < inst->operands().size(); i += 2) {
972         uint32_t target = inst->GetOperandAs<uint32_t>(i);
973         CFG_ASSERT(FirstBlockAssert, target);
974         cases.push_back(target);
975       }
976       _.current_function().RegisterBlockEnd({cases});
977     } break;
978     case SpvOpReturn: {
979       const uint32_t return_type = _.current_function().GetResultTypeId();
980       const Instruction* return_type_inst = _.FindDef(return_type);
981       assert(return_type_inst);
982       if (return_type_inst->opcode() != SpvOpTypeVoid)
983         return _.diag(SPV_ERROR_INVALID_CFG, inst)
984                << "OpReturn can only be called from a function with void "
985                << "return type.";
986       _.current_function().RegisterBlockEnd(std::vector<uint32_t>());
987       break;
988     }
989     case SpvOpKill:
990     case SpvOpReturnValue:
991     case SpvOpUnreachable:
992     case SpvOpTerminateInvocation:
993     case SpvOpIgnoreIntersectionKHR:
994     case SpvOpTerminateRayKHR:
995       _.current_function().RegisterBlockEnd(std::vector<uint32_t>());
996       if (opcode == SpvOpKill) {
997         _.current_function().RegisterExecutionModelLimitation(
998             SpvExecutionModelFragment,
999             "OpKill requires Fragment execution model");
1000       }
1001       if (opcode == SpvOpTerminateInvocation) {
1002         _.current_function().RegisterExecutionModelLimitation(
1003             SpvExecutionModelFragment,
1004             "OpTerminateInvocation requires Fragment execution model");
1005       }
1006       if (opcode == SpvOpIgnoreIntersectionKHR) {
1007         _.current_function().RegisterExecutionModelLimitation(
1008             SpvExecutionModelAnyHitKHR,
1009             "OpIgnoreIntersectionKHR requires AnyHit execution model");
1010       }
1011       if (opcode == SpvOpTerminateRayKHR) {
1012         _.current_function().RegisterExecutionModelLimitation(
1013             SpvExecutionModelAnyHitKHR,
1014             "OpTerminateRayKHR requires AnyHit execution model");
1015       }
1016 
1017       break;
1018     default:
1019       break;
1020   }
1021   return SPV_SUCCESS;
1022 }
1023 
ReachabilityPass(ValidationState_t & _)1024 void ReachabilityPass(ValidationState_t& _) {
1025   for (auto& f : _.functions()) {
1026     std::vector<BasicBlock*> stack;
1027     auto entry = f.first_block();
1028     // Skip function declarations.
1029     if (entry) stack.push_back(entry);
1030 
1031     while (!stack.empty()) {
1032       auto block = stack.back();
1033       stack.pop_back();
1034 
1035       if (block->reachable()) continue;
1036 
1037       block->set_reachable(true);
1038       for (auto succ : *block->successors()) {
1039         stack.push_back(succ);
1040       }
1041     }
1042   }
1043 }
1044 
ControlFlowPass(ValidationState_t & _,const Instruction * inst)1045 spv_result_t ControlFlowPass(ValidationState_t& _, const Instruction* inst) {
1046   switch (inst->opcode()) {
1047     case SpvOpPhi:
1048       if (auto error = ValidatePhi(_, inst)) return error;
1049       break;
1050     case SpvOpBranch:
1051       if (auto error = ValidateBranch(_, inst)) return error;
1052       break;
1053     case SpvOpBranchConditional:
1054       if (auto error = ValidateBranchConditional(_, inst)) return error;
1055       break;
1056     case SpvOpReturnValue:
1057       if (auto error = ValidateReturnValue(_, inst)) return error;
1058       break;
1059     case SpvOpSwitch:
1060       if (auto error = ValidateSwitch(_, inst)) return error;
1061       break;
1062     case SpvOpLoopMerge:
1063       if (auto error = ValidateLoopMerge(_, inst)) return error;
1064       break;
1065     default:
1066       break;
1067   }
1068 
1069   return SPV_SUCCESS;
1070 }
1071 
1072 }  // namespace val
1073 }  // namespace spvtools
1074