inline_pass.cpp 29 KB

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