validate_cfg.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 "cfa.h"
  15. #include "validate.h"
  16. #include <algorithm>
  17. #include <cassert>
  18. #include <functional>
  19. #include <iostream>
  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 "spirv_validator_options.h"
  28. #include "val/basic_block.h"
  29. #include "val/construct.h"
  30. #include "val/function.h"
  31. #include "val/validation_state.h"
  32. using std::find;
  33. using std::function;
  34. using std::get;
  35. using std::ignore;
  36. using std::make_pair;
  37. using std::make_tuple;
  38. using std::numeric_limits;
  39. using std::pair;
  40. using std::string;
  41. using std::tie;
  42. using std::transform;
  43. using std::tuple;
  44. using std::unordered_map;
  45. using std::unordered_set;
  46. using std::vector;
  47. using libspirv::BasicBlock;
  48. namespace libspirv {
  49. namespace {
  50. using bb_ptr = BasicBlock*;
  51. using cbb_ptr = const BasicBlock*;
  52. using bb_iter = vector<BasicBlock*>::const_iterator;
  53. } // namespace
  54. void printDominatorList(const BasicBlock& b) {
  55. std::cout << b.id() << " is dominated by: ";
  56. const BasicBlock* bb = &b;
  57. while (bb->immediate_dominator() != bb) {
  58. bb = bb->immediate_dominator();
  59. std::cout << bb->id() << " ";
  60. }
  61. }
  62. #define CFG_ASSERT(ASSERT_FUNC, TARGET) \
  63. if (spv_result_t rcode = ASSERT_FUNC(_, TARGET)) return rcode
  64. spv_result_t FirstBlockAssert(ValidationState_t& _, uint32_t target) {
  65. if (_.current_function().IsFirstBlock(target)) {
  66. return _.diag(SPV_ERROR_INVALID_CFG)
  67. << "First block " << _.getIdName(target) << " of function "
  68. << _.getIdName(_.current_function().id()) << " is targeted by block "
  69. << _.getIdName(_.current_function().current_block()->id());
  70. }
  71. return SPV_SUCCESS;
  72. }
  73. spv_result_t MergeBlockAssert(ValidationState_t& _, uint32_t merge_block) {
  74. if (_.current_function().IsBlockType(merge_block, kBlockTypeMerge)) {
  75. return _.diag(SPV_ERROR_INVALID_CFG)
  76. << "Block " << _.getIdName(merge_block)
  77. << " is already a merge block for another header";
  78. }
  79. return SPV_SUCCESS;
  80. }
  81. /// Update the continue construct's exit blocks once the backedge blocks are
  82. /// identified in the CFG.
  83. void UpdateContinueConstructExitBlocks(
  84. Function& function, const vector<pair<uint32_t, uint32_t>>& back_edges) {
  85. auto& constructs = function.constructs();
  86. // TODO(umar): Think of a faster way to do this
  87. for (auto& edge : back_edges) {
  88. uint32_t back_edge_block_id;
  89. uint32_t loop_header_block_id;
  90. tie(back_edge_block_id, loop_header_block_id) = edge;
  91. auto is_this_header = [=](Construct& c) {
  92. return c.type() == ConstructType::kLoop &&
  93. c.entry_block()->id() == loop_header_block_id;
  94. };
  95. for (auto construct : constructs) {
  96. if (is_this_header(construct)) {
  97. Construct* continue_construct =
  98. construct.corresponding_constructs().back();
  99. assert(continue_construct->type() == ConstructType::kContinue);
  100. BasicBlock* back_edge_block;
  101. tie(back_edge_block, ignore) = function.GetBlock(back_edge_block_id);
  102. continue_construct->set_exit(back_edge_block);
  103. }
  104. }
  105. }
  106. }
  107. tuple<string, string, string> ConstructNames(ConstructType type) {
  108. string construct_name, header_name, exit_name;
  109. switch (type) {
  110. case ConstructType::kSelection:
  111. construct_name = "selection";
  112. header_name = "selection header";
  113. exit_name = "merge block";
  114. break;
  115. case ConstructType::kLoop:
  116. construct_name = "loop";
  117. header_name = "loop header";
  118. exit_name = "merge block";
  119. break;
  120. case ConstructType::kContinue:
  121. construct_name = "continue";
  122. header_name = "continue target";
  123. exit_name = "back-edge block";
  124. break;
  125. case ConstructType::kCase:
  126. construct_name = "case";
  127. header_name = "case entry block";
  128. exit_name = "case exit block";
  129. break;
  130. default:
  131. assert(1 == 0 && "Not defined type");
  132. }
  133. return make_tuple(construct_name, header_name, exit_name);
  134. }
  135. /// Constructs an error message for construct validation errors
  136. string ConstructErrorString(const Construct& construct,
  137. const string& header_string,
  138. const string& exit_string,
  139. const string& dominate_text) {
  140. string construct_name, header_name, exit_name;
  141. tie(construct_name, header_name, exit_name) =
  142. ConstructNames(construct.type());
  143. // TODO(umar): Add header block for continue constructs to error message
  144. return "The " + construct_name + " construct with the " + header_name + " " +
  145. header_string + " " + dominate_text + " the " + exit_name + " " +
  146. exit_string;
  147. }
  148. spv_result_t StructuredControlFlowChecks(
  149. const ValidationState_t& _, const Function& function,
  150. const vector<pair<uint32_t, uint32_t>>& back_edges) {
  151. /// Check all backedges target only loop headers and have exactly one
  152. /// back-edge branching to it
  153. // Map a loop header to blocks with back-edges to the loop header.
  154. std::map<uint32_t, std::unordered_set<uint32_t>> loop_latch_blocks;
  155. for (auto back_edge : back_edges) {
  156. uint32_t back_edge_block;
  157. uint32_t header_block;
  158. tie(back_edge_block, header_block) = back_edge;
  159. if (!function.IsBlockType(header_block, kBlockTypeLoop)) {
  160. return _.diag(SPV_ERROR_INVALID_CFG)
  161. << "Back-edges (" << _.getIdName(back_edge_block) << " -> "
  162. << _.getIdName(header_block)
  163. << ") can only be formed between a block and a loop header.";
  164. }
  165. loop_latch_blocks[header_block].insert(back_edge_block);
  166. }
  167. // Check the loop headers have exactly one back-edge branching to it
  168. for (BasicBlock* loop_header : function.ordered_blocks()) {
  169. if (!loop_header->reachable()) continue;
  170. if (!loop_header->is_type(kBlockTypeLoop)) continue;
  171. auto loop_header_id = loop_header->id();
  172. auto num_latch_blocks = loop_latch_blocks[loop_header_id].size();
  173. if (num_latch_blocks != 1) {
  174. return _.diag(SPV_ERROR_INVALID_CFG)
  175. << "Loop header " << _.getIdName(loop_header_id)
  176. << " is targeted by " << num_latch_blocks
  177. << " back-edge blocks but the standard requires exactly one";
  178. }
  179. }
  180. // Check construct rules
  181. for (const Construct& construct : function.constructs()) {
  182. auto header = construct.entry_block();
  183. auto merge = construct.exit_block();
  184. if (header->reachable() && !merge) {
  185. string construct_name, header_name, exit_name;
  186. tie(construct_name, header_name, exit_name) =
  187. ConstructNames(construct.type());
  188. return _.diag(SPV_ERROR_INTERNAL)
  189. << "Construct " + construct_name + " with " + header_name + " " +
  190. _.getIdName(header->id()) + " does not have a " +
  191. exit_name + ". This may be a bug in the validator.";
  192. }
  193. // If the exit block is reachable then it's dominated by the
  194. // header.
  195. if (merge && merge->reachable()) {
  196. if (!header->dominates(*merge)) {
  197. return _.diag(SPV_ERROR_INVALID_CFG) << ConstructErrorString(
  198. construct, _.getIdName(header->id()),
  199. _.getIdName(merge->id()), "does not dominate");
  200. }
  201. // If it's really a merge block for a selection or loop, then it must be
  202. // *strictly* dominated by the header.
  203. if (construct.ExitBlockIsMergeBlock() && (header == merge)) {
  204. return _.diag(SPV_ERROR_INVALID_CFG) << ConstructErrorString(
  205. construct, _.getIdName(header->id()),
  206. _.getIdName(merge->id()), "does not strictly dominate");
  207. }
  208. }
  209. // Check post-dominance for continue constructs. But dominance and
  210. // post-dominance only make sense when the construct is reachable.
  211. if (header->reachable() && construct.type() == ConstructType::kContinue) {
  212. if (!merge->postdominates(*header)) {
  213. return _.diag(SPV_ERROR_INVALID_CFG) << ConstructErrorString(
  214. construct, _.getIdName(header->id()),
  215. _.getIdName(merge->id()), "is not post dominated by");
  216. }
  217. }
  218. // TODO(umar): an OpSwitch block dominates all its defined case
  219. // constructs
  220. // TODO(umar): each case construct has at most one branch to another
  221. // case construct
  222. // TODO(umar): each case construct is branched to by at most one other
  223. // case construct
  224. // TODO(umar): if Target T1 branches to Target T2, or if Target T1
  225. // branches to the Default and the Default branches to Target T2, then
  226. // T1 must immediately precede T2 in the list of the OpSwitch Target
  227. // operands
  228. }
  229. return SPV_SUCCESS;
  230. }
  231. spv_result_t PerformCfgChecks(ValidationState_t& _) {
  232. for (auto& function : _.functions()) {
  233. // Check all referenced blocks are defined within a function
  234. if (function.undefined_block_count() != 0) {
  235. string undef_blocks("{");
  236. for (auto undefined_block : function.undefined_blocks()) {
  237. undef_blocks += _.getIdName(undefined_block) + " ";
  238. }
  239. return _.diag(SPV_ERROR_INVALID_CFG)
  240. << "Block(s) " << undef_blocks << "\b}"
  241. << " are referenced but not defined in function "
  242. << _.getIdName(function.id());
  243. }
  244. // Set each block's immediate dominator and immediate postdominator,
  245. // and find all back-edges.
  246. //
  247. // We want to analyze all the blocks in the function, even in degenerate
  248. // control flow cases including unreachable blocks. So use the augmented
  249. // CFG to ensure we cover all the blocks.
  250. vector<const BasicBlock*> postorder;
  251. vector<const BasicBlock*> postdom_postorder;
  252. vector<pair<uint32_t, uint32_t>> back_edges;
  253. auto ignore_block = [](cbb_ptr) {};
  254. auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
  255. if (!function.ordered_blocks().empty()) {
  256. /// calculate dominators
  257. spvtools::CFA<libspirv::BasicBlock>::DepthFirstTraversal(
  258. function.first_block(), function.AugmentedCFGSuccessorsFunction(),
  259. ignore_block, [&](cbb_ptr b) { postorder.push_back(b); },
  260. ignore_edge);
  261. auto edges = spvtools::CFA<libspirv::BasicBlock>::CalculateDominators(
  262. postorder, function.AugmentedCFGPredecessorsFunction());
  263. for (auto edge : edges) {
  264. edge.first->SetImmediateDominator(edge.second);
  265. }
  266. /// calculate post dominators
  267. spvtools::CFA<libspirv::BasicBlock>::DepthFirstTraversal(
  268. function.pseudo_exit_block(),
  269. function.AugmentedCFGPredecessorsFunction(), ignore_block,
  270. [&](cbb_ptr b) { postdom_postorder.push_back(b); }, ignore_edge);
  271. auto postdom_edges =
  272. spvtools::CFA<libspirv::BasicBlock>::CalculateDominators(
  273. postdom_postorder, function.AugmentedCFGSuccessorsFunction());
  274. for (auto edge : postdom_edges) {
  275. edge.first->SetImmediatePostDominator(edge.second);
  276. }
  277. /// calculate back edges.
  278. spvtools::CFA<libspirv::BasicBlock>::DepthFirstTraversal(
  279. function.pseudo_entry_block(),
  280. function
  281. .AugmentedCFGSuccessorsFunctionIncludingHeaderToContinueEdge(),
  282. ignore_block, ignore_block, [&](cbb_ptr from, cbb_ptr to) {
  283. back_edges.emplace_back(from->id(), to->id());
  284. });
  285. }
  286. UpdateContinueConstructExitBlocks(function, back_edges);
  287. auto& blocks = function.ordered_blocks();
  288. if (!blocks.empty()) {
  289. // Check if the order of blocks in the binary appear before the blocks
  290. // they dominate
  291. for (auto block = begin(blocks) + 1; block != end(blocks); ++block) {
  292. if (auto idom = (*block)->immediate_dominator()) {
  293. if (idom != function.pseudo_entry_block() &&
  294. block == std::find(begin(blocks), block, idom)) {
  295. return _.diag(SPV_ERROR_INVALID_CFG)
  296. << "Block " << _.getIdName((*block)->id())
  297. << " appears in the binary before its dominator "
  298. << _.getIdName(idom->id());
  299. }
  300. }
  301. }
  302. // If we have structed control flow, check that no block has a control
  303. // flow nesting depth larger than the limit.
  304. if (_.HasCapability(SpvCapabilityShader)) {
  305. const int control_flow_nesting_depth_limit =
  306. _.options()->universal_limits_.max_control_flow_nesting_depth;
  307. for (auto block = begin(blocks); block != end(blocks); ++block) {
  308. if (function.GetBlockDepth(*block) >
  309. control_flow_nesting_depth_limit) {
  310. return _.diag(SPV_ERROR_INVALID_CFG)
  311. << "Maximum Control Flow nesting depth exceeded.";
  312. }
  313. }
  314. }
  315. }
  316. /// Structured control flow checks are only required for shader capabilities
  317. if (_.HasCapability(SpvCapabilityShader)) {
  318. if (auto error = StructuredControlFlowChecks(_, function, back_edges))
  319. return error;
  320. }
  321. }
  322. return SPV_SUCCESS;
  323. }
  324. spv_result_t CfgPass(ValidationState_t& _,
  325. const spv_parsed_instruction_t* inst) {
  326. SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  327. switch (opcode) {
  328. case SpvOpLabel:
  329. if (auto error = _.current_function().RegisterBlock(inst->result_id))
  330. return error;
  331. break;
  332. case SpvOpLoopMerge: {
  333. uint32_t merge_block = inst->words[inst->operands[0].offset];
  334. uint32_t continue_block = inst->words[inst->operands[1].offset];
  335. CFG_ASSERT(MergeBlockAssert, merge_block);
  336. if (auto error = _.current_function().RegisterLoopMerge(merge_block,
  337. continue_block))
  338. return error;
  339. } break;
  340. case SpvOpSelectionMerge: {
  341. uint32_t merge_block = inst->words[inst->operands[0].offset];
  342. CFG_ASSERT(MergeBlockAssert, merge_block);
  343. if (auto error = _.current_function().RegisterSelectionMerge(merge_block))
  344. return error;
  345. } break;
  346. case SpvOpBranch: {
  347. uint32_t target = inst->words[inst->operands[0].offset];
  348. CFG_ASSERT(FirstBlockAssert, target);
  349. _.current_function().RegisterBlockEnd({target}, opcode);
  350. } break;
  351. case SpvOpBranchConditional: {
  352. uint32_t tlabel = inst->words[inst->operands[1].offset];
  353. uint32_t flabel = inst->words[inst->operands[2].offset];
  354. CFG_ASSERT(FirstBlockAssert, tlabel);
  355. CFG_ASSERT(FirstBlockAssert, flabel);
  356. _.current_function().RegisterBlockEnd({tlabel, flabel}, opcode);
  357. } break;
  358. case SpvOpSwitch: {
  359. vector<uint32_t> cases;
  360. for (int i = 1; i < inst->num_operands; i += 2) {
  361. uint32_t target = inst->words[inst->operands[i].offset];
  362. CFG_ASSERT(FirstBlockAssert, target);
  363. cases.push_back(target);
  364. }
  365. _.current_function().RegisterBlockEnd({cases}, opcode);
  366. } break;
  367. case SpvOpReturn: {
  368. const uint32_t return_type = _.current_function().GetResultTypeId();
  369. const Instruction* return_type_inst = _.FindDef(return_type);
  370. assert(return_type_inst);
  371. if (return_type_inst->opcode() != SpvOpTypeVoid)
  372. return _.diag(SPV_ERROR_INVALID_CFG)
  373. << "OpReturn can only be called from a function with void "
  374. << "return type.";
  375. }
  376. // Fallthrough.
  377. case SpvOpKill:
  378. case SpvOpReturnValue:
  379. case SpvOpUnreachable:
  380. _.current_function().RegisterBlockEnd(vector<uint32_t>(), opcode);
  381. if (opcode == SpvOpKill) {
  382. _.current_function().RegisterExecutionModelLimitation(
  383. SpvExecutionModelFragment,
  384. "OpKill requires Fragment execution model");
  385. }
  386. break;
  387. default:
  388. break;
  389. }
  390. return SPV_SUCCESS;
  391. }
  392. } // namespace libspirv