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