ssa_rewrite_pass.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. // Copyright (c) 2018 Google LLC.
  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. // This file implements the SSA rewriting algorithm proposed in
  15. //
  16. // Simple and Efficient Construction of Static Single Assignment Form.
  17. // Braun M., Buchwald S., Hack S., Leißa R., Mallon C., Zwinkau A. (2013)
  18. // In: Jhala R., De Bosschere K. (eds)
  19. // Compiler Construction. CC 2013.
  20. // Lecture Notes in Computer Science, vol 7791.
  21. // Springer, Berlin, Heidelberg
  22. //
  23. // https://link.springer.com/chapter/10.1007/978-3-642-37051-9_6
  24. //
  25. // In contrast to common eager algorithms based on dominance and dominance
  26. // frontier information, this algorithm works backwards from load operations.
  27. //
  28. // When a target variable is loaded, it queries the variable's reaching
  29. // definition. If the reaching definition is unknown at the current location,
  30. // it searches backwards in the CFG, inserting Phi instructions at join points
  31. // in the CFG along the way until it finds the desired store instruction.
  32. //
  33. // The algorithm avoids repeated lookups using memoization.
  34. //
  35. // For reducible CFGs, which are a superset of the structured CFGs in SPIRV,
  36. // this algorithm is proven to produce minimal SSA. That is, it inserts the
  37. // minimal number of Phi instructions required to ensure the SSA property, but
  38. // some Phi instructions may be dead
  39. // (https://en.wikipedia.org/wiki/Static_single_assignment_form).
  40. #include "source/opt/ssa_rewrite_pass.h"
  41. #include <memory>
  42. #include <sstream>
  43. #include "source/opcode.h"
  44. #include "source/opt/cfg.h"
  45. #include "source/opt/mem_pass.h"
  46. #include "source/opt/types.h"
  47. #include "source/util/make_unique.h"
  48. // Debug logging (0: Off, 1-N: Verbosity level). Replace this with the
  49. // implementation done for
  50. // https://github.com/KhronosGroup/SPIRV-Tools/issues/1351
  51. // #define SSA_REWRITE_DEBUGGING_LEVEL 3
  52. #ifdef SSA_REWRITE_DEBUGGING_LEVEL
  53. #include <ostream>
  54. #else
  55. #define SSA_REWRITE_DEBUGGING_LEVEL 0
  56. #endif
  57. namespace spvtools {
  58. namespace opt {
  59. namespace {
  60. constexpr uint32_t kStoreValIdInIdx = 1;
  61. constexpr uint32_t kVariableInitIdInIdx = 1;
  62. } // namespace
  63. std::string SSARewriter::PhiCandidate::PrettyPrint(const CFG* cfg) const {
  64. std::ostringstream str;
  65. str << "%" << result_id_ << " = Phi[%" << var_id_ << ", BB %" << bb_->id()
  66. << "](";
  67. if (phi_args_.size() > 0) {
  68. uint32_t arg_ix = 0;
  69. for (uint32_t pred_label : cfg->preds(bb_->id())) {
  70. uint32_t arg_id = phi_args_[arg_ix++];
  71. str << "[%" << arg_id << ", bb(%" << pred_label << ")] ";
  72. }
  73. }
  74. str << ")";
  75. if (copy_of_ != 0) {
  76. str << " [COPY OF " << copy_of_ << "]";
  77. }
  78. str << ((is_complete_) ? " [COMPLETE]" : " [INCOMPLETE]");
  79. return str.str();
  80. }
  81. SSARewriter::PhiCandidate& SSARewriter::CreatePhiCandidate(uint32_t var_id,
  82. BasicBlock* bb) {
  83. // TODO(1841): Handle id overflow.
  84. uint32_t phi_result_id = pass_->context()->TakeNextId();
  85. auto result = phi_candidates_.emplace(
  86. phi_result_id, PhiCandidate(var_id, phi_result_id, bb));
  87. PhiCandidate& phi_candidate = result.first->second;
  88. return phi_candidate;
  89. }
  90. void SSARewriter::ReplacePhiUsersWith(const PhiCandidate& phi_to_remove,
  91. uint32_t repl_id) {
  92. for (uint32_t user_id : phi_to_remove.users()) {
  93. PhiCandidate* user_phi = GetPhiCandidate(user_id);
  94. BasicBlock* bb = pass_->context()->get_instr_block(user_id);
  95. if (user_phi) {
  96. // If the user is a Phi candidate, replace all arguments that refer to
  97. // |phi_to_remove.result_id()| with |repl_id|.
  98. for (uint32_t& arg : user_phi->phi_args()) {
  99. if (arg == phi_to_remove.result_id()) {
  100. arg = repl_id;
  101. }
  102. }
  103. } else if (bb->id() == user_id) {
  104. // The phi candidate is the definition of the variable at basic block
  105. // |bb|. We must change this to the replacement.
  106. WriteVariable(phi_to_remove.var_id(), bb, repl_id);
  107. } else {
  108. // For regular loads, traverse the |load_replacement_| table looking for
  109. // instances of |phi_to_remove|.
  110. for (auto& it : load_replacement_) {
  111. if (it.second == phi_to_remove.result_id()) {
  112. it.second = repl_id;
  113. }
  114. }
  115. }
  116. }
  117. }
  118. uint32_t SSARewriter::TryRemoveTrivialPhi(PhiCandidate* phi_candidate) {
  119. uint32_t same_id = 0;
  120. for (uint32_t arg_id : phi_candidate->phi_args()) {
  121. if (arg_id == same_id || arg_id == phi_candidate->result_id()) {
  122. // This is a self-reference operand or a reference to the same value ID.
  123. continue;
  124. }
  125. if (same_id != 0) {
  126. // This Phi candidate merges at least two values. Therefore, it is not
  127. // trivial.
  128. assert(phi_candidate->copy_of() == 0 &&
  129. "Phi candidate transitioning from copy to non-copy.");
  130. return phi_candidate->result_id();
  131. }
  132. same_id = arg_id;
  133. }
  134. // The previous logic has determined that this Phi candidate |phi_candidate|
  135. // is trivial. It is essentially the copy operation phi_candidate->phi_result
  136. // = Phi(same, same, same, ...). Since it is not necessary, we can re-route
  137. // all the users of |phi_candidate->phi_result| to all its users, and remove
  138. // |phi_candidate|.
  139. // Mark the Phi candidate as a trivial copy of |same_id|, so it won't be
  140. // generated.
  141. phi_candidate->MarkCopyOf(same_id);
  142. assert(same_id != 0 && "Completed Phis cannot have %0 in their arguments");
  143. // Since |phi_candidate| always produces |same_id|, replace all the users of
  144. // |phi_candidate| with |same_id|.
  145. ReplacePhiUsersWith(*phi_candidate, same_id);
  146. return same_id;
  147. }
  148. uint32_t SSARewriter::AddPhiOperands(PhiCandidate* phi_candidate) {
  149. assert(phi_candidate->phi_args().size() == 0 &&
  150. "Phi candidate already has arguments");
  151. bool found_0_arg = false;
  152. for (uint32_t pred : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  153. BasicBlock* pred_bb = pass_->cfg()->block(pred);
  154. // If |pred_bb| is not sealed, use %0 to indicate that
  155. // |phi_candidate| needs to be completed after the whole CFG has
  156. // been processed.
  157. //
  158. // Note that we cannot call GetReachingDef() in these cases
  159. // because this would generate an empty Phi candidate in
  160. // |pred_bb|. When |pred_bb| is later processed, a new definition
  161. // for |phi_candidate->var_id_| will be lost because
  162. // |phi_candidate| will still be reached by the empty Phi.
  163. //
  164. // Consider:
  165. //
  166. // BB %23:
  167. // %38 = Phi[%i](%int_0[%1], %39[%25])
  168. //
  169. // ...
  170. //
  171. // BB %25: [Starts unsealed]
  172. // %39 = Phi[%i]()
  173. // %34 = ...
  174. // OpStore %i %34 -> Currdef(%i) at %25 is %34
  175. // OpBranch %23
  176. //
  177. // When we first create the Phi in %38, we add an operandless Phi in
  178. // %39 to hold the unknown reaching def for %i.
  179. //
  180. // But then, when we go to complete %39 at the end. The reaching def
  181. // for %i in %25's predecessor is %38 itself. So we miss the fact
  182. // that %25 has a def for %i that should be used.
  183. //
  184. // By making the argument %0, we make |phi_candidate| incomplete,
  185. // which will cause it to be completed after the whole CFG has
  186. // been scanned.
  187. uint32_t arg_id = IsBlockSealed(pred_bb)
  188. ? GetReachingDef(phi_candidate->var_id(), pred_bb)
  189. : 0;
  190. phi_candidate->phi_args().push_back(arg_id);
  191. if (arg_id == 0) {
  192. found_0_arg = true;
  193. } else {
  194. // If this argument is another Phi candidate, add |phi_candidate| to the
  195. // list of users for the defining Phi.
  196. PhiCandidate* defining_phi = GetPhiCandidate(arg_id);
  197. if (defining_phi && defining_phi != phi_candidate) {
  198. defining_phi->AddUser(phi_candidate->result_id());
  199. }
  200. }
  201. }
  202. // If we could not fill-in all the arguments of this Phi, mark it incomplete
  203. // so it gets completed after the whole CFG has been processed.
  204. if (found_0_arg) {
  205. phi_candidate->MarkIncomplete();
  206. incomplete_phis_.push(phi_candidate);
  207. return phi_candidate->result_id();
  208. }
  209. // Try to remove |phi_candidate|, if it's trivial.
  210. uint32_t repl_id = TryRemoveTrivialPhi(phi_candidate);
  211. if (repl_id == phi_candidate->result_id()) {
  212. // |phi_candidate| is complete and not trivial. Add it to the
  213. // list of Phi candidates to generate.
  214. phi_candidate->MarkComplete();
  215. phis_to_generate_.push_back(phi_candidate);
  216. }
  217. return repl_id;
  218. }
  219. uint32_t SSARewriter::GetValueAtBlock(uint32_t var_id, BasicBlock* bb) {
  220. assert(bb != nullptr);
  221. const auto& bb_it = defs_at_block_.find(bb);
  222. if (bb_it != defs_at_block_.end()) {
  223. const auto& current_defs = bb_it->second;
  224. const auto& var_it = current_defs.find(var_id);
  225. if (var_it != current_defs.end()) {
  226. return var_it->second;
  227. }
  228. }
  229. return 0;
  230. }
  231. uint32_t SSARewriter::GetReachingDef(uint32_t var_id, BasicBlock* bb) {
  232. // If |var_id| has a definition in |bb|, return it.
  233. uint32_t val_id = GetValueAtBlock(var_id, bb);
  234. if (val_id != 0) return val_id;
  235. // Otherwise, look up the value for |var_id| in |bb|'s predecessors.
  236. auto& predecessors = pass_->cfg()->preds(bb->id());
  237. if (predecessors.size() == 1) {
  238. // If |bb| has exactly one predecessor, we look for |var_id|'s definition
  239. // there.
  240. val_id = GetReachingDef(var_id, pass_->cfg()->block(predecessors[0]));
  241. } else if (predecessors.size() > 1) {
  242. // If there is more than one predecessor, this is a join block which may
  243. // require a Phi instruction. This will act as |var_id|'s current
  244. // definition to break potential cycles.
  245. PhiCandidate& phi_candidate = CreatePhiCandidate(var_id, bb);
  246. // Set the value for |bb| to avoid an infinite recursion.
  247. WriteVariable(var_id, bb, phi_candidate.result_id());
  248. val_id = AddPhiOperands(&phi_candidate);
  249. }
  250. // If we could not find a store for this variable in the path from the root
  251. // of the CFG, the variable is not defined, so we use undef.
  252. if (val_id == 0) {
  253. val_id = pass_->GetUndefVal(var_id);
  254. if (val_id == 0) {
  255. return 0;
  256. }
  257. }
  258. WriteVariable(var_id, bb, val_id);
  259. return val_id;
  260. }
  261. void SSARewriter::SealBlock(BasicBlock* bb) {
  262. auto result = sealed_blocks_.insert(bb);
  263. (void)result;
  264. assert(result.second == true &&
  265. "Tried to seal the same basic block more than once.");
  266. }
  267. void SSARewriter::ProcessStore(Instruction* inst, BasicBlock* bb) {
  268. auto opcode = inst->opcode();
  269. assert((opcode == spv::Op::OpStore || opcode == spv::Op::OpVariable) &&
  270. "Expecting a store or a variable definition instruction.");
  271. uint32_t var_id = 0;
  272. uint32_t val_id = 0;
  273. if (opcode == spv::Op::OpStore) {
  274. (void)pass_->GetPtr(inst, &var_id);
  275. val_id = inst->GetSingleWordInOperand(kStoreValIdInIdx);
  276. } else if (inst->NumInOperands() >= 2) {
  277. var_id = inst->result_id();
  278. val_id = inst->GetSingleWordInOperand(kVariableInitIdInIdx);
  279. }
  280. if (pass_->IsTargetVar(var_id)) {
  281. WriteVariable(var_id, bb, val_id);
  282. pass_->context()->get_debug_info_mgr()->AddDebugValueForVariable(
  283. inst, var_id, val_id, inst);
  284. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  285. std::cerr << "\tFound store '%" << var_id << " = %" << val_id << "': "
  286. << inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  287. << "\n";
  288. #endif
  289. }
  290. }
  291. bool SSARewriter::ProcessLoad(Instruction* inst, BasicBlock* bb) {
  292. // Get the pointer that we are using to load from.
  293. uint32_t var_id = 0;
  294. (void)pass_->GetPtr(inst, &var_id);
  295. // Get the immediate reaching definition for |var_id|.
  296. //
  297. // In the presence of variable pointers, the reaching definition may be
  298. // another pointer. For example, the following fragment:
  299. //
  300. // %2 = OpVariable %_ptr_Input_float Input
  301. // %11 = OpVariable %_ptr_Function__ptr_Input_float Function
  302. // OpStore %11 %2
  303. // %12 = OpLoad %_ptr_Input_float %11
  304. // %13 = OpLoad %float %12
  305. //
  306. // corresponds to the pseudo-code:
  307. //
  308. // layout(location = 0) in flat float *%2
  309. // float %13;
  310. // float *%12;
  311. // float **%11;
  312. // *%11 = %2;
  313. // %12 = *%11;
  314. // %13 = *%12;
  315. //
  316. // which ultimately, should correspond to:
  317. //
  318. // %13 = *%2;
  319. //
  320. // During rewriting, the pointer %12 is found to be replaceable by %2 (i.e.,
  321. // load_replacement_[12] is 2). However, when processing the load
  322. // %13 = *%12, the type of %12's reaching definition is another float
  323. // pointer (%2), instead of a float value.
  324. //
  325. // When this happens, we need to continue looking up the reaching definition
  326. // chain until we get to a float value or a non-target var (i.e. a variable
  327. // that cannot be SSA replaced, like %2 in this case since it is a function
  328. // argument).
  329. analysis::DefUseManager* def_use_mgr = pass_->context()->get_def_use_mgr();
  330. analysis::TypeManager* type_mgr = pass_->context()->get_type_mgr();
  331. analysis::Type* load_type = type_mgr->GetType(inst->type_id());
  332. uint32_t val_id = 0;
  333. bool found_reaching_def = false;
  334. while (!found_reaching_def) {
  335. if (!pass_->IsTargetVar(var_id)) {
  336. // If the variable we are loading from is not an SSA target (globals,
  337. // function parameters), do nothing.
  338. return true;
  339. }
  340. val_id = GetReachingDef(var_id, bb);
  341. if (val_id == 0) {
  342. return false;
  343. }
  344. // If the reaching definition is a pointer type different than the type of
  345. // the instruction we are analyzing, then it must be a reference to another
  346. // pointer (otherwise, this would be invalid SPIRV). We continue
  347. // de-referencing it by making |val_id| be |var_id|.
  348. //
  349. // NOTE: if there is no reaching definition instruction, it means |val_id|
  350. // is an undef.
  351. Instruction* reaching_def_inst = def_use_mgr->GetDef(val_id);
  352. if (reaching_def_inst &&
  353. !type_mgr->GetType(reaching_def_inst->type_id())->IsSame(load_type)) {
  354. var_id = val_id;
  355. } else {
  356. found_reaching_def = true;
  357. }
  358. }
  359. // Schedule a replacement for the result of this load instruction with
  360. // |val_id|. After all the rewriting decisions are made, every use of
  361. // this load will be replaced with |val_id|.
  362. uint32_t load_id = inst->result_id();
  363. assert(load_replacement_.count(load_id) == 0);
  364. load_replacement_[load_id] = val_id;
  365. PhiCandidate* defining_phi = GetPhiCandidate(val_id);
  366. if (defining_phi) {
  367. defining_phi->AddUser(load_id);
  368. }
  369. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  370. std::cerr << "\tFound load: "
  371. << inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  372. << " (replacement for %" << load_id << " is %" << val_id << ")\n";
  373. #endif
  374. return true;
  375. }
  376. void SSARewriter::PrintPhiCandidates() const {
  377. std::cerr << "\nPhi candidates:\n";
  378. for (const auto& phi_it : phi_candidates_) {
  379. std::cerr << "\tBB %" << phi_it.second.bb()->id() << ": "
  380. << phi_it.second.PrettyPrint(pass_->cfg()) << "\n";
  381. }
  382. std::cerr << "\n";
  383. }
  384. void SSARewriter::PrintReplacementTable() const {
  385. std::cerr << "\nLoad replacement table\n";
  386. for (const auto& it : load_replacement_) {
  387. std::cerr << "\t%" << it.first << " -> %" << it.second << "\n";
  388. }
  389. std::cerr << "\n";
  390. }
  391. bool SSARewriter::GenerateSSAReplacements(BasicBlock* bb) {
  392. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  393. std::cerr << "Generating SSA replacements for block: " << bb->id() << "\n";
  394. std::cerr << bb->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  395. << "\n";
  396. #endif
  397. for (auto& inst : *bb) {
  398. auto opcode = inst.opcode();
  399. if (opcode == spv::Op::OpStore || opcode == spv::Op::OpVariable) {
  400. ProcessStore(&inst, bb);
  401. } else if (inst.opcode() == spv::Op::OpLoad) {
  402. if (!ProcessLoad(&inst, bb)) {
  403. return false;
  404. }
  405. }
  406. }
  407. // Seal |bb|. This means that all the stores in it have been scanned and
  408. // it's ready to feed them into its successors.
  409. SealBlock(bb);
  410. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  411. PrintPhiCandidates();
  412. PrintReplacementTable();
  413. std::cerr << "\n\n";
  414. #endif
  415. return true;
  416. }
  417. uint32_t SSARewriter::GetReplacement(std::pair<uint32_t, uint32_t> repl) {
  418. uint32_t val_id = repl.second;
  419. auto it = load_replacement_.find(val_id);
  420. while (it != load_replacement_.end()) {
  421. val_id = it->second;
  422. it = load_replacement_.find(val_id);
  423. }
  424. return val_id;
  425. }
  426. uint32_t SSARewriter::GetPhiArgument(const PhiCandidate* phi_candidate,
  427. uint32_t ix) {
  428. assert(phi_candidate->IsReady() &&
  429. "Tried to get the final argument from an incomplete/trivial Phi");
  430. uint32_t arg_id = phi_candidate->phi_args()[ix];
  431. while (arg_id != 0) {
  432. PhiCandidate* phi_user = GetPhiCandidate(arg_id);
  433. if (phi_user == nullptr || phi_user->IsReady()) {
  434. // If the argument is not a Phi or it's a Phi candidate ready to be
  435. // emitted, return it.
  436. return arg_id;
  437. }
  438. arg_id = phi_user->copy_of();
  439. }
  440. assert(false &&
  441. "No Phi candidates in the copy-of chain are ready to be generated");
  442. return 0;
  443. }
  444. bool SSARewriter::ApplyReplacements() {
  445. bool modified = false;
  446. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  447. std::cerr << "\n\nApplying replacement decisions to IR\n\n";
  448. PrintPhiCandidates();
  449. PrintReplacementTable();
  450. std::cerr << "\n\n";
  451. #endif
  452. // Add Phi instructions from completed Phi candidates.
  453. std::vector<Instruction*> generated_phis;
  454. for (const PhiCandidate* phi_candidate : phis_to_generate_) {
  455. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  456. std::cerr << "Phi candidate: " << phi_candidate->PrettyPrint(pass_->cfg())
  457. << "\n";
  458. #endif
  459. assert(phi_candidate->is_complete() &&
  460. "Tried to instantiate a Phi instruction from an incomplete Phi "
  461. "candidate");
  462. auto* local_var = pass_->get_def_use_mgr()->GetDef(phi_candidate->var_id());
  463. // Build the vector of operands for the new OpPhi instruction.
  464. uint32_t type_id = pass_->GetPointeeTypeId(local_var);
  465. std::vector<Operand> phi_operands;
  466. uint32_t arg_ix = 0;
  467. std::unordered_map<uint32_t, uint32_t> already_seen;
  468. for (uint32_t pred_label : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  469. uint32_t op_val_id = GetPhiArgument(phi_candidate, arg_ix++);
  470. if (already_seen.count(pred_label) == 0) {
  471. phi_operands.push_back(
  472. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {op_val_id}});
  473. phi_operands.push_back(
  474. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {pred_label}});
  475. already_seen[pred_label] = op_val_id;
  476. } else {
  477. // It is possible that there are two edges from the same parent block.
  478. // Since the OpPhi can have only one entry for each parent, we have to
  479. // make sure the two edges are consistent with each other.
  480. assert(already_seen[pred_label] == op_val_id &&
  481. "Inconsistent value for duplicate edges.");
  482. }
  483. }
  484. // Generate a new OpPhi instruction and insert it in its basic
  485. // block.
  486. std::unique_ptr<Instruction> phi_inst(
  487. new Instruction(pass_->context(), spv::Op::OpPhi, type_id,
  488. phi_candidate->result_id(), phi_operands));
  489. generated_phis.push_back(phi_inst.get());
  490. pass_->get_def_use_mgr()->AnalyzeInstDef(&*phi_inst);
  491. pass_->context()->set_instr_block(&*phi_inst, phi_candidate->bb());
  492. auto insert_it = phi_candidate->bb()->begin();
  493. insert_it = insert_it.InsertBefore(std::move(phi_inst));
  494. pass_->context()->get_decoration_mgr()->CloneDecorations(
  495. phi_candidate->var_id(), phi_candidate->result_id(),
  496. {spv::Decoration::RelaxedPrecision});
  497. // Add DebugValue for the new OpPhi instruction.
  498. insert_it->SetDebugScope(local_var->GetDebugScope());
  499. pass_->context()->get_debug_info_mgr()->AddDebugValueForVariable(
  500. &*insert_it, phi_candidate->var_id(), phi_candidate->result_id(),
  501. &*insert_it);
  502. modified = true;
  503. }
  504. // Scan uses for all inserted Phi instructions. Do this separately from the
  505. // registration of the Phi instruction itself to avoid trying to analyze
  506. // uses of Phi instructions that have not been registered yet.
  507. for (Instruction* phi_inst : generated_phis) {
  508. pass_->get_def_use_mgr()->AnalyzeInstUse(&*phi_inst);
  509. }
  510. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  511. std::cerr << "\n\nReplacing the result of load instructions with the "
  512. "corresponding SSA id\n\n";
  513. #endif
  514. // Apply replacements from the load replacement table.
  515. for (auto& repl : load_replacement_) {
  516. uint32_t load_id = repl.first;
  517. uint32_t val_id = GetReplacement(repl);
  518. Instruction* load_inst =
  519. pass_->context()->get_def_use_mgr()->GetDef(load_id);
  520. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  521. std::cerr << "\t"
  522. << load_inst->PrettyPrint(
  523. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  524. << " (%" << load_id << " -> %" << val_id << ")\n";
  525. #endif
  526. // Remove the load instruction and replace all the uses of this load's
  527. // result with |val_id|. Kill any names or decorates using the load's
  528. // result before replacing to prevent incorrect replacement in those
  529. // instructions.
  530. pass_->context()->KillNamesAndDecorates(load_id);
  531. pass_->context()->ReplaceAllUsesWith(load_id, val_id);
  532. pass_->context()->KillInst(load_inst);
  533. modified = true;
  534. }
  535. return modified;
  536. }
  537. void SSARewriter::FinalizePhiCandidate(PhiCandidate* phi_candidate) {
  538. assert(phi_candidate->phi_args().size() > 0 &&
  539. "Phi candidate should have arguments");
  540. uint32_t ix = 0;
  541. for (uint32_t pred : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  542. BasicBlock* pred_bb = pass_->cfg()->block(pred);
  543. uint32_t& arg_id = phi_candidate->phi_args()[ix++];
  544. if (arg_id == 0) {
  545. // If |pred_bb| is still not sealed, it means it's unreachable. In this
  546. // case, we just use Undef as an argument.
  547. arg_id = IsBlockSealed(pred_bb)
  548. ? GetReachingDef(phi_candidate->var_id(), pred_bb)
  549. : pass_->GetUndefVal(phi_candidate->var_id());
  550. }
  551. }
  552. // This candidate is now completed.
  553. phi_candidate->MarkComplete();
  554. // If |phi_candidate| is not trivial, add it to the list of Phis to
  555. // generate.
  556. if (TryRemoveTrivialPhi(phi_candidate) == phi_candidate->result_id()) {
  557. // If we could not remove |phi_candidate|, it means that it is complete
  558. // and not trivial. Add it to the list of Phis to generate.
  559. assert(!phi_candidate->copy_of() && "A completed Phi cannot be trivial.");
  560. phis_to_generate_.push_back(phi_candidate);
  561. }
  562. }
  563. void SSARewriter::FinalizePhiCandidates() {
  564. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  565. std::cerr << "Finalizing Phi candidates:\n\n";
  566. PrintPhiCandidates();
  567. std::cerr << "\n";
  568. #endif
  569. // Now, complete the collected candidates.
  570. while (incomplete_phis_.size() > 0) {
  571. PhiCandidate* phi_candidate = incomplete_phis_.front();
  572. incomplete_phis_.pop();
  573. FinalizePhiCandidate(phi_candidate);
  574. }
  575. }
  576. Pass::Status SSARewriter::RewriteFunctionIntoSSA(Function* fp) {
  577. #if SSA_REWRITE_DEBUGGING_LEVEL > 0
  578. std::cerr << "Function before SSA rewrite:\n"
  579. << fp->PrettyPrint(0) << "\n\n\n";
  580. #endif
  581. // Collect variables that can be converted into SSA IDs.
  582. pass_->CollectTargetVars(fp);
  583. // Generate all the SSA replacements and Phi candidates. This will
  584. // generate incomplete and trivial Phis.
  585. bool succeeded = pass_->cfg()->WhileEachBlockInReversePostOrder(
  586. fp->entry().get(), [this](BasicBlock* bb) {
  587. if (!GenerateSSAReplacements(bb)) {
  588. return false;
  589. }
  590. return true;
  591. });
  592. if (!succeeded) {
  593. return Pass::Status::Failure;
  594. }
  595. // Remove trivial Phis and add arguments to incomplete Phis.
  596. FinalizePhiCandidates();
  597. // Finally, apply all the replacements in the IR.
  598. bool modified = ApplyReplacements();
  599. #if SSA_REWRITE_DEBUGGING_LEVEL > 0
  600. std::cerr << "\n\n\nFunction after SSA rewrite:\n"
  601. << fp->PrettyPrint(0) << "\n";
  602. #endif
  603. return modified ? Pass::Status::SuccessWithChange
  604. : Pass::Status::SuccessWithoutChange;
  605. }
  606. Pass::Status SSARewritePass::Process() {
  607. Status status = Status::SuccessWithoutChange;
  608. for (auto& fn : *get_module()) {
  609. if (fn.IsDeclaration()) {
  610. continue;
  611. }
  612. status =
  613. CombineStatus(status, SSARewriter(this).RewriteFunctionIntoSSA(&fn));
  614. // Kill DebugDeclares for target variables.
  615. for (auto var_id : seen_target_vars_) {
  616. context()->get_debug_info_mgr()->KillDebugDeclares(var_id);
  617. }
  618. if (status == Status::Failure) {
  619. break;
  620. }
  621. }
  622. return status;
  623. }
  624. } // namespace opt
  625. } // namespace spvtools