inline_pass.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. // Copyright (c) 2017 The Khronos Group Inc.
  2. // Copyright (c) 2017 Valve Corporation
  3. // Copyright (c) 2017 LunarG Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. #include "source/opt/inline_pass.h"
  17. #include <unordered_set>
  18. #include <utility>
  19. #include "source/cfa.h"
  20. #include "source/opt/reflect.h"
  21. #include "source/util/make_unique.h"
  22. // Indices of operands in SPIR-V instructions
  23. static const int kSpvFunctionCallFunctionId = 2;
  24. static const int kSpvFunctionCallArgumentId = 3;
  25. static const int kSpvReturnValueId = 0;
  26. namespace spvtools {
  27. namespace opt {
  28. uint32_t InlinePass::AddPointerToType(uint32_t type_id,
  29. SpvStorageClass storage_class) {
  30. uint32_t resultId = context()->TakeNextId();
  31. if (resultId == 0) {
  32. return resultId;
  33. }
  34. std::unique_ptr<Instruction> type_inst(
  35. new Instruction(context(), SpvOpTypePointer, 0, resultId,
  36. {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
  37. {uint32_t(storage_class)}},
  38. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
  39. context()->AddType(std::move(type_inst));
  40. analysis::Type* pointeeTy;
  41. std::unique_ptr<analysis::Pointer> pointerTy;
  42. std::tie(pointeeTy, pointerTy) =
  43. context()->get_type_mgr()->GetTypeAndPointerType(type_id,
  44. SpvStorageClassFunction);
  45. context()->get_type_mgr()->RegisterType(resultId, *pointerTy);
  46. return resultId;
  47. }
  48. void InlinePass::AddBranch(uint32_t label_id,
  49. std::unique_ptr<BasicBlock>* block_ptr) {
  50. std::unique_ptr<Instruction> newBranch(
  51. new Instruction(context(), SpvOpBranch, 0, 0,
  52. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
  53. (*block_ptr)->AddInstruction(std::move(newBranch));
  54. }
  55. void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
  56. uint32_t false_id,
  57. std::unique_ptr<BasicBlock>* block_ptr) {
  58. std::unique_ptr<Instruction> newBranch(
  59. new Instruction(context(), SpvOpBranchConditional, 0, 0,
  60. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
  61. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
  62. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
  63. (*block_ptr)->AddInstruction(std::move(newBranch));
  64. }
  65. void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
  66. std::unique_ptr<BasicBlock>* block_ptr) {
  67. std::unique_ptr<Instruction> newLoopMerge(new Instruction(
  68. context(), SpvOpLoopMerge, 0, 0,
  69. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
  70. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
  71. {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
  72. (*block_ptr)->AddInstruction(std::move(newLoopMerge));
  73. }
  74. void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
  75. std::unique_ptr<BasicBlock>* block_ptr) {
  76. std::unique_ptr<Instruction> newStore(
  77. new Instruction(context(), SpvOpStore, 0, 0,
  78. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
  79. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
  80. (*block_ptr)->AddInstruction(std::move(newStore));
  81. }
  82. void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
  83. std::unique_ptr<BasicBlock>* block_ptr) {
  84. std::unique_ptr<Instruction> newLoad(
  85. new Instruction(context(), SpvOpLoad, type_id, resultId,
  86. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
  87. (*block_ptr)->AddInstruction(std::move(newLoad));
  88. }
  89. std::unique_ptr<Instruction> InlinePass::NewLabel(uint32_t label_id) {
  90. std::unique_ptr<Instruction> newLabel(
  91. new Instruction(context(), SpvOpLabel, 0, label_id, {}));
  92. return newLabel;
  93. }
  94. uint32_t InlinePass::GetFalseId() {
  95. if (false_id_ != 0) return false_id_;
  96. false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
  97. if (false_id_ != 0) return false_id_;
  98. uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
  99. if (boolId == 0) {
  100. boolId = context()->TakeNextId();
  101. if (boolId == 0) {
  102. return 0;
  103. }
  104. get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
  105. }
  106. false_id_ = context()->TakeNextId();
  107. if (false_id_ == 0) {
  108. return 0;
  109. }
  110. get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
  111. return false_id_;
  112. }
  113. void InlinePass::MapParams(
  114. Function* calleeFn, BasicBlock::iterator call_inst_itr,
  115. std::unordered_map<uint32_t, uint32_t>* callee2caller) {
  116. int param_idx = 0;
  117. calleeFn->ForEachParam(
  118. [&call_inst_itr, &param_idx, &callee2caller](const Instruction* cpi) {
  119. const uint32_t pid = cpi->result_id();
  120. (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
  121. kSpvFunctionCallArgumentId + param_idx);
  122. ++param_idx;
  123. });
  124. }
  125. bool InlinePass::CloneAndMapLocals(
  126. Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars,
  127. std::unordered_map<uint32_t, uint32_t>* callee2caller) {
  128. auto callee_block_itr = calleeFn->begin();
  129. auto callee_var_itr = callee_block_itr->begin();
  130. while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
  131. std::unique_ptr<Instruction> var_inst(callee_var_itr->Clone(context()));
  132. uint32_t newId = context()->TakeNextId();
  133. if (newId == 0) {
  134. return false;
  135. }
  136. get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId);
  137. var_inst->SetResultId(newId);
  138. (*callee2caller)[callee_var_itr->result_id()] = newId;
  139. new_vars->push_back(std::move(var_inst));
  140. ++callee_var_itr;
  141. }
  142. return true;
  143. }
  144. uint32_t InlinePass::CreateReturnVar(
  145. Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars) {
  146. uint32_t returnVarId = 0;
  147. const uint32_t calleeTypeId = calleeFn->type_id();
  148. analysis::TypeManager* type_mgr = context()->get_type_mgr();
  149. assert(type_mgr->GetType(calleeTypeId)->AsVoid() == nullptr &&
  150. "Cannot create a return variable of type void.");
  151. // Find or create ptr to callee return type.
  152. uint32_t returnVarTypeId =
  153. type_mgr->FindPointerToType(calleeTypeId, SpvStorageClassFunction);
  154. if (returnVarTypeId == 0) {
  155. returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
  156. if (returnVarTypeId == 0) {
  157. return 0;
  158. }
  159. }
  160. // Add return var to new function scope variables.
  161. returnVarId = context()->TakeNextId();
  162. if (returnVarId == 0) {
  163. return 0;
  164. }
  165. std::unique_ptr<Instruction> var_inst(
  166. new Instruction(context(), SpvOpVariable, returnVarTypeId, returnVarId,
  167. {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
  168. {SpvStorageClassFunction}}}));
  169. new_vars->push_back(std::move(var_inst));
  170. get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId);
  171. return returnVarId;
  172. }
  173. bool InlinePass::IsSameBlockOp(const Instruction* inst) const {
  174. return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
  175. }
  176. bool InlinePass::CloneSameBlockOps(
  177. std::unique_ptr<Instruction>* inst,
  178. std::unordered_map<uint32_t, uint32_t>* postCallSB,
  179. std::unordered_map<uint32_t, Instruction*>* preCallSB,
  180. std::unique_ptr<BasicBlock>* block_ptr) {
  181. return (*inst)->WhileEachInId([&postCallSB, &preCallSB, &block_ptr,
  182. this](uint32_t* iid) {
  183. const auto mapItr = (*postCallSB).find(*iid);
  184. if (mapItr == (*postCallSB).end()) {
  185. const auto mapItr2 = (*preCallSB).find(*iid);
  186. if (mapItr2 != (*preCallSB).end()) {
  187. // Clone pre-call same-block ops, map result id.
  188. const Instruction* inInst = mapItr2->second;
  189. std::unique_ptr<Instruction> sb_inst(inInst->Clone(context()));
  190. if (!CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr)) {
  191. return false;
  192. }
  193. const uint32_t rid = sb_inst->result_id();
  194. const uint32_t nid = context()->TakeNextId();
  195. if (nid == 0) {
  196. return false;
  197. }
  198. get_decoration_mgr()->CloneDecorations(rid, nid);
  199. sb_inst->SetResultId(nid);
  200. (*postCallSB)[rid] = nid;
  201. *iid = nid;
  202. (*block_ptr)->AddInstruction(std::move(sb_inst));
  203. }
  204. } else {
  205. // Reset same-block op operand.
  206. *iid = mapItr->second;
  207. }
  208. return true;
  209. });
  210. }
  211. void InlinePass::MoveInstsBeforeEntryBlock(
  212. std::unordered_map<uint32_t, Instruction*>* preCallSB,
  213. BasicBlock* new_blk_ptr, BasicBlock::iterator call_inst_itr,
  214. UptrVectorIterator<BasicBlock> call_block_itr) {
  215. for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
  216. cii = call_block_itr->begin()) {
  217. Instruction* inst = &*cii;
  218. inst->RemoveFromList();
  219. std::unique_ptr<Instruction> cp_inst(inst);
  220. // Remember same-block ops for possible regeneration.
  221. if (IsSameBlockOp(&*cp_inst)) {
  222. auto* sb_inst_ptr = cp_inst.get();
  223. (*preCallSB)[cp_inst->result_id()] = sb_inst_ptr;
  224. }
  225. new_blk_ptr->AddInstruction(std::move(cp_inst));
  226. }
  227. }
  228. std::unique_ptr<BasicBlock> InlinePass::AddGuardBlock(
  229. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  230. std::unordered_map<uint32_t, uint32_t>* callee2caller,
  231. std::unique_ptr<BasicBlock> new_blk_ptr, uint32_t entry_blk_label_id) {
  232. const auto guard_block_id = context()->TakeNextId();
  233. if (guard_block_id == 0) {
  234. return nullptr;
  235. }
  236. AddBranch(guard_block_id, &new_blk_ptr);
  237. new_blocks->push_back(std::move(new_blk_ptr));
  238. // Start the next block.
  239. new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(guard_block_id));
  240. // Reset the mapping of the callee's entry block to point to
  241. // the guard block. Do this so we can fix up phis later on to
  242. // satisfy dominance.
  243. (*callee2caller)[entry_blk_label_id] = guard_block_id;
  244. return new_blk_ptr;
  245. }
  246. InstructionList::iterator InlinePass::AddStoresForVariableInitializers(
  247. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  248. std::unique_ptr<BasicBlock>* new_blk_ptr,
  249. UptrVectorIterator<BasicBlock> callee_first_block_itr) {
  250. auto callee_var_itr = callee_first_block_itr->begin();
  251. while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
  252. if (callee_var_itr->NumInOperands() == 2) {
  253. assert(callee2caller.count(callee_var_itr->result_id()) &&
  254. "Expected the variable to have already been mapped.");
  255. uint32_t new_var_id = callee2caller.at(callee_var_itr->result_id());
  256. // The initializer must be a constant or global value. No mapped
  257. // should be used.
  258. uint32_t val_id = callee_var_itr->GetSingleWordInOperand(1);
  259. AddStore(new_var_id, val_id, new_blk_ptr);
  260. }
  261. ++callee_var_itr;
  262. }
  263. return callee_var_itr;
  264. }
  265. bool InlinePass::InlineInstructionInBB(
  266. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  267. BasicBlock* new_blk_ptr, const Instruction* inst) {
  268. // If we have return, it must be at the end of the callee. We will handle
  269. // it at the end.
  270. if (inst->opcode() == SpvOpReturnValue || inst->opcode() == SpvOpReturn)
  271. return true;
  272. // Copy callee instruction and remap all input Ids.
  273. std::unique_ptr<Instruction> cp_inst(inst->Clone(context()));
  274. cp_inst->ForEachInId([&callee2caller](uint32_t* iid) {
  275. const auto mapItr = callee2caller.find(*iid);
  276. if (mapItr != callee2caller.end()) {
  277. *iid = mapItr->second;
  278. }
  279. });
  280. // If result id is non-zero, remap it.
  281. const uint32_t rid = cp_inst->result_id();
  282. if (rid != 0) {
  283. const auto mapItr = callee2caller.find(rid);
  284. if (mapItr == callee2caller.end()) return false;
  285. uint32_t nid = mapItr->second;
  286. cp_inst->SetResultId(nid);
  287. get_decoration_mgr()->CloneDecorations(rid, nid);
  288. }
  289. new_blk_ptr->AddInstruction(std::move(cp_inst));
  290. return true;
  291. }
  292. std::unique_ptr<BasicBlock> InlinePass::InlineReturn(
  293. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  294. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  295. std::unique_ptr<BasicBlock> new_blk_ptr, Function* calleeFn,
  296. const Instruction* inst, uint32_t returnVarId) {
  297. // Store return value to return variable.
  298. if (inst->opcode() == SpvOpReturnValue) {
  299. assert(returnVarId != 0);
  300. uint32_t valId = inst->GetInOperand(kSpvReturnValueId).words[0];
  301. const auto mapItr = callee2caller.find(valId);
  302. if (mapItr != callee2caller.end()) {
  303. valId = mapItr->second;
  304. }
  305. AddStore(returnVarId, valId, &new_blk_ptr);
  306. }
  307. uint32_t returnLabelId = 0;
  308. for (auto callee_block_itr = calleeFn->begin();
  309. callee_block_itr != calleeFn->end(); ++callee_block_itr) {
  310. if (callee_block_itr->tail()->opcode() == SpvOpUnreachable ||
  311. callee_block_itr->tail()->opcode() == SpvOpKill) {
  312. returnLabelId = context()->TakeNextId();
  313. break;
  314. }
  315. }
  316. if (returnLabelId == 0) return new_blk_ptr;
  317. if (inst->opcode() == SpvOpReturn || inst->opcode() == SpvOpReturnValue)
  318. AddBranch(returnLabelId, &new_blk_ptr);
  319. new_blocks->push_back(std::move(new_blk_ptr));
  320. return MakeUnique<BasicBlock>(NewLabel(returnLabelId));
  321. }
  322. bool InlinePass::InlineEntryBlock(
  323. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  324. std::unique_ptr<BasicBlock>* new_blk_ptr,
  325. UptrVectorIterator<BasicBlock> callee_first_block) {
  326. auto callee_inst_itr = AddStoresForVariableInitializers(
  327. callee2caller, new_blk_ptr, callee_first_block);
  328. while (callee_inst_itr != callee_first_block->end()) {
  329. if (!InlineInstructionInBB(callee2caller, new_blk_ptr->get(),
  330. &*callee_inst_itr)) {
  331. return false;
  332. }
  333. ++callee_inst_itr;
  334. }
  335. return true;
  336. }
  337. std::unique_ptr<BasicBlock> InlinePass::InlineBasicBlocks(
  338. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  339. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  340. std::unique_ptr<BasicBlock> new_blk_ptr, Function* calleeFn) {
  341. auto callee_block_itr = calleeFn->begin();
  342. ++callee_block_itr;
  343. while (callee_block_itr != calleeFn->end()) {
  344. new_blocks->push_back(std::move(new_blk_ptr));
  345. const auto mapItr =
  346. callee2caller.find(callee_block_itr->GetLabelInst()->result_id());
  347. if (mapItr == callee2caller.end()) return nullptr;
  348. new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(mapItr->second));
  349. auto tail_inst_itr = callee_block_itr->end();
  350. for (auto inst_itr = callee_block_itr->begin(); inst_itr != tail_inst_itr;
  351. ++inst_itr) {
  352. if (!InlineInstructionInBB(callee2caller, new_blk_ptr.get(),
  353. &*inst_itr)) {
  354. return nullptr;
  355. }
  356. }
  357. ++callee_block_itr;
  358. }
  359. return new_blk_ptr;
  360. }
  361. bool InlinePass::MoveCallerInstsAfterFunctionCall(
  362. std::unordered_map<uint32_t, Instruction*>* preCallSB,
  363. std::unordered_map<uint32_t, uint32_t>* postCallSB,
  364. std::unique_ptr<BasicBlock>* new_blk_ptr,
  365. BasicBlock::iterator call_inst_itr, bool multiBlocks) {
  366. // Copy remaining instructions from caller block.
  367. for (Instruction* inst = call_inst_itr->NextNode(); inst;
  368. inst = call_inst_itr->NextNode()) {
  369. inst->RemoveFromList();
  370. std::unique_ptr<Instruction> cp_inst(inst);
  371. // If multiple blocks generated, regenerate any same-block
  372. // instruction that has not been seen in this last block.
  373. if (multiBlocks) {
  374. if (!CloneSameBlockOps(&cp_inst, postCallSB, preCallSB, new_blk_ptr)) {
  375. return false;
  376. }
  377. // Remember same-block ops in this block.
  378. if (IsSameBlockOp(&*cp_inst)) {
  379. const uint32_t rid = cp_inst->result_id();
  380. (*postCallSB)[rid] = rid;
  381. }
  382. }
  383. new_blk_ptr->get()->AddInstruction(std::move(cp_inst));
  384. }
  385. return true;
  386. }
  387. void InlinePass::MoveLoopMergeInstToFirstBlock(
  388. std::vector<std::unique_ptr<BasicBlock>>* new_blocks) {
  389. // Move the OpLoopMerge from the last block back to the first, where
  390. // it belongs.
  391. auto& first = new_blocks->front();
  392. auto& last = new_blocks->back();
  393. assert(first != last);
  394. // Insert a modified copy of the loop merge into the first block.
  395. auto loop_merge_itr = last->tail();
  396. --loop_merge_itr;
  397. assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
  398. std::unique_ptr<Instruction> cp_inst(loop_merge_itr->Clone(context()));
  399. first->tail().InsertBefore(std::move(cp_inst));
  400. // Remove the loop merge from the last block.
  401. loop_merge_itr->RemoveFromList();
  402. delete &*loop_merge_itr;
  403. }
  404. bool InlinePass::GenInlineCode(
  405. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  406. std::vector<std::unique_ptr<Instruction>>* new_vars,
  407. BasicBlock::iterator call_inst_itr,
  408. UptrVectorIterator<BasicBlock> call_block_itr) {
  409. // Map from all ids in the callee to their equivalent id in the caller
  410. // as callee instructions are copied into caller.
  411. std::unordered_map<uint32_t, uint32_t> callee2caller;
  412. // Pre-call same-block insts
  413. std::unordered_map<uint32_t, Instruction*> preCallSB;
  414. // Post-call same-block op ids
  415. std::unordered_map<uint32_t, uint32_t> postCallSB;
  416. // Invalidate the def-use chains. They are not kept up to date while
  417. // inlining. However, certain calls try to keep them up-to-date if they are
  418. // valid. These operations can fail.
  419. context()->InvalidateAnalyses(IRContext::kAnalysisDefUse);
  420. // If the caller is a loop header and the callee has multiple blocks, then the
  421. // normal inlining logic will place the OpLoopMerge in the last of several
  422. // blocks in the loop. Instead, it should be placed at the end of the first
  423. // block. We'll wait to move the OpLoopMerge until the end of the regular
  424. // inlining logic, and only if necessary.
  425. bool caller_is_loop_header = call_block_itr->GetLoopMergeInst() != nullptr;
  426. // Single-trip loop continue block
  427. std::unique_ptr<BasicBlock> single_trip_loop_cont_blk;
  428. Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
  429. kSpvFunctionCallFunctionId)];
  430. // Map parameters to actual arguments.
  431. MapParams(calleeFn, call_inst_itr, &callee2caller);
  432. // Define caller local variables for all callee variables and create map to
  433. // them.
  434. if (!CloneAndMapLocals(calleeFn, new_vars, &callee2caller)) {
  435. return false;
  436. }
  437. // First block needs to use label of original block
  438. // but map callee label in case of phi reference.
  439. uint32_t entry_blk_label_id = calleeFn->begin()->GetLabelInst()->result_id();
  440. callee2caller[entry_blk_label_id] = call_block_itr->id();
  441. std::unique_ptr<BasicBlock> new_blk_ptr =
  442. MakeUnique<BasicBlock>(NewLabel(call_block_itr->id()));
  443. // Move instructions of original caller block up to call instruction.
  444. MoveInstsBeforeEntryBlock(&preCallSB, new_blk_ptr.get(), call_inst_itr,
  445. call_block_itr);
  446. if (caller_is_loop_header &&
  447. (*(calleeFn->begin())).GetMergeInst() != nullptr) {
  448. // We can't place both the caller's merge instruction and
  449. // another merge instruction in the same block. So split the
  450. // calling block. Insert an unconditional branch to a new guard
  451. // block. Later, once we know the ID of the last block, we
  452. // will move the caller's OpLoopMerge from the last generated
  453. // block into the first block. We also wait to avoid
  454. // invalidating various iterators.
  455. new_blk_ptr = AddGuardBlock(new_blocks, &callee2caller,
  456. std::move(new_blk_ptr), entry_blk_label_id);
  457. if (new_blk_ptr == nullptr) return false;
  458. }
  459. // Create return var if needed.
  460. const uint32_t calleeTypeId = calleeFn->type_id();
  461. uint32_t returnVarId = 0;
  462. analysis::Type* calleeType = context()->get_type_mgr()->GetType(calleeTypeId);
  463. if (calleeType->AsVoid() == nullptr) {
  464. returnVarId = CreateReturnVar(calleeFn, new_vars);
  465. if (returnVarId == 0) {
  466. return false;
  467. }
  468. }
  469. calleeFn->WhileEachInst([&callee2caller, this](const Instruction* cpi) {
  470. // Create set of callee result ids. Used to detect forward references
  471. const uint32_t rid = cpi->result_id();
  472. if (rid != 0 && callee2caller.find(rid) == callee2caller.end()) {
  473. const uint32_t nid = context()->TakeNextId();
  474. if (nid == 0) return false;
  475. callee2caller[rid] = nid;
  476. }
  477. return true;
  478. });
  479. // Inline the entry block of the callee function.
  480. if (!InlineEntryBlock(callee2caller, &new_blk_ptr, calleeFn->begin())) {
  481. return false;
  482. }
  483. // Inline blocks of the callee function other than the entry block.
  484. new_blk_ptr = InlineBasicBlocks(new_blocks, callee2caller,
  485. std::move(new_blk_ptr), calleeFn);
  486. if (new_blk_ptr == nullptr) return false;
  487. new_blk_ptr =
  488. InlineReturn(callee2caller, new_blocks, std::move(new_blk_ptr), calleeFn,
  489. &*(calleeFn->tail()->tail()), returnVarId);
  490. // Load return value into result id of call, if it exists.
  491. if (returnVarId != 0) {
  492. const uint32_t resId = call_inst_itr->result_id();
  493. assert(resId != 0);
  494. AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
  495. }
  496. // Move instructions of original caller block after call instruction.
  497. if (!MoveCallerInstsAfterFunctionCall(&preCallSB, &postCallSB, &new_blk_ptr,
  498. call_inst_itr,
  499. calleeFn->begin() != calleeFn->end()))
  500. return false;
  501. // Finalize inline code.
  502. new_blocks->push_back(std::move(new_blk_ptr));
  503. if (caller_is_loop_header && (new_blocks->size() > 1))
  504. MoveLoopMergeInstToFirstBlock(new_blocks);
  505. // Update block map given replacement blocks.
  506. for (auto& blk : *new_blocks) {
  507. id2block_[blk->id()] = &*blk;
  508. }
  509. return true;
  510. }
  511. bool InlinePass::IsInlinableFunctionCall(const Instruction* inst) {
  512. if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
  513. const uint32_t calleeFnId =
  514. inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
  515. const auto ci = inlinable_.find(calleeFnId);
  516. if (ci == inlinable_.cend()) return false;
  517. if (early_return_funcs_.find(calleeFnId) != early_return_funcs_.end()) {
  518. // We rely on the merge-return pass to handle the early return case
  519. // in advance.
  520. std::string message =
  521. "The function '" + id2function_[calleeFnId]->DefInst().PrettyPrint() +
  522. "' could not be inlined because the return instruction "
  523. "is not at the end of the function. This could be fixed by "
  524. "running merge-return before inlining.";
  525. consumer()(SPV_MSG_WARNING, "", {0, 0, 0}, message.c_str());
  526. return false;
  527. }
  528. return true;
  529. }
  530. void InlinePass::UpdateSucceedingPhis(
  531. std::vector<std::unique_ptr<BasicBlock>>& new_blocks) {
  532. const auto firstBlk = new_blocks.begin();
  533. const auto lastBlk = new_blocks.end() - 1;
  534. const uint32_t firstId = (*firstBlk)->id();
  535. const uint32_t lastId = (*lastBlk)->id();
  536. const BasicBlock& const_last_block = *lastBlk->get();
  537. const_last_block.ForEachSuccessorLabel(
  538. [&firstId, &lastId, this](const uint32_t succ) {
  539. BasicBlock* sbp = this->id2block_[succ];
  540. sbp->ForEachPhiInst([&firstId, &lastId](Instruction* phi) {
  541. phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
  542. if (*id == firstId) *id = lastId;
  543. });
  544. });
  545. });
  546. }
  547. bool InlinePass::HasNoReturnInLoop(Function* func) {
  548. // If control not structured, do not do loop/return analysis
  549. // TODO: Analyze returns in non-structured control flow
  550. if (!context()->get_feature_mgr()->HasCapability(SpvCapabilityShader))
  551. return false;
  552. const auto structured_analysis = context()->GetStructuredCFGAnalysis();
  553. // Search for returns in structured construct.
  554. bool return_in_loop = false;
  555. for (auto& blk : *func) {
  556. auto terminal_ii = blk.cend();
  557. --terminal_ii;
  558. if (spvOpcodeIsReturn(terminal_ii->opcode()) &&
  559. structured_analysis->ContainingLoop(blk.id()) != 0) {
  560. return_in_loop = true;
  561. break;
  562. }
  563. }
  564. return !return_in_loop;
  565. }
  566. void InlinePass::AnalyzeReturns(Function* func) {
  567. // Analyze functions without a return in loop.
  568. if (HasNoReturnInLoop(func)) {
  569. no_return_in_loop_.insert(func->result_id());
  570. }
  571. // Analyze functions with a return before its tail basic block.
  572. for (auto& blk : *func) {
  573. auto terminal_ii = blk.cend();
  574. --terminal_ii;
  575. if (spvOpcodeIsReturn(terminal_ii->opcode()) && &blk != func->tail()) {
  576. early_return_funcs_.insert(func->result_id());
  577. break;
  578. }
  579. }
  580. }
  581. bool InlinePass::IsInlinableFunction(Function* func) {
  582. // We can only inline a function if it has blocks.
  583. if (func->cbegin() == func->cend()) return false;
  584. // Do not inline functions with returns in loops. Currently early return
  585. // functions are inlined by wrapping them in a one trip loop and implementing
  586. // the returns as a branch to the loop's merge block. However, this can only
  587. // done validly if the return was not in a loop in the original function.
  588. // Also remember functions with multiple (early) returns.
  589. AnalyzeReturns(func);
  590. if (no_return_in_loop_.find(func->result_id()) == no_return_in_loop_.cend()) {
  591. return false;
  592. }
  593. if (func->IsRecursive()) {
  594. return false;
  595. }
  596. // Do not inline functions with an OpKill if they are called from a continue
  597. // construct. If it is inlined into a continue construct it will generate
  598. // invalid code.
  599. bool func_is_called_from_continue =
  600. funcs_called_from_continue_.count(func->result_id()) != 0;
  601. if (func_is_called_from_continue && ContainsKill(func)) {
  602. return false;
  603. }
  604. return true;
  605. }
  606. bool InlinePass::ContainsKill(Function* func) const {
  607. return !func->WhileEachInst(
  608. [](Instruction* inst) { return inst->opcode() != SpvOpKill; });
  609. }
  610. void InlinePass::InitializeInline() {
  611. false_id_ = 0;
  612. // clear collections
  613. id2function_.clear();
  614. id2block_.clear();
  615. inlinable_.clear();
  616. no_return_in_loop_.clear();
  617. early_return_funcs_.clear();
  618. funcs_called_from_continue_ =
  619. context()->GetStructuredCFGAnalysis()->FindFuncsCalledFromContinue();
  620. for (auto& fn : *get_module()) {
  621. // Initialize function and block maps.
  622. id2function_[fn.result_id()] = &fn;
  623. for (auto& blk : fn) {
  624. id2block_[blk.id()] = &blk;
  625. }
  626. // Compute inlinability
  627. if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
  628. }
  629. }
  630. InlinePass::InlinePass() {}
  631. } // namespace opt
  632. } // namespace spvtools