validate_cfg.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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. #include "source/val/validate.h"
  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. #include "source/cfa.h"
  28. #include "source/opcode.h"
  29. #include "source/spirv_target_env.h"
  30. #include "source/spirv_validator_options.h"
  31. #include "source/val/basic_block.h"
  32. #include "source/val/construct.h"
  33. #include "source/val/function.h"
  34. #include "source/val/validation_state.h"
  35. namespace spvtools {
  36. namespace val {
  37. namespace {
  38. spv_result_t ValidatePhi(ValidationState_t& _, const Instruction* inst) {
  39. auto block = inst->block();
  40. size_t num_in_ops = inst->words().size() - 3;
  41. if (num_in_ops % 2 != 0) {
  42. return _.diag(SPV_ERROR_INVALID_ID, inst)
  43. << "OpPhi does not have an equal number of incoming values and "
  44. "basic blocks.";
  45. }
  46. const Instruction* type_inst = _.FindDef(inst->type_id());
  47. assert(type_inst);
  48. const SpvOp type_opcode = type_inst->opcode();
  49. if (type_opcode == SpvOpTypePointer &&
  50. _.addressing_model() == SpvAddressingModelLogical) {
  51. if (!_.features().variable_pointers &&
  52. !_.features().variable_pointers_storage_buffer) {
  53. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  54. << "Using pointers with OpPhi requires capability "
  55. << "VariablePointers or VariablePointersStorageBuffer";
  56. }
  57. }
  58. // Create a uniqued vector of predecessor ids for comparison against
  59. // incoming values. OpBranchConditional %cond %label %label produces two
  60. // predecessors in the CFG.
  61. std::vector<uint32_t> pred_ids;
  62. std::transform(block->predecessors()->begin(), block->predecessors()->end(),
  63. std::back_inserter(pred_ids),
  64. [](const BasicBlock* b) { return b->id(); });
  65. std::sort(pred_ids.begin(), pred_ids.end());
  66. pred_ids.erase(std::unique(pred_ids.begin(), pred_ids.end()), pred_ids.end());
  67. size_t num_edges = num_in_ops / 2;
  68. if (num_edges != pred_ids.size()) {
  69. return _.diag(SPV_ERROR_INVALID_ID, inst)
  70. << "OpPhi's number of incoming blocks (" << num_edges
  71. << ") does not match block's predecessor count ("
  72. << block->predecessors()->size() << ").";
  73. }
  74. for (size_t i = 3; i < inst->words().size(); ++i) {
  75. auto inc_id = inst->word(i);
  76. if (i % 2 == 1) {
  77. // Incoming value type must match the phi result type.
  78. auto inc_type_id = _.GetTypeId(inc_id);
  79. if (inst->type_id() != inc_type_id) {
  80. return _.diag(SPV_ERROR_INVALID_ID, inst)
  81. << "OpPhi's result type <id> " << _.getIdName(inst->type_id())
  82. << " does not match incoming value <id> " << _.getIdName(inc_id)
  83. << " type <id> " << _.getIdName(inc_type_id) << ".";
  84. }
  85. } else {
  86. if (_.GetIdOpcode(inc_id) != SpvOpLabel) {
  87. return _.diag(SPV_ERROR_INVALID_ID, inst)
  88. << "OpPhi's incoming basic block <id> " << _.getIdName(inc_id)
  89. << " is not an OpLabel.";
  90. }
  91. // Incoming basic block must be an immediate predecessor of the phi's
  92. // block.
  93. if (!std::binary_search(pred_ids.begin(), pred_ids.end(), inc_id)) {
  94. return _.diag(SPV_ERROR_INVALID_ID, inst)
  95. << "OpPhi's incoming basic block <id> " << _.getIdName(inc_id)
  96. << " is not a predecessor of <id> " << _.getIdName(block->id())
  97. << ".";
  98. }
  99. }
  100. }
  101. return SPV_SUCCESS;
  102. }
  103. spv_result_t ValidateBranch(ValidationState_t& _, const Instruction* inst) {
  104. // target operands must be OpLabel
  105. const auto id = inst->GetOperandAs<uint32_t>(0);
  106. const auto target = _.FindDef(id);
  107. if (!target || SpvOpLabel != target->opcode()) {
  108. return _.diag(SPV_ERROR_INVALID_ID, inst)
  109. << "'Target Label' operands for OpBranch must be the ID "
  110. "of an OpLabel instruction";
  111. }
  112. return SPV_SUCCESS;
  113. }
  114. spv_result_t ValidateBranchConditional(ValidationState_t& _,
  115. const Instruction* inst) {
  116. // num_operands is either 3 or 5 --- if 5, the last two need to be literal
  117. // integers
  118. const auto num_operands = inst->operands().size();
  119. if (num_operands != 3 && num_operands != 5) {
  120. return _.diag(SPV_ERROR_INVALID_ID, inst)
  121. << "OpBranchConditional requires either 3 or 5 parameters";
  122. }
  123. // grab the condition operand and check that it is a bool
  124. const auto cond_id = inst->GetOperandAs<uint32_t>(0);
  125. const auto cond_op = _.FindDef(cond_id);
  126. if (!cond_op || !cond_op->type_id() ||
  127. !_.IsBoolScalarType(cond_op->type_id())) {
  128. return _.diag(SPV_ERROR_INVALID_ID, inst) << "Condition operand for "
  129. "OpBranchConditional must be "
  130. "of boolean type";
  131. }
  132. // target operands must be OpLabel
  133. // note that we don't need to check that the target labels are in the same
  134. // function,
  135. // PerformCfgChecks already checks for that
  136. const auto true_id = inst->GetOperandAs<uint32_t>(1);
  137. const auto true_target = _.FindDef(true_id);
  138. if (!true_target || SpvOpLabel != true_target->opcode()) {
  139. return _.diag(SPV_ERROR_INVALID_ID, inst)
  140. << "The 'True Label' operand for OpBranchConditional must be the "
  141. "ID of an OpLabel instruction";
  142. }
  143. const auto false_id = inst->GetOperandAs<uint32_t>(2);
  144. const auto false_target = _.FindDef(false_id);
  145. if (!false_target || SpvOpLabel != false_target->opcode()) {
  146. return _.diag(SPV_ERROR_INVALID_ID, inst)
  147. << "The 'False Label' operand for OpBranchConditional must be the "
  148. "ID of an OpLabel instruction";
  149. }
  150. return SPV_SUCCESS;
  151. }
  152. spv_result_t ValidateSwitch(ValidationState_t& _, const Instruction* inst) {
  153. const auto num_operands = inst->operands().size();
  154. // At least two operands (selector, default), any more than that are
  155. // literal/target.
  156. // target operands must be OpLabel
  157. for (size_t i = 2; i < num_operands; i += 2) {
  158. // literal, id
  159. const auto id = inst->GetOperandAs<uint32_t>(i + 1);
  160. const auto target = _.FindDef(id);
  161. if (!target || SpvOpLabel != target->opcode()) {
  162. return _.diag(SPV_ERROR_INVALID_ID, inst)
  163. << "'Target Label' operands for OpSwitch must be IDs of an "
  164. "OpLabel instruction";
  165. }
  166. }
  167. return SPV_SUCCESS;
  168. }
  169. spv_result_t ValidateReturnValue(ValidationState_t& _,
  170. const Instruction* inst) {
  171. const auto value_id = inst->GetOperandAs<uint32_t>(0);
  172. const auto value = _.FindDef(value_id);
  173. if (!value || !value->type_id()) {
  174. return _.diag(SPV_ERROR_INVALID_ID, inst)
  175. << "OpReturnValue Value <id> '" << _.getIdName(value_id)
  176. << "' does not represent a value.";
  177. }
  178. auto value_type = _.FindDef(value->type_id());
  179. if (!value_type || SpvOpTypeVoid == value_type->opcode()) {
  180. return _.diag(SPV_ERROR_INVALID_ID, inst)
  181. << "OpReturnValue value's type <id> '"
  182. << _.getIdName(value->type_id()) << "' is missing or void.";
  183. }
  184. const bool uses_variable_pointer =
  185. _.features().variable_pointers ||
  186. _.features().variable_pointers_storage_buffer;
  187. if (_.addressing_model() == SpvAddressingModelLogical &&
  188. SpvOpTypePointer == value_type->opcode() && !uses_variable_pointer &&
  189. !_.options()->relax_logical_pointer) {
  190. return _.diag(SPV_ERROR_INVALID_ID, inst)
  191. << "OpReturnValue value's type <id> '"
  192. << _.getIdName(value->type_id())
  193. << "' is a pointer, which is invalid in the Logical addressing "
  194. "model.";
  195. }
  196. const auto function = inst->function();
  197. const auto return_type = _.FindDef(function->GetResultTypeId());
  198. if (!return_type || return_type->id() != value_type->id()) {
  199. return _.diag(SPV_ERROR_INVALID_ID, inst)
  200. << "OpReturnValue Value <id> '" << _.getIdName(value_id)
  201. << "'s type does not match OpFunction's return type.";
  202. }
  203. return SPV_SUCCESS;
  204. }
  205. } // namespace
  206. void printDominatorList(const BasicBlock& b) {
  207. std::cout << b.id() << " is dominated by: ";
  208. const BasicBlock* bb = &b;
  209. while (bb->immediate_dominator() != bb) {
  210. bb = bb->immediate_dominator();
  211. std::cout << bb->id() << " ";
  212. }
  213. }
  214. #define CFG_ASSERT(ASSERT_FUNC, TARGET) \
  215. if (spv_result_t rcode = ASSERT_FUNC(_, TARGET)) return rcode
  216. spv_result_t FirstBlockAssert(ValidationState_t& _, uint32_t target) {
  217. if (_.current_function().IsFirstBlock(target)) {
  218. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(_.current_function().id()))
  219. << "First block " << _.getIdName(target) << " of function "
  220. << _.getIdName(_.current_function().id()) << " is targeted by block "
  221. << _.getIdName(_.current_function().current_block()->id());
  222. }
  223. return SPV_SUCCESS;
  224. }
  225. spv_result_t MergeBlockAssert(ValidationState_t& _, uint32_t merge_block) {
  226. if (_.current_function().IsBlockType(merge_block, kBlockTypeMerge)) {
  227. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(_.current_function().id()))
  228. << "Block " << _.getIdName(merge_block)
  229. << " is already a merge block for another header";
  230. }
  231. return SPV_SUCCESS;
  232. }
  233. /// Update the continue construct's exit blocks once the backedge blocks are
  234. /// identified in the CFG.
  235. void UpdateContinueConstructExitBlocks(
  236. Function& function,
  237. const std::vector<std::pair<uint32_t, uint32_t>>& back_edges) {
  238. auto& constructs = function.constructs();
  239. // TODO(umar): Think of a faster way to do this
  240. for (auto& edge : back_edges) {
  241. uint32_t back_edge_block_id;
  242. uint32_t loop_header_block_id;
  243. std::tie(back_edge_block_id, loop_header_block_id) = edge;
  244. auto is_this_header = [=](Construct& c) {
  245. return c.type() == ConstructType::kLoop &&
  246. c.entry_block()->id() == loop_header_block_id;
  247. };
  248. for (auto construct : constructs) {
  249. if (is_this_header(construct)) {
  250. Construct* continue_construct =
  251. construct.corresponding_constructs().back();
  252. assert(continue_construct->type() == ConstructType::kContinue);
  253. BasicBlock* back_edge_block;
  254. std::tie(back_edge_block, std::ignore) =
  255. function.GetBlock(back_edge_block_id);
  256. continue_construct->set_exit(back_edge_block);
  257. }
  258. }
  259. }
  260. }
  261. std::tuple<std::string, std::string, std::string> ConstructNames(
  262. ConstructType type) {
  263. std::string construct_name, header_name, exit_name;
  264. switch (type) {
  265. case ConstructType::kSelection:
  266. construct_name = "selection";
  267. header_name = "selection header";
  268. exit_name = "merge block";
  269. break;
  270. case ConstructType::kLoop:
  271. construct_name = "loop";
  272. header_name = "loop header";
  273. exit_name = "merge block";
  274. break;
  275. case ConstructType::kContinue:
  276. construct_name = "continue";
  277. header_name = "continue target";
  278. exit_name = "back-edge block";
  279. break;
  280. case ConstructType::kCase:
  281. construct_name = "case";
  282. header_name = "case entry block";
  283. exit_name = "case exit block";
  284. break;
  285. default:
  286. assert(1 == 0 && "Not defined type");
  287. }
  288. return std::make_tuple(construct_name, header_name, exit_name);
  289. }
  290. /// Constructs an error message for construct validation errors
  291. std::string ConstructErrorString(const Construct& construct,
  292. const std::string& header_string,
  293. const std::string& exit_string,
  294. const std::string& dominate_text) {
  295. std::string construct_name, header_name, exit_name;
  296. std::tie(construct_name, header_name, exit_name) =
  297. ConstructNames(construct.type());
  298. // TODO(umar): Add header block for continue constructs to error message
  299. return "The " + construct_name + " construct with the " + header_name + " " +
  300. header_string + " " + dominate_text + " the " + exit_name + " " +
  301. exit_string;
  302. }
  303. // Finds the fall through case construct of |target_block| and records it in
  304. // |case_fall_through|. Returns SPV_ERROR_INVALID_CFG if the case construct
  305. // headed by |target_block| branches to multiple case constructs.
  306. spv_result_t FindCaseFallThrough(
  307. ValidationState_t& _, BasicBlock* target_block, uint32_t* case_fall_through,
  308. const BasicBlock* merge, const std::unordered_set<uint32_t>& case_targets,
  309. Function* function) {
  310. std::vector<BasicBlock*> stack;
  311. stack.push_back(target_block);
  312. std::unordered_set<const BasicBlock*> visited;
  313. bool target_reachable = target_block->reachable();
  314. int target_depth = function->GetBlockDepth(target_block);
  315. while (!stack.empty()) {
  316. auto block = stack.back();
  317. stack.pop_back();
  318. if (block == merge) continue;
  319. if (!visited.insert(block).second) continue;
  320. if (target_reachable && block->reachable() &&
  321. target_block->dominates(*block)) {
  322. // Still in the case construct.
  323. for (auto successor : *block->successors()) {
  324. stack.push_back(successor);
  325. }
  326. } else {
  327. // Exiting the case construct to non-merge block.
  328. if (!case_targets.count(block->id())) {
  329. int depth = function->GetBlockDepth(block);
  330. if ((depth < target_depth) ||
  331. (depth == target_depth && block->is_type(kBlockTypeContinue))) {
  332. continue;
  333. }
  334. return _.diag(SPV_ERROR_INVALID_CFG, target_block->label())
  335. << "Case construct that targets "
  336. << _.getIdName(target_block->id())
  337. << " has invalid branch to block " << _.getIdName(block->id())
  338. << " (not another case construct, corresponding merge, outer "
  339. "loop merge or outer loop continue)";
  340. }
  341. if (*case_fall_through == 0u) {
  342. if (target_block != block) {
  343. *case_fall_through = block->id();
  344. }
  345. } else if (*case_fall_through != block->id()) {
  346. // Case construct has at most one branch to another case construct.
  347. return _.diag(SPV_ERROR_INVALID_CFG, target_block->label())
  348. << "Case construct that targets "
  349. << _.getIdName(target_block->id())
  350. << " has branches to multiple other case construct targets "
  351. << _.getIdName(*case_fall_through) << " and "
  352. << _.getIdName(block->id());
  353. }
  354. }
  355. }
  356. return SPV_SUCCESS;
  357. }
  358. spv_result_t StructuredSwitchChecks(ValidationState_t& _, Function* function,
  359. const Instruction* switch_inst,
  360. const BasicBlock* header,
  361. const BasicBlock* merge) {
  362. std::unordered_set<uint32_t> case_targets;
  363. for (uint32_t i = 1; i < switch_inst->operands().size(); i += 2) {
  364. uint32_t target = switch_inst->GetOperandAs<uint32_t>(i);
  365. if (target != merge->id()) case_targets.insert(target);
  366. }
  367. // Tracks how many times each case construct is targeted by another case
  368. // construct.
  369. std::map<uint32_t, uint32_t> num_fall_through_targeted;
  370. uint32_t default_case_fall_through = 0u;
  371. uint32_t default_target = switch_inst->GetOperandAs<uint32_t>(1u);
  372. std::unordered_set<uint32_t> seen;
  373. for (uint32_t i = 1; i < switch_inst->operands().size(); i += 2) {
  374. uint32_t target = switch_inst->GetOperandAs<uint32_t>(i);
  375. if (target == merge->id()) continue;
  376. if (!seen.insert(target).second) continue;
  377. const auto target_block = function->GetBlock(target).first;
  378. // OpSwitch must dominate all its case constructs.
  379. if (header->reachable() && target_block->reachable() &&
  380. !header->dominates(*target_block)) {
  381. return _.diag(SPV_ERROR_INVALID_CFG, header->label())
  382. << "Selection header " << _.getIdName(header->id())
  383. << " does not dominate its case construct " << _.getIdName(target);
  384. }
  385. uint32_t case_fall_through = 0u;
  386. if (auto error = FindCaseFallThrough(_, target_block, &case_fall_through,
  387. merge, case_targets, function)) {
  388. return error;
  389. }
  390. // Track how many time the fall through case has been targeted.
  391. if (case_fall_through != 0u) {
  392. auto where = num_fall_through_targeted.lower_bound(case_fall_through);
  393. if (where == num_fall_through_targeted.end() ||
  394. where->first != case_fall_through) {
  395. num_fall_through_targeted.insert(where,
  396. std::make_pair(case_fall_through, 1));
  397. } else {
  398. where->second++;
  399. }
  400. }
  401. if (case_fall_through == default_target) {
  402. case_fall_through = default_case_fall_through;
  403. }
  404. if (case_fall_through != 0u) {
  405. bool is_default = i == 1;
  406. if (is_default) {
  407. default_case_fall_through = case_fall_through;
  408. } else {
  409. // Allow code like:
  410. // case x:
  411. // case y:
  412. // ...
  413. // case z:
  414. //
  415. // Where x and y target the same block and fall through to z.
  416. uint32_t j = i;
  417. while ((j + 2 < switch_inst->operands().size()) &&
  418. target == switch_inst->GetOperandAs<uint32_t>(j + 2)) {
  419. j += 2;
  420. }
  421. // If Target T1 branches to Target T2, or if Target T1 branches to the
  422. // Default target and the Default target branches to Target T2, then T1
  423. // must immediately precede T2 in the list of OpSwitch Target operands.
  424. if ((switch_inst->operands().size() < j + 2) ||
  425. (case_fall_through != switch_inst->GetOperandAs<uint32_t>(j + 2))) {
  426. return _.diag(SPV_ERROR_INVALID_CFG, switch_inst)
  427. << "Case construct that targets " << _.getIdName(target)
  428. << " has branches to the case construct that targets "
  429. << _.getIdName(case_fall_through)
  430. << ", but does not immediately precede it in the "
  431. "OpSwitch's target list";
  432. }
  433. }
  434. }
  435. }
  436. // Each case construct must be branched to by at most one other case
  437. // construct.
  438. for (const auto& pair : num_fall_through_targeted) {
  439. if (pair.second > 1) {
  440. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(pair.first))
  441. << "Multiple case constructs have branches to the case construct "
  442. "that targets "
  443. << _.getIdName(pair.first);
  444. }
  445. }
  446. return SPV_SUCCESS;
  447. }
  448. spv_result_t StructuredControlFlowChecks(
  449. ValidationState_t& _, Function* function,
  450. const std::vector<std::pair<uint32_t, uint32_t>>& back_edges) {
  451. /// Check all backedges target only loop headers and have exactly one
  452. /// back-edge branching to it
  453. // Map a loop header to blocks with back-edges to the loop header.
  454. std::map<uint32_t, std::unordered_set<uint32_t>> loop_latch_blocks;
  455. for (auto back_edge : back_edges) {
  456. uint32_t back_edge_block;
  457. uint32_t header_block;
  458. std::tie(back_edge_block, header_block) = back_edge;
  459. if (!function->IsBlockType(header_block, kBlockTypeLoop)) {
  460. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(back_edge_block))
  461. << "Back-edges (" << _.getIdName(back_edge_block) << " -> "
  462. << _.getIdName(header_block)
  463. << ") can only be formed between a block and a loop header.";
  464. }
  465. loop_latch_blocks[header_block].insert(back_edge_block);
  466. }
  467. // Check the loop headers have exactly one back-edge branching to it
  468. for (BasicBlock* loop_header : function->ordered_blocks()) {
  469. if (!loop_header->reachable()) continue;
  470. if (!loop_header->is_type(kBlockTypeLoop)) continue;
  471. auto loop_header_id = loop_header->id();
  472. auto num_latch_blocks = loop_latch_blocks[loop_header_id].size();
  473. if (num_latch_blocks != 1) {
  474. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(loop_header_id))
  475. << "Loop header " << _.getIdName(loop_header_id)
  476. << " is targeted by " << num_latch_blocks
  477. << " back-edge blocks but the standard requires exactly one";
  478. }
  479. }
  480. // Check construct rules
  481. for (const Construct& construct : function->constructs()) {
  482. auto header = construct.entry_block();
  483. auto merge = construct.exit_block();
  484. if (header->reachable() && !merge) {
  485. std::string construct_name, header_name, exit_name;
  486. std::tie(construct_name, header_name, exit_name) =
  487. ConstructNames(construct.type());
  488. return _.diag(SPV_ERROR_INTERNAL, _.FindDef(header->id()))
  489. << "Construct " + construct_name + " with " + header_name + " " +
  490. _.getIdName(header->id()) + " does not have a " +
  491. exit_name + ". This may be a bug in the validator.";
  492. }
  493. // If the exit block is reachable then it's dominated by the
  494. // header.
  495. if (merge && merge->reachable()) {
  496. if (!header->dominates(*merge)) {
  497. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
  498. << ConstructErrorString(construct, _.getIdName(header->id()),
  499. _.getIdName(merge->id()),
  500. "does not dominate");
  501. }
  502. // If it's really a merge block for a selection or loop, then it must be
  503. // *strictly* dominated by the header.
  504. if (construct.ExitBlockIsMergeBlock() && (header == merge)) {
  505. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
  506. << ConstructErrorString(construct, _.getIdName(header->id()),
  507. _.getIdName(merge->id()),
  508. "does not strictly dominate");
  509. }
  510. }
  511. // Check post-dominance for continue constructs. But dominance and
  512. // post-dominance only make sense when the construct is reachable.
  513. if (header->reachable() && construct.type() == ConstructType::kContinue) {
  514. if (!merge->postdominates(*header)) {
  515. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
  516. << ConstructErrorString(construct, _.getIdName(header->id()),
  517. _.getIdName(merge->id()),
  518. "is not post dominated by");
  519. }
  520. }
  521. // Check that for all non-header blocks, all predecessors are within this
  522. // construct.
  523. Construct::ConstructBlockSet construct_blocks = construct.blocks(function);
  524. for (auto block : construct_blocks) {
  525. if (block == header) continue;
  526. for (auto pred : *block->predecessors()) {
  527. if (pred->reachable() && !construct_blocks.count(pred)) {
  528. std::string construct_name, header_name, exit_name;
  529. std::tie(construct_name, header_name, exit_name) =
  530. ConstructNames(construct.type());
  531. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(pred->id()))
  532. << "block <ID> " << pred->id() << " branches to the "
  533. << construct_name << " construct, but not to the "
  534. << header_name << " <ID> " << header->id();
  535. }
  536. }
  537. }
  538. // Checks rules for case constructs.
  539. if (construct.type() == ConstructType::kSelection &&
  540. header->terminator()->opcode() == SpvOpSwitch) {
  541. const auto terminator = header->terminator();
  542. if (auto error =
  543. StructuredSwitchChecks(_, function, terminator, header, merge)) {
  544. return error;
  545. }
  546. }
  547. }
  548. return SPV_SUCCESS;
  549. }
  550. spv_result_t PerformWebGPUCfgChecks(ValidationState_t& _, Function* function) {
  551. for (auto& block : function->ordered_blocks()) {
  552. if (block->reachable()) continue;
  553. if (block->is_type(kBlockTypeMerge)) {
  554. // 1. Find the referencing merge and confirm that it is reachable.
  555. BasicBlock* merge_header = function->GetMergeHeader(block);
  556. assert(merge_header != nullptr);
  557. if (!merge_header->reachable()) {
  558. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  559. << "For WebGPU, unreachable merge-blocks must be referenced by "
  560. "a reachable merge instruction.";
  561. }
  562. // 2. Check that the only instructions are OpLabel and OpUnreachable.
  563. auto* label_inst = block->label();
  564. auto* terminator_inst = block->terminator();
  565. assert(label_inst != nullptr);
  566. assert(terminator_inst != nullptr);
  567. if (terminator_inst->opcode() != SpvOpUnreachable) {
  568. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  569. << "For WebGPU, unreachable merge-blocks must terminate with "
  570. "OpUnreachable.";
  571. }
  572. auto label_idx = label_inst - &_.ordered_instructions()[0];
  573. auto terminator_idx = terminator_inst - &_.ordered_instructions()[0];
  574. if (label_idx + 1 != terminator_idx) {
  575. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  576. << "For WebGPU, unreachable merge-blocks must only contain an "
  577. "OpLabel and OpUnreachable instruction.";
  578. }
  579. // 3. Use label instruction to confirm there is no uses by branches.
  580. for (auto use : label_inst->uses()) {
  581. const auto* use_inst = use.first;
  582. if (spvOpcodeIsBranch(use_inst->opcode())) {
  583. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  584. << "For WebGPU, unreachable merge-blocks cannot be the target "
  585. "of a branch.";
  586. }
  587. }
  588. } else if (block->is_type(kBlockTypeContinue)) {
  589. // 1. Find referencing loop and confirm that it is reachable.
  590. std::vector<BasicBlock*> continue_headers =
  591. function->GetContinueHeaders(block);
  592. if (continue_headers.empty()) {
  593. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  594. << "For WebGPU, unreachable continue-target must be referenced "
  595. "by a loop instruction.";
  596. }
  597. std::vector<BasicBlock*> reachable_headers(continue_headers.size());
  598. auto iter =
  599. std::copy_if(continue_headers.begin(), continue_headers.end(),
  600. reachable_headers.begin(),
  601. [](BasicBlock* header) { return header->reachable(); });
  602. reachable_headers.resize(std::distance(reachable_headers.begin(), iter));
  603. if (reachable_headers.empty()) {
  604. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  605. << "For WebGPU, unreachable continue-target must be referenced "
  606. "by a reachable loop instruction.";
  607. }
  608. // 2. Check that the only instructions are OpLabel and OpBranch.
  609. auto* label_inst = block->label();
  610. auto* terminator_inst = block->terminator();
  611. assert(label_inst != nullptr);
  612. assert(terminator_inst != nullptr);
  613. if (terminator_inst->opcode() != SpvOpBranch) {
  614. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  615. << "For WebGPU, unreachable continue-target must terminate with "
  616. "OpBranch.";
  617. }
  618. auto label_idx = label_inst - &_.ordered_instructions()[0];
  619. auto terminator_idx = terminator_inst - &_.ordered_instructions()[0];
  620. if (label_idx + 1 != terminator_idx) {
  621. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  622. << "For WebGPU, unreachable continue-target must only contain "
  623. "an OpLabel and an OpBranch instruction.";
  624. }
  625. // 3. Use label instruction to confirm there is no uses by branches.
  626. for (auto use : label_inst->uses()) {
  627. const auto* use_inst = use.first;
  628. if (spvOpcodeIsBranch(use_inst->opcode())) {
  629. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  630. << "For WebGPU, unreachable continue-target cannot be the "
  631. "target of a branch.";
  632. }
  633. }
  634. // 4. Confirm that continue-target has a back edge to a reachable loop
  635. // header block.
  636. auto branch_target = terminator_inst->GetOperandAs<uint32_t>(0);
  637. for (auto* continue_header : reachable_headers) {
  638. if (branch_target != continue_header->id()) {
  639. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  640. << "For WebGPU, unreachable continue-target must only have a "
  641. "back edge to a single reachable loop instruction.";
  642. }
  643. }
  644. } else {
  645. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
  646. << "For WebGPU, all blocks must be reachable, unless they are "
  647. << "degenerate cases of merge-block or continue-target.";
  648. }
  649. }
  650. return SPV_SUCCESS;
  651. }
  652. spv_result_t PerformCfgChecks(ValidationState_t& _) {
  653. for (auto& function : _.functions()) {
  654. // Check all referenced blocks are defined within a function
  655. if (function.undefined_block_count() != 0) {
  656. std::string undef_blocks("{");
  657. bool first = true;
  658. for (auto undefined_block : function.undefined_blocks()) {
  659. undef_blocks += _.getIdName(undefined_block);
  660. if (!first) {
  661. undef_blocks += " ";
  662. }
  663. first = false;
  664. }
  665. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(function.id()))
  666. << "Block(s) " << undef_blocks << "}"
  667. << " are referenced but not defined in function "
  668. << _.getIdName(function.id());
  669. }
  670. // Set each block's immediate dominator and immediate postdominator,
  671. // and find all back-edges.
  672. //
  673. // We want to analyze all the blocks in the function, even in degenerate
  674. // control flow cases including unreachable blocks. So use the augmented
  675. // CFG to ensure we cover all the blocks.
  676. std::vector<const BasicBlock*> postorder;
  677. std::vector<const BasicBlock*> postdom_postorder;
  678. std::vector<std::pair<uint32_t, uint32_t>> back_edges;
  679. auto ignore_block = [](const BasicBlock*) {};
  680. auto ignore_edge = [](const BasicBlock*, const BasicBlock*) {};
  681. if (!function.ordered_blocks().empty()) {
  682. /// calculate dominators
  683. CFA<BasicBlock>::DepthFirstTraversal(
  684. function.first_block(), function.AugmentedCFGSuccessorsFunction(),
  685. ignore_block, [&](const BasicBlock* b) { postorder.push_back(b); },
  686. ignore_edge);
  687. auto edges = CFA<BasicBlock>::CalculateDominators(
  688. postorder, function.AugmentedCFGPredecessorsFunction());
  689. for (auto edge : edges) {
  690. edge.first->SetImmediateDominator(edge.second);
  691. }
  692. /// calculate post dominators
  693. CFA<BasicBlock>::DepthFirstTraversal(
  694. function.pseudo_exit_block(),
  695. function.AugmentedCFGPredecessorsFunction(), ignore_block,
  696. [&](const BasicBlock* b) { postdom_postorder.push_back(b); },
  697. ignore_edge);
  698. auto postdom_edges = CFA<BasicBlock>::CalculateDominators(
  699. postdom_postorder, function.AugmentedCFGSuccessorsFunction());
  700. for (auto edge : postdom_edges) {
  701. edge.first->SetImmediatePostDominator(edge.second);
  702. }
  703. /// calculate back edges.
  704. CFA<BasicBlock>::DepthFirstTraversal(
  705. function.pseudo_entry_block(),
  706. function
  707. .AugmentedCFGSuccessorsFunctionIncludingHeaderToContinueEdge(),
  708. ignore_block, ignore_block,
  709. [&](const BasicBlock* from, const BasicBlock* to) {
  710. back_edges.emplace_back(from->id(), to->id());
  711. });
  712. }
  713. UpdateContinueConstructExitBlocks(function, back_edges);
  714. auto& blocks = function.ordered_blocks();
  715. if (!blocks.empty()) {
  716. // Check if the order of blocks in the binary appear before the blocks
  717. // they dominate
  718. for (auto block = begin(blocks) + 1; block != end(blocks); ++block) {
  719. if (auto idom = (*block)->immediate_dominator()) {
  720. if (idom != function.pseudo_entry_block() &&
  721. block == std::find(begin(blocks), block, idom)) {
  722. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(idom->id()))
  723. << "Block " << _.getIdName((*block)->id())
  724. << " appears in the binary before its dominator "
  725. << _.getIdName(idom->id());
  726. }
  727. }
  728. // For WebGPU check that all unreachable blocks are degenerate cases for
  729. // merge-block or continue-target.
  730. if (spvIsWebGPUEnv(_.context()->target_env)) {
  731. spv_result_t result = PerformWebGPUCfgChecks(_, &function);
  732. if (result != SPV_SUCCESS) return result;
  733. }
  734. }
  735. // If we have structed control flow, check that no block has a control
  736. // flow nesting depth larger than the limit.
  737. if (_.HasCapability(SpvCapabilityShader)) {
  738. const int control_flow_nesting_depth_limit =
  739. _.options()->universal_limits_.max_control_flow_nesting_depth;
  740. for (auto block = begin(blocks); block != end(blocks); ++block) {
  741. if (function.GetBlockDepth(*block) >
  742. control_flow_nesting_depth_limit) {
  743. return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef((*block)->id()))
  744. << "Maximum Control Flow nesting depth exceeded.";
  745. }
  746. }
  747. }
  748. }
  749. /// Structured control flow checks are only required for shader capabilities
  750. if (_.HasCapability(SpvCapabilityShader)) {
  751. if (auto error = StructuredControlFlowChecks(_, &function, back_edges))
  752. return error;
  753. }
  754. }
  755. return SPV_SUCCESS;
  756. }
  757. spv_result_t CfgPass(ValidationState_t& _, const Instruction* inst) {
  758. SpvOp opcode = inst->opcode();
  759. switch (opcode) {
  760. case SpvOpLabel:
  761. if (auto error = _.current_function().RegisterBlock(inst->id()))
  762. return error;
  763. // TODO(github:1661) This should be done in the
  764. // ValidationState::RegisterInstruction method but because of the order of
  765. // passes the OpLabel ends up not being part of the basic block it starts.
  766. _.current_function().current_block()->set_label(inst);
  767. break;
  768. case SpvOpLoopMerge: {
  769. uint32_t merge_block = inst->GetOperandAs<uint32_t>(0);
  770. uint32_t continue_block = inst->GetOperandAs<uint32_t>(1);
  771. CFG_ASSERT(MergeBlockAssert, merge_block);
  772. if (auto error = _.current_function().RegisterLoopMerge(merge_block,
  773. continue_block))
  774. return error;
  775. } break;
  776. case SpvOpSelectionMerge: {
  777. uint32_t merge_block = inst->GetOperandAs<uint32_t>(0);
  778. CFG_ASSERT(MergeBlockAssert, merge_block);
  779. if (auto error = _.current_function().RegisterSelectionMerge(merge_block))
  780. return error;
  781. } break;
  782. case SpvOpBranch: {
  783. uint32_t target = inst->GetOperandAs<uint32_t>(0);
  784. CFG_ASSERT(FirstBlockAssert, target);
  785. _.current_function().RegisterBlockEnd({target}, opcode);
  786. } break;
  787. case SpvOpBranchConditional: {
  788. uint32_t tlabel = inst->GetOperandAs<uint32_t>(1);
  789. uint32_t flabel = inst->GetOperandAs<uint32_t>(2);
  790. CFG_ASSERT(FirstBlockAssert, tlabel);
  791. CFG_ASSERT(FirstBlockAssert, flabel);
  792. _.current_function().RegisterBlockEnd({tlabel, flabel}, opcode);
  793. } break;
  794. case SpvOpSwitch: {
  795. std::vector<uint32_t> cases;
  796. for (size_t i = 1; i < inst->operands().size(); i += 2) {
  797. uint32_t target = inst->GetOperandAs<uint32_t>(i);
  798. CFG_ASSERT(FirstBlockAssert, target);
  799. cases.push_back(target);
  800. }
  801. _.current_function().RegisterBlockEnd({cases}, opcode);
  802. } break;
  803. case SpvOpReturn: {
  804. const uint32_t return_type = _.current_function().GetResultTypeId();
  805. const Instruction* return_type_inst = _.FindDef(return_type);
  806. assert(return_type_inst);
  807. if (return_type_inst->opcode() != SpvOpTypeVoid)
  808. return _.diag(SPV_ERROR_INVALID_CFG, inst)
  809. << "OpReturn can only be called from a function with void "
  810. << "return type.";
  811. }
  812. // Fallthrough.
  813. case SpvOpKill:
  814. case SpvOpReturnValue:
  815. case SpvOpUnreachable:
  816. _.current_function().RegisterBlockEnd(std::vector<uint32_t>(), opcode);
  817. if (opcode == SpvOpKill) {
  818. _.current_function().RegisterExecutionModelLimitation(
  819. SpvExecutionModelFragment,
  820. "OpKill requires Fragment execution model");
  821. }
  822. break;
  823. default:
  824. break;
  825. }
  826. return SPV_SUCCESS;
  827. }
  828. spv_result_t ControlFlowPass(ValidationState_t& _, const Instruction* inst) {
  829. switch (inst->opcode()) {
  830. case SpvOpPhi:
  831. if (auto error = ValidatePhi(_, inst)) return error;
  832. break;
  833. case SpvOpBranch:
  834. if (auto error = ValidateBranch(_, inst)) return error;
  835. break;
  836. case SpvOpBranchConditional:
  837. if (auto error = ValidateBranchConditional(_, inst)) return error;
  838. break;
  839. case SpvOpReturnValue:
  840. if (auto error = ValidateReturnValue(_, inst)) return error;
  841. break;
  842. case SpvOpSwitch:
  843. if (auto error = ValidateSwitch(_, inst)) return error;
  844. break;
  845. default:
  846. break;
  847. }
  848. return SPV_SUCCESS;
  849. }
  850. } // namespace val
  851. } // namespace spvtools