validate_cfg.cpp 46 KB

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