function.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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/function.h"
  15. #include <cassert>
  16. #include <algorithm>
  17. #include <sstream>
  18. #include <unordered_map>
  19. #include <unordered_set>
  20. #include <utility>
  21. #include "source/cfa.h"
  22. #include "source/val/basic_block.h"
  23. #include "source/val/construct.h"
  24. #include "source/val/validate.h"
  25. namespace spvtools {
  26. namespace val {
  27. // Universal Limit of ResultID + 1
  28. static const uint32_t kInvalidId = 0x400000;
  29. Function::Function(uint32_t function_id, uint32_t result_type_id,
  30. SpvFunctionControlMask function_control,
  31. uint32_t function_type_id)
  32. : id_(function_id),
  33. function_type_id_(function_type_id),
  34. result_type_id_(result_type_id),
  35. function_control_(function_control),
  36. declaration_type_(FunctionDecl::kFunctionDeclUnknown),
  37. end_has_been_registered_(false),
  38. blocks_(),
  39. current_block_(nullptr),
  40. pseudo_entry_block_(0),
  41. pseudo_exit_block_(kInvalidId),
  42. cfg_constructs_(),
  43. variable_ids_(),
  44. parameter_ids_() {}
  45. bool Function::IsFirstBlock(uint32_t block_id) const {
  46. return !ordered_blocks_.empty() && *first_block() == block_id;
  47. }
  48. spv_result_t Function::RegisterFunctionParameter(uint32_t parameter_id,
  49. uint32_t type_id) {
  50. assert(current_block_ == nullptr &&
  51. "RegisterFunctionParameter can only be called when parsing the binary "
  52. "ouside of a block");
  53. // TODO(umar): Validate function parameter type order and count
  54. // TODO(umar): Use these variables to validate parameter type
  55. (void)parameter_id;
  56. (void)type_id;
  57. return SPV_SUCCESS;
  58. }
  59. spv_result_t Function::RegisterLoopMerge(uint32_t merge_id,
  60. uint32_t continue_id) {
  61. RegisterBlock(merge_id, false);
  62. RegisterBlock(continue_id, false);
  63. BasicBlock& merge_block = blocks_.at(merge_id);
  64. BasicBlock& continue_target_block = blocks_.at(continue_id);
  65. assert(current_block_ &&
  66. "RegisterLoopMerge must be called when called within a block");
  67. current_block_->set_type(kBlockTypeLoop);
  68. merge_block.set_type(kBlockTypeMerge);
  69. continue_target_block.set_type(kBlockTypeContinue);
  70. Construct& loop_construct =
  71. AddConstruct({ConstructType::kLoop, current_block_, &merge_block});
  72. Construct& continue_construct =
  73. AddConstruct({ConstructType::kContinue, &continue_target_block});
  74. continue_construct.set_corresponding_constructs({&loop_construct});
  75. loop_construct.set_corresponding_constructs({&continue_construct});
  76. merge_block_header_[&merge_block] = current_block_;
  77. if (continue_target_headers_.find(&continue_target_block) ==
  78. continue_target_headers_.end()) {
  79. continue_target_headers_[&continue_target_block] = {current_block_};
  80. } else {
  81. continue_target_headers_[&continue_target_block].push_back(current_block_);
  82. }
  83. return SPV_SUCCESS;
  84. }
  85. spv_result_t Function::RegisterSelectionMerge(uint32_t merge_id) {
  86. RegisterBlock(merge_id, false);
  87. BasicBlock& merge_block = blocks_.at(merge_id);
  88. current_block_->set_type(kBlockTypeHeader);
  89. merge_block.set_type(kBlockTypeMerge);
  90. merge_block_header_[&merge_block] = current_block_;
  91. AddConstruct({ConstructType::kSelection, current_block(), &merge_block});
  92. return SPV_SUCCESS;
  93. }
  94. spv_result_t Function::RegisterSetFunctionDeclType(FunctionDecl type) {
  95. assert(declaration_type_ == FunctionDecl::kFunctionDeclUnknown);
  96. declaration_type_ = type;
  97. return SPV_SUCCESS;
  98. }
  99. spv_result_t Function::RegisterBlock(uint32_t block_id, bool is_definition) {
  100. assert(
  101. declaration_type_ == FunctionDecl::kFunctionDeclDefinition &&
  102. "RegisterBlocks can only be called after declaration_type_ is defined");
  103. std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
  104. bool success = false;
  105. tie(inserted_block, success) =
  106. blocks_.insert({block_id, BasicBlock(block_id)});
  107. if (is_definition) { // new block definition
  108. assert(current_block_ == nullptr &&
  109. "Register Block can only be called when parsing a binary outside of "
  110. "a BasicBlock");
  111. undefined_blocks_.erase(block_id);
  112. current_block_ = &inserted_block->second;
  113. ordered_blocks_.push_back(current_block_);
  114. if (IsFirstBlock(block_id)) current_block_->set_reachable(true);
  115. } else if (success) { // Block doesn't exsist but this is not a definition
  116. undefined_blocks_.insert(block_id);
  117. }
  118. return SPV_SUCCESS;
  119. }
  120. void Function::RegisterBlockEnd(std::vector<uint32_t> next_list,
  121. SpvOp branch_instruction) {
  122. assert(
  123. current_block_ &&
  124. "RegisterBlockEnd can only be called when parsing a binary in a block");
  125. std::vector<BasicBlock*> next_blocks;
  126. next_blocks.reserve(next_list.size());
  127. std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
  128. bool success;
  129. for (uint32_t successor_id : next_list) {
  130. tie(inserted_block, success) =
  131. blocks_.insert({successor_id, BasicBlock(successor_id)});
  132. if (success) {
  133. undefined_blocks_.insert(successor_id);
  134. }
  135. next_blocks.push_back(&inserted_block->second);
  136. }
  137. if (current_block_->is_type(kBlockTypeLoop)) {
  138. // For each loop header, record the set of its successors, and include
  139. // its continue target if the continue target is not the loop header
  140. // itself.
  141. std::vector<BasicBlock*>& next_blocks_plus_continue_target =
  142. loop_header_successors_plus_continue_target_map_[current_block_];
  143. next_blocks_plus_continue_target = next_blocks;
  144. auto continue_target =
  145. FindConstructForEntryBlock(current_block_, ConstructType::kLoop)
  146. .corresponding_constructs()
  147. .back()
  148. ->entry_block();
  149. if (continue_target != current_block_) {
  150. next_blocks_plus_continue_target.push_back(continue_target);
  151. }
  152. }
  153. current_block_->RegisterBranchInstruction(branch_instruction);
  154. current_block_->RegisterSuccessors(next_blocks);
  155. current_block_ = nullptr;
  156. return;
  157. }
  158. void Function::RegisterFunctionEnd() {
  159. if (!end_has_been_registered_) {
  160. end_has_been_registered_ = true;
  161. ComputeAugmentedCFG();
  162. }
  163. }
  164. size_t Function::block_count() const { return blocks_.size(); }
  165. size_t Function::undefined_block_count() const {
  166. return undefined_blocks_.size();
  167. }
  168. const std::vector<BasicBlock*>& Function::ordered_blocks() const {
  169. return ordered_blocks_;
  170. }
  171. std::vector<BasicBlock*>& Function::ordered_blocks() { return ordered_blocks_; }
  172. const BasicBlock* Function::current_block() const { return current_block_; }
  173. BasicBlock* Function::current_block() { return current_block_; }
  174. const std::list<Construct>& Function::constructs() const {
  175. return cfg_constructs_;
  176. }
  177. std::list<Construct>& Function::constructs() { return cfg_constructs_; }
  178. const BasicBlock* Function::first_block() const {
  179. if (ordered_blocks_.empty()) return nullptr;
  180. return ordered_blocks_[0];
  181. }
  182. BasicBlock* Function::first_block() {
  183. if (ordered_blocks_.empty()) return nullptr;
  184. return ordered_blocks_[0];
  185. }
  186. bool Function::IsBlockType(uint32_t merge_block_id, BlockType type) const {
  187. bool ret = false;
  188. const BasicBlock* block;
  189. std::tie(block, std::ignore) = GetBlock(merge_block_id);
  190. if (block) {
  191. ret = block->is_type(type);
  192. }
  193. return ret;
  194. }
  195. std::pair<const BasicBlock*, bool> Function::GetBlock(uint32_t block_id) const {
  196. const auto b = blocks_.find(block_id);
  197. if (b != end(blocks_)) {
  198. const BasicBlock* block = &(b->second);
  199. bool defined =
  200. undefined_blocks_.find(block->id()) == std::end(undefined_blocks_);
  201. return std::make_pair(block, defined);
  202. } else {
  203. return std::make_pair(nullptr, false);
  204. }
  205. }
  206. std::pair<BasicBlock*, bool> Function::GetBlock(uint32_t block_id) {
  207. const BasicBlock* out;
  208. bool defined;
  209. std::tie(out, defined) =
  210. const_cast<const Function*>(this)->GetBlock(block_id);
  211. return std::make_pair(const_cast<BasicBlock*>(out), defined);
  212. }
  213. Function::GetBlocksFunction Function::AugmentedCFGSuccessorsFunction() const {
  214. return [this](const BasicBlock* block) {
  215. auto where = augmented_successors_map_.find(block);
  216. return where == augmented_successors_map_.end() ? block->successors()
  217. : &(*where).second;
  218. };
  219. }
  220. Function::GetBlocksFunction
  221. Function::AugmentedCFGSuccessorsFunctionIncludingHeaderToContinueEdge() const {
  222. return [this](const BasicBlock* block) {
  223. auto where = loop_header_successors_plus_continue_target_map_.find(block);
  224. return where == loop_header_successors_plus_continue_target_map_.end()
  225. ? AugmentedCFGSuccessorsFunction()(block)
  226. : &(*where).second;
  227. };
  228. }
  229. Function::GetBlocksFunction Function::AugmentedCFGPredecessorsFunction() const {
  230. return [this](const BasicBlock* block) {
  231. auto where = augmented_predecessors_map_.find(block);
  232. return where == augmented_predecessors_map_.end() ? block->predecessors()
  233. : &(*where).second;
  234. };
  235. }
  236. void Function::ComputeAugmentedCFG() {
  237. // Compute the successors of the pseudo-entry block, and
  238. // the predecessors of the pseudo exit block.
  239. auto succ_func = [](const BasicBlock* b) { return b->successors(); };
  240. auto pred_func = [](const BasicBlock* b) { return b->predecessors(); };
  241. CFA<BasicBlock>::ComputeAugmentedCFG(
  242. ordered_blocks_, &pseudo_entry_block_, &pseudo_exit_block_,
  243. &augmented_successors_map_, &augmented_predecessors_map_, succ_func,
  244. pred_func);
  245. }
  246. Construct& Function::AddConstruct(const Construct& new_construct) {
  247. cfg_constructs_.push_back(new_construct);
  248. auto& result = cfg_constructs_.back();
  249. entry_block_to_construct_[std::make_pair(new_construct.entry_block(),
  250. new_construct.type())] = &result;
  251. return result;
  252. }
  253. Construct& Function::FindConstructForEntryBlock(const BasicBlock* entry_block,
  254. ConstructType type) {
  255. auto where =
  256. entry_block_to_construct_.find(std::make_pair(entry_block, type));
  257. assert(where != entry_block_to_construct_.end());
  258. auto construct_ptr = (*where).second;
  259. assert(construct_ptr);
  260. return *construct_ptr;
  261. }
  262. int Function::GetBlockDepth(BasicBlock* bb) {
  263. // Guard against nullptr.
  264. if (!bb) {
  265. return 0;
  266. }
  267. // Only calculate the depth if it's not already calculated.
  268. // This function uses memoization to avoid duplicate CFG depth calculations.
  269. if (block_depth_.find(bb) != block_depth_.end()) {
  270. return block_depth_[bb];
  271. }
  272. BasicBlock* bb_dom = bb->immediate_dominator();
  273. if (!bb_dom || bb == bb_dom) {
  274. // This block has no dominator, so it's at depth 0.
  275. block_depth_[bb] = 0;
  276. } else if (bb->is_type(kBlockTypeMerge)) {
  277. // If this is a merge block, its depth is equal to the block before
  278. // branching.
  279. BasicBlock* header = merge_block_header_[bb];
  280. assert(header);
  281. block_depth_[bb] = GetBlockDepth(header);
  282. } else if (bb->is_type(kBlockTypeContinue)) {
  283. // The depth of the continue block entry point is 1 + loop header depth.
  284. Construct* continue_construct =
  285. entry_block_to_construct_[std::make_pair(bb, ConstructType::kContinue)];
  286. assert(continue_construct);
  287. // Continue construct has only 1 corresponding construct (loop header).
  288. Construct* loop_construct =
  289. continue_construct->corresponding_constructs()[0];
  290. assert(loop_construct);
  291. BasicBlock* loop_header = loop_construct->entry_block();
  292. // The continue target may be the loop itself (while 1).
  293. // In such cases, the depth of the continue block is: 1 + depth of the
  294. // loop's dominator block.
  295. if (loop_header == bb) {
  296. block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
  297. } else {
  298. block_depth_[bb] = 1 + GetBlockDepth(loop_header);
  299. }
  300. } else if (bb_dom->is_type(kBlockTypeHeader) ||
  301. bb_dom->is_type(kBlockTypeLoop)) {
  302. // The dominator of the given block is a header block. So, the nesting
  303. // depth of this block is: 1 + nesting depth of the header.
  304. block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
  305. } else {
  306. block_depth_[bb] = GetBlockDepth(bb_dom);
  307. }
  308. return block_depth_[bb];
  309. }
  310. void Function::RegisterExecutionModelLimitation(SpvExecutionModel model,
  311. const std::string& message) {
  312. execution_model_limitations_.push_back(
  313. [model, message](SpvExecutionModel in_model, std::string* out_message) {
  314. if (model != in_model) {
  315. if (out_message) {
  316. *out_message = message;
  317. }
  318. return false;
  319. }
  320. return true;
  321. });
  322. }
  323. bool Function::IsCompatibleWithExecutionModel(SpvExecutionModel model,
  324. std::string* reason) const {
  325. bool return_value = true;
  326. std::stringstream ss_reason;
  327. for (const auto& is_compatible : execution_model_limitations_) {
  328. std::string message;
  329. if (!is_compatible(model, &message)) {
  330. if (!reason) return false;
  331. return_value = false;
  332. if (!message.empty()) {
  333. ss_reason << message << "\n";
  334. }
  335. }
  336. }
  337. if (!return_value && reason) {
  338. *reason = ss_reason.str();
  339. }
  340. return return_value;
  341. }
  342. } // namespace val
  343. } // namespace spvtools