ssa_rewrite_pass.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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/util/make_unique.h"
  47. // Debug logging (0: Off, 1-N: Verbosity level). Replace this with the
  48. // implementation done for
  49. // https://github.com/KhronosGroup/SPIRV-Tools/issues/1351
  50. // #define SSA_REWRITE_DEBUGGING_LEVEL 3
  51. #ifdef SSA_REWRITE_DEBUGGING_LEVEL
  52. #include <ostream>
  53. #else
  54. #define SSA_REWRITE_DEBUGGING_LEVEL 0
  55. #endif
  56. namespace spvtools {
  57. namespace opt {
  58. namespace {
  59. const uint32_t kStoreValIdInIdx = 1;
  60. const uint32_t kVariableInitIdInIdx = 1;
  61. } // namespace
  62. std::string SSARewriter::PhiCandidate::PrettyPrint(const CFG* cfg) const {
  63. std::ostringstream str;
  64. str << "%" << result_id_ << " = Phi[%" << var_id_ << ", BB %" << bb_->id()
  65. << "](";
  66. if (phi_args_.size() > 0) {
  67. uint32_t arg_ix = 0;
  68. for (uint32_t pred_label : cfg->preds(bb_->id())) {
  69. uint32_t arg_id = phi_args_[arg_ix++];
  70. str << "[%" << arg_id << ", bb(%" << pred_label << ")] ";
  71. }
  72. }
  73. str << ")";
  74. if (copy_of_ != 0) {
  75. str << " [COPY OF " << copy_of_ << "]";
  76. }
  77. str << ((is_complete_) ? " [COMPLETE]" : " [INCOMPLETE]");
  78. return str.str();
  79. }
  80. SSARewriter::PhiCandidate& SSARewriter::CreatePhiCandidate(uint32_t var_id,
  81. BasicBlock* bb) {
  82. // TODO(1841): Handle id overflow.
  83. uint32_t phi_result_id = pass_->context()->TakeNextId();
  84. auto result = phi_candidates_.emplace(
  85. phi_result_id, PhiCandidate(var_id, phi_result_id, bb));
  86. PhiCandidate& phi_candidate = result.first->second;
  87. return phi_candidate;
  88. }
  89. void SSARewriter::ReplacePhiUsersWith(const PhiCandidate& phi_to_remove,
  90. uint32_t repl_id) {
  91. for (uint32_t user_id : phi_to_remove.users()) {
  92. PhiCandidate* user_phi = GetPhiCandidate(user_id);
  93. BasicBlock* bb = pass_->context()->get_instr_block(user_id);
  94. if (user_phi) {
  95. // If the user is a Phi candidate, replace all arguments that refer to
  96. // |phi_to_remove.result_id()| with |repl_id|.
  97. for (uint32_t& arg : user_phi->phi_args()) {
  98. if (arg == phi_to_remove.result_id()) {
  99. arg = repl_id;
  100. }
  101. }
  102. } else if (bb->id() == user_id) {
  103. // The phi candidate is the definition of the variable at basic block
  104. // |bb|. We must change this to the replacement.
  105. WriteVariable(phi_to_remove.var_id(), bb, repl_id);
  106. } else {
  107. // For regular loads, traverse the |load_replacement_| table looking for
  108. // instances of |phi_to_remove|.
  109. for (auto& it : load_replacement_) {
  110. if (it.second == phi_to_remove.result_id()) {
  111. it.second = repl_id;
  112. }
  113. }
  114. }
  115. }
  116. }
  117. uint32_t SSARewriter::TryRemoveTrivialPhi(PhiCandidate* phi_candidate) {
  118. uint32_t same_id = 0;
  119. for (uint32_t arg_id : phi_candidate->phi_args()) {
  120. if (arg_id == same_id || arg_id == phi_candidate->result_id()) {
  121. // This is a self-reference operand or a reference to the same value ID.
  122. continue;
  123. }
  124. if (same_id != 0) {
  125. // This Phi candidate merges at least two values. Therefore, it is not
  126. // trivial.
  127. assert(phi_candidate->copy_of() == 0 &&
  128. "Phi candidate transitioning from copy to non-copy.");
  129. return phi_candidate->result_id();
  130. }
  131. same_id = arg_id;
  132. }
  133. // The previous logic has determined that this Phi candidate |phi_candidate|
  134. // is trivial. It is essentially the copy operation phi_candidate->phi_result
  135. // = Phi(same, same, same, ...). Since it is not necessary, we can re-route
  136. // all the users of |phi_candidate->phi_result| to all its users, and remove
  137. // |phi_candidate|.
  138. // Mark the Phi candidate as a trivial copy of |same_id|, so it won't be
  139. // generated.
  140. phi_candidate->MarkCopyOf(same_id);
  141. assert(same_id != 0 && "Completed Phis cannot have %0 in their arguments");
  142. // Since |phi_candidate| always produces |same_id|, replace all the users of
  143. // |phi_candidate| with |same_id|.
  144. ReplacePhiUsersWith(*phi_candidate, same_id);
  145. return same_id;
  146. }
  147. uint32_t SSARewriter::AddPhiOperands(PhiCandidate* phi_candidate) {
  148. assert(phi_candidate->phi_args().size() == 0 &&
  149. "Phi candidate already has arguments");
  150. bool found_0_arg = false;
  151. for (uint32_t pred : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  152. BasicBlock* pred_bb = pass_->cfg()->block(pred);
  153. // If |pred_bb| is not sealed, use %0 to indicate that
  154. // |phi_candidate| needs to be completed after the whole CFG has
  155. // been processed.
  156. //
  157. // Note that we cannot call GetReachingDef() in these cases
  158. // because this would generate an empty Phi candidate in
  159. // |pred_bb|. When |pred_bb| is later processed, a new definition
  160. // for |phi_candidate->var_id_| will be lost because
  161. // |phi_candidate| will still be reached by the empty Phi.
  162. //
  163. // Consider:
  164. //
  165. // BB %23:
  166. // %38 = Phi[%i](%int_0[%1], %39[%25])
  167. //
  168. // ...
  169. //
  170. // BB %25: [Starts unsealed]
  171. // %39 = Phi[%i]()
  172. // %34 = ...
  173. // OpStore %i %34 -> Currdef(%i) at %25 is %34
  174. // OpBranch %23
  175. //
  176. // When we first create the Phi in %38, we add an operandless Phi in
  177. // %39 to hold the unknown reaching def for %i.
  178. //
  179. // But then, when we go to complete %39 at the end. The reaching def
  180. // for %i in %25's predecessor is %38 itself. So we miss the fact
  181. // that %25 has a def for %i that should be used.
  182. //
  183. // By making the argument %0, we make |phi_candidate| incomplete,
  184. // which will cause it to be completed after the whole CFG has
  185. // been scanned.
  186. uint32_t arg_id = IsBlockSealed(pred_bb)
  187. ? GetReachingDef(phi_candidate->var_id(), pred_bb)
  188. : 0;
  189. phi_candidate->phi_args().push_back(arg_id);
  190. if (arg_id == 0) {
  191. found_0_arg = true;
  192. } else {
  193. // If this argument is another Phi candidate, add |phi_candidate| to the
  194. // list of users for the defining Phi.
  195. PhiCandidate* defining_phi = GetPhiCandidate(arg_id);
  196. if (defining_phi && defining_phi != phi_candidate) {
  197. defining_phi->AddUser(phi_candidate->result_id());
  198. }
  199. }
  200. }
  201. // If we could not fill-in all the arguments of this Phi, mark it incomplete
  202. // so it gets completed after the whole CFG has been processed.
  203. if (found_0_arg) {
  204. phi_candidate->MarkIncomplete();
  205. incomplete_phis_.push(phi_candidate);
  206. return phi_candidate->result_id();
  207. }
  208. // Try to remove |phi_candidate|, if it's trivial.
  209. uint32_t repl_id = TryRemoveTrivialPhi(phi_candidate);
  210. if (repl_id == phi_candidate->result_id()) {
  211. // |phi_candidate| is complete and not trivial. Add it to the
  212. // list of Phi candidates to generate.
  213. phi_candidate->MarkComplete();
  214. phis_to_generate_.push_back(phi_candidate);
  215. }
  216. return repl_id;
  217. }
  218. uint32_t SSARewriter::GetReachingDef(uint32_t var_id, BasicBlock* bb) {
  219. // If |var_id| has a definition in |bb|, return it.
  220. const auto& bb_it = defs_at_block_.find(bb);
  221. if (bb_it != defs_at_block_.end()) {
  222. const auto& current_defs = bb_it->second;
  223. const auto& var_it = current_defs.find(var_id);
  224. if (var_it != current_defs.end()) {
  225. return var_it->second;
  226. }
  227. }
  228. // Otherwise, look up the value for |var_id| in |bb|'s predecessors.
  229. uint32_t val_id = 0;
  230. auto& predecessors = pass_->cfg()->preds(bb->id());
  231. if (predecessors.size() == 1) {
  232. // If |bb| has exactly one predecessor, we look for |var_id|'s definition
  233. // there.
  234. val_id = GetReachingDef(var_id, pass_->cfg()->block(predecessors[0]));
  235. } else if (predecessors.size() > 1) {
  236. // If there is more than one predecessor, this is a join block which may
  237. // require a Phi instruction. This will act as |var_id|'s current
  238. // definition to break potential cycles.
  239. PhiCandidate& phi_candidate = CreatePhiCandidate(var_id, bb);
  240. // Set the value for |bb| to avoid an infinite recursion.
  241. WriteVariable(var_id, bb, phi_candidate.result_id());
  242. val_id = AddPhiOperands(&phi_candidate);
  243. }
  244. // If we could not find a store for this variable in the path from the root
  245. // of the CFG, the variable is not defined, so we use undef.
  246. if (val_id == 0) {
  247. val_id = pass_->GetUndefVal(var_id);
  248. if (val_id == 0) {
  249. return 0;
  250. }
  251. }
  252. WriteVariable(var_id, bb, val_id);
  253. return val_id;
  254. }
  255. void SSARewriter::SealBlock(BasicBlock* bb) {
  256. auto result = sealed_blocks_.insert(bb);
  257. (void)result;
  258. assert(result.second == true &&
  259. "Tried to seal the same basic block more than once.");
  260. }
  261. void SSARewriter::ProcessStore(Instruction* inst, BasicBlock* bb) {
  262. auto opcode = inst->opcode();
  263. assert((opcode == SpvOpStore || opcode == SpvOpVariable) &&
  264. "Expecting a store or a variable definition instruction.");
  265. uint32_t var_id = 0;
  266. uint32_t val_id = 0;
  267. if (opcode == SpvOpStore) {
  268. (void)pass_->GetPtr(inst, &var_id);
  269. val_id = inst->GetSingleWordInOperand(kStoreValIdInIdx);
  270. } else if (inst->NumInOperands() >= 2) {
  271. var_id = inst->result_id();
  272. val_id = inst->GetSingleWordInOperand(kVariableInitIdInIdx);
  273. }
  274. if (pass_->IsTargetVar(var_id)) {
  275. WriteVariable(var_id, bb, val_id);
  276. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  277. std::cerr << "\tFound store '%" << var_id << " = %" << val_id << "': "
  278. << inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  279. << "\n";
  280. #endif
  281. }
  282. }
  283. bool SSARewriter::ProcessLoad(Instruction* inst, BasicBlock* bb) {
  284. uint32_t var_id = 0;
  285. (void)pass_->GetPtr(inst, &var_id);
  286. if (pass_->IsTargetVar(var_id)) {
  287. // Get the immediate reaching definition for |var_id|.
  288. uint32_t val_id = GetReachingDef(var_id, bb);
  289. if (val_id == 0) {
  290. return false;
  291. }
  292. // Schedule a replacement for the result of this load instruction with
  293. // |val_id|. After all the rewriting decisions are made, every use of
  294. // this load will be replaced with |val_id|.
  295. const uint32_t load_id = inst->result_id();
  296. assert(load_replacement_.count(load_id) == 0);
  297. load_replacement_[load_id] = val_id;
  298. PhiCandidate* defining_phi = GetPhiCandidate(val_id);
  299. if (defining_phi) {
  300. defining_phi->AddUser(load_id);
  301. }
  302. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  303. std::cerr << "\tFound load: "
  304. << inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  305. << " (replacement for %" << load_id << " is %" << val_id << ")\n";
  306. #endif
  307. }
  308. return true;
  309. }
  310. void SSARewriter::PrintPhiCandidates() const {
  311. std::cerr << "\nPhi candidates:\n";
  312. for (const auto& phi_it : phi_candidates_) {
  313. std::cerr << "\tBB %" << phi_it.second.bb()->id() << ": "
  314. << phi_it.second.PrettyPrint(pass_->cfg()) << "\n";
  315. }
  316. std::cerr << "\n";
  317. }
  318. void SSARewriter::PrintReplacementTable() const {
  319. std::cerr << "\nLoad replacement table\n";
  320. for (const auto& it : load_replacement_) {
  321. std::cerr << "\t%" << it.first << " -> %" << it.second << "\n";
  322. }
  323. std::cerr << "\n";
  324. }
  325. bool SSARewriter::GenerateSSAReplacements(BasicBlock* bb) {
  326. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  327. std::cerr << "Generating SSA replacements for block: " << bb->id() << "\n";
  328. std::cerr << bb->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  329. << "\n";
  330. #endif
  331. for (auto& inst : *bb) {
  332. auto opcode = inst.opcode();
  333. if (opcode == SpvOpStore || opcode == SpvOpVariable) {
  334. ProcessStore(&inst, bb);
  335. } else if (inst.opcode() == SpvOpLoad) {
  336. if (!ProcessLoad(&inst, bb)) {
  337. return false;
  338. }
  339. }
  340. }
  341. // Seal |bb|. This means that all the stores in it have been scanned and it's
  342. // ready to feed them into its successors.
  343. SealBlock(bb);
  344. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  345. PrintPhiCandidates();
  346. PrintReplacementTable();
  347. std::cerr << "\n\n";
  348. #endif
  349. return true;
  350. }
  351. uint32_t SSARewriter::GetReplacement(std::pair<uint32_t, uint32_t> repl) {
  352. uint32_t val_id = repl.second;
  353. auto it = load_replacement_.find(val_id);
  354. while (it != load_replacement_.end()) {
  355. val_id = it->second;
  356. it = load_replacement_.find(val_id);
  357. }
  358. return val_id;
  359. }
  360. uint32_t SSARewriter::GetPhiArgument(const PhiCandidate* phi_candidate,
  361. uint32_t ix) {
  362. assert(phi_candidate->IsReady() &&
  363. "Tried to get the final argument from an incomplete/trivial Phi");
  364. uint32_t arg_id = phi_candidate->phi_args()[ix];
  365. while (arg_id != 0) {
  366. PhiCandidate* phi_user = GetPhiCandidate(arg_id);
  367. if (phi_user == nullptr || phi_user->IsReady()) {
  368. // If the argument is not a Phi or it's a Phi candidate ready to be
  369. // emitted, return it.
  370. return arg_id;
  371. }
  372. arg_id = phi_user->copy_of();
  373. }
  374. assert(false &&
  375. "No Phi candidates in the copy-of chain are ready to be generated");
  376. return 0;
  377. }
  378. bool SSARewriter::ApplyReplacements() {
  379. bool modified = false;
  380. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  381. std::cerr << "\n\nApplying replacement decisions to IR\n\n";
  382. PrintPhiCandidates();
  383. PrintReplacementTable();
  384. std::cerr << "\n\n";
  385. #endif
  386. // Add Phi instructions from completed Phi candidates.
  387. std::vector<Instruction*> generated_phis;
  388. for (const PhiCandidate* phi_candidate : phis_to_generate_) {
  389. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  390. std::cerr << "Phi candidate: " << phi_candidate->PrettyPrint(pass_->cfg())
  391. << "\n";
  392. #endif
  393. assert(phi_candidate->is_complete() &&
  394. "Tried to instantiate a Phi instruction from an incomplete Phi "
  395. "candidate");
  396. // Build the vector of operands for the new OpPhi instruction.
  397. uint32_t type_id = pass_->GetPointeeTypeId(
  398. pass_->get_def_use_mgr()->GetDef(phi_candidate->var_id()));
  399. std::vector<Operand> phi_operands;
  400. uint32_t arg_ix = 0;
  401. std::unordered_map<uint32_t, uint32_t> already_seen;
  402. for (uint32_t pred_label : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  403. uint32_t op_val_id = GetPhiArgument(phi_candidate, arg_ix++);
  404. if (already_seen.count(pred_label) == 0) {
  405. phi_operands.push_back(
  406. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {op_val_id}});
  407. phi_operands.push_back(
  408. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {pred_label}});
  409. already_seen[pred_label] = op_val_id;
  410. } else {
  411. // It is possible that there are two edges from the same parent block.
  412. // Since the OpPhi can have only one entry for each parent, we have to
  413. // make sure the two edges are consistent with each other.
  414. assert(already_seen[pred_label] == op_val_id &&
  415. "Inconsistent value for duplicate edges.");
  416. }
  417. }
  418. // Generate a new OpPhi instruction and insert it in its basic
  419. // block.
  420. std::unique_ptr<Instruction> phi_inst(
  421. new Instruction(pass_->context(), SpvOpPhi, type_id,
  422. phi_candidate->result_id(), phi_operands));
  423. generated_phis.push_back(phi_inst.get());
  424. pass_->get_def_use_mgr()->AnalyzeInstDef(&*phi_inst);
  425. pass_->context()->set_instr_block(&*phi_inst, phi_candidate->bb());
  426. auto insert_it = phi_candidate->bb()->begin();
  427. insert_it.InsertBefore(std::move(phi_inst));
  428. pass_->context()->get_decoration_mgr()->CloneDecorations(
  429. phi_candidate->var_id(), phi_candidate->result_id(),
  430. {SpvDecorationRelaxedPrecision});
  431. modified = true;
  432. }
  433. // Scan uses for all inserted Phi instructions. Do this separately from the
  434. // registration of the Phi instruction itself to avoid trying to analyze uses
  435. // of Phi instructions that have not been registered yet.
  436. for (Instruction* phi_inst : generated_phis) {
  437. pass_->get_def_use_mgr()->AnalyzeInstUse(&*phi_inst);
  438. }
  439. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  440. std::cerr << "\n\nReplacing the result of load instructions with the "
  441. "corresponding SSA id\n\n";
  442. #endif
  443. // Apply replacements from the load replacement table.
  444. for (auto& repl : load_replacement_) {
  445. uint32_t load_id = repl.first;
  446. uint32_t val_id = GetReplacement(repl);
  447. Instruction* load_inst =
  448. pass_->context()->get_def_use_mgr()->GetDef(load_id);
  449. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  450. std::cerr << "\t"
  451. << load_inst->PrettyPrint(
  452. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  453. << " (%" << load_id << " -> %" << val_id << ")\n";
  454. #endif
  455. // Remove the load instruction and replace all the uses of this load's
  456. // result with |val_id|. Kill any names or decorates using the load's
  457. // result before replacing to prevent incorrect replacement in those
  458. // instructions.
  459. pass_->context()->KillNamesAndDecorates(load_id);
  460. pass_->context()->ReplaceAllUsesWith(load_id, val_id);
  461. pass_->context()->KillInst(load_inst);
  462. modified = true;
  463. }
  464. return modified;
  465. }
  466. void SSARewriter::FinalizePhiCandidate(PhiCandidate* phi_candidate) {
  467. assert(phi_candidate->phi_args().size() > 0 &&
  468. "Phi candidate should have arguments");
  469. uint32_t ix = 0;
  470. for (uint32_t pred : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  471. BasicBlock* pred_bb = pass_->cfg()->block(pred);
  472. uint32_t& arg_id = phi_candidate->phi_args()[ix++];
  473. if (arg_id == 0) {
  474. // If |pred_bb| is still not sealed, it means it's unreachable. In this
  475. // case, we just use Undef as an argument.
  476. arg_id = IsBlockSealed(pred_bb)
  477. ? GetReachingDef(phi_candidate->var_id(), pred_bb)
  478. : pass_->GetUndefVal(phi_candidate->var_id());
  479. }
  480. }
  481. // This candidate is now completed.
  482. phi_candidate->MarkComplete();
  483. // If |phi_candidate| is not trivial, add it to the list of Phis to generate.
  484. if (TryRemoveTrivialPhi(phi_candidate) == phi_candidate->result_id()) {
  485. // If we could not remove |phi_candidate|, it means that it is complete
  486. // and not trivial. Add it to the list of Phis to generate.
  487. assert(!phi_candidate->copy_of() && "A completed Phi cannot be trivial.");
  488. phis_to_generate_.push_back(phi_candidate);
  489. }
  490. }
  491. void SSARewriter::FinalizePhiCandidates() {
  492. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  493. std::cerr << "Finalizing Phi candidates:\n\n";
  494. PrintPhiCandidates();
  495. std::cerr << "\n";
  496. #endif
  497. // Now, complete the collected candidates.
  498. while (incomplete_phis_.size() > 0) {
  499. PhiCandidate* phi_candidate = incomplete_phis_.front();
  500. incomplete_phis_.pop();
  501. FinalizePhiCandidate(phi_candidate);
  502. }
  503. }
  504. Pass::Status SSARewriter::RewriteFunctionIntoSSA(Function* fp) {
  505. #if SSA_REWRITE_DEBUGGING_LEVEL > 0
  506. std::cerr << "Function before SSA rewrite:\n"
  507. << fp->PrettyPrint(0) << "\n\n\n";
  508. #endif
  509. // Collect variables that can be converted into SSA IDs.
  510. pass_->CollectTargetVars(fp);
  511. // Generate all the SSA replacements and Phi candidates. This will
  512. // generate incomplete and trivial Phis.
  513. bool succeeded = pass_->cfg()->WhileEachBlockInReversePostOrder(
  514. fp->entry().get(), [this](BasicBlock* bb) {
  515. if (!GenerateSSAReplacements(bb)) {
  516. return false;
  517. }
  518. return true;
  519. });
  520. if (!succeeded) {
  521. return Pass::Status::Failure;
  522. }
  523. // Remove trivial Phis and add arguments to incomplete Phis.
  524. FinalizePhiCandidates();
  525. // Finally, apply all the replacements in the IR.
  526. bool modified = ApplyReplacements();
  527. #if SSA_REWRITE_DEBUGGING_LEVEL > 0
  528. std::cerr << "\n\n\nFunction after SSA rewrite:\n"
  529. << fp->PrettyPrint(0) << "\n";
  530. #endif
  531. return modified ? Pass::Status::SuccessWithChange
  532. : Pass::Status::SuccessWithoutChange;
  533. }
  534. Pass::Status SSARewritePass::Process() {
  535. Status status = Status::SuccessWithoutChange;
  536. for (auto& fn : *get_module()) {
  537. status =
  538. CombineStatus(status, SSARewriter(this).RewriteFunctionIntoSSA(&fn));
  539. if (status == Status::Failure) {
  540. break;
  541. }
  542. }
  543. return status;
  544. }
  545. } // namespace opt
  546. } // namespace spvtools