ssa_rewrite_pass.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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. // 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. constexpr uint32_t kStoreValIdInIdx = 1;
  60. constexpr 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::GetValueAtBlock(uint32_t var_id, BasicBlock* bb) {
  219. assert(bb != nullptr);
  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. return 0;
  229. }
  230. uint32_t SSARewriter::GetReachingDef(uint32_t var_id, BasicBlock* bb) {
  231. // If |var_id| has a definition in |bb|, return it.
  232. uint32_t val_id = GetValueAtBlock(var_id, bb);
  233. if (val_id != 0) return val_id;
  234. // Otherwise, look up the value for |var_id| in |bb|'s predecessors.
  235. auto& predecessors = pass_->cfg()->preds(bb->id());
  236. if (predecessors.size() == 1) {
  237. // If |bb| has exactly one predecessor, we look for |var_id|'s definition
  238. // there.
  239. val_id = GetReachingDef(var_id, pass_->cfg()->block(predecessors[0]));
  240. } else if (predecessors.size() > 1) {
  241. // If there is more than one predecessor, this is a join block which may
  242. // require a Phi instruction. This will act as |var_id|'s current
  243. // definition to break potential cycles.
  244. PhiCandidate& phi_candidate = CreatePhiCandidate(var_id, bb);
  245. // Set the value for |bb| to avoid an infinite recursion.
  246. WriteVariable(var_id, bb, phi_candidate.result_id());
  247. val_id = AddPhiOperands(&phi_candidate);
  248. }
  249. // If we could not find a store for this variable in the path from the root
  250. // of the CFG, the variable is not defined, so we use undef.
  251. if (val_id == 0) {
  252. val_id = pass_->GetUndefVal(var_id);
  253. if (val_id == 0) {
  254. return 0;
  255. }
  256. }
  257. WriteVariable(var_id, bb, val_id);
  258. return val_id;
  259. }
  260. void SSARewriter::SealBlock(BasicBlock* bb) {
  261. auto result = sealed_blocks_.insert(bb);
  262. (void)result;
  263. assert(result.second == true &&
  264. "Tried to seal the same basic block more than once.");
  265. }
  266. void SSARewriter::ProcessStore(Instruction* inst, BasicBlock* bb) {
  267. auto opcode = inst->opcode();
  268. assert((opcode == spv::Op::OpStore || opcode == spv::Op::OpVariable) &&
  269. "Expecting a store or a variable definition instruction.");
  270. uint32_t var_id = 0;
  271. uint32_t val_id = 0;
  272. if (opcode == spv::Op::OpStore) {
  273. (void)pass_->GetPtr(inst, &var_id);
  274. val_id = inst->GetSingleWordInOperand(kStoreValIdInIdx);
  275. } else if (inst->NumInOperands() >= 2) {
  276. var_id = inst->result_id();
  277. val_id = inst->GetSingleWordInOperand(kVariableInitIdInIdx);
  278. }
  279. if (pass_->IsTargetVar(var_id)) {
  280. WriteVariable(var_id, bb, val_id);
  281. pass_->context()->get_debug_info_mgr()->AddDebugValueForVariable(
  282. inst, var_id, val_id, inst);
  283. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  284. std::cerr << "\tFound store '%" << var_id << " = %" << val_id << "': "
  285. << inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  286. << "\n";
  287. #endif
  288. }
  289. }
  290. bool SSARewriter::ProcessLoad(Instruction* inst, BasicBlock* bb) {
  291. // Get the pointer that we are using to load from.
  292. uint32_t var_id = 0;
  293. (void)pass_->GetPtr(inst, &var_id);
  294. // Get the immediate reaching definition for |var_id|.
  295. //
  296. // In the presence of variable pointers, the reaching definition may be
  297. // another pointer. For example, the following fragment:
  298. //
  299. // %2 = OpVariable %_ptr_Input_float Input
  300. // %11 = OpVariable %_ptr_Function__ptr_Input_float Function
  301. // OpStore %11 %2
  302. // %12 = OpLoad %_ptr_Input_float %11
  303. // %13 = OpLoad %float %12
  304. //
  305. // corresponds to the pseudo-code:
  306. //
  307. // layout(location = 0) in flat float *%2
  308. // float %13;
  309. // float *%12;
  310. // float **%11;
  311. // *%11 = %2;
  312. // %12 = *%11;
  313. // %13 = *%12;
  314. //
  315. // which ultimately, should correspond to:
  316. //
  317. // %13 = *%2;
  318. //
  319. // During rewriting, the pointer %12 is found to be replaceable by %2 (i.e.,
  320. // load_replacement_[12] is 2). However, when processing the load
  321. // %13 = *%12, the type of %12's reaching definition is another float
  322. // pointer (%2), instead of a float value.
  323. //
  324. // When this happens, we need to continue looking up the reaching definition
  325. // chain until we get to a float value or a non-target var (i.e. a variable
  326. // that cannot be SSA replaced, like %2 in this case since it is a function
  327. // argument).
  328. analysis::DefUseManager* def_use_mgr = pass_->context()->get_def_use_mgr();
  329. analysis::TypeManager* type_mgr = pass_->context()->get_type_mgr();
  330. analysis::Type* load_type = type_mgr->GetType(inst->type_id());
  331. uint32_t val_id = 0;
  332. bool found_reaching_def = false;
  333. while (!found_reaching_def) {
  334. if (!pass_->IsTargetVar(var_id)) {
  335. // If the variable we are loading from is not an SSA target (globals,
  336. // function parameters), do nothing.
  337. return true;
  338. }
  339. val_id = GetReachingDef(var_id, bb);
  340. if (val_id == 0) {
  341. return false;
  342. }
  343. // If the reaching definition is a pointer type different than the type of
  344. // the instruction we are analyzing, then it must be a reference to another
  345. // pointer (otherwise, this would be invalid SPIRV). We continue
  346. // de-referencing it by making |val_id| be |var_id|.
  347. //
  348. // NOTE: if there is no reaching definition instruction, it means |val_id|
  349. // is an undef.
  350. Instruction* reaching_def_inst = def_use_mgr->GetDef(val_id);
  351. if (reaching_def_inst &&
  352. !type_mgr->GetType(reaching_def_inst->type_id())->IsSame(load_type)) {
  353. var_id = val_id;
  354. } else {
  355. found_reaching_def = true;
  356. }
  357. }
  358. // Schedule a replacement for the result of this load instruction with
  359. // |val_id|. After all the rewriting decisions are made, every use of
  360. // this load will be replaced with |val_id|.
  361. uint32_t load_id = inst->result_id();
  362. assert(load_replacement_.count(load_id) == 0);
  363. load_replacement_[load_id] = val_id;
  364. PhiCandidate* defining_phi = GetPhiCandidate(val_id);
  365. if (defining_phi) {
  366. defining_phi->AddUser(load_id);
  367. }
  368. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  369. std::cerr << "\tFound load: "
  370. << inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  371. << " (replacement for %" << load_id << " is %" << val_id << ")\n";
  372. #endif
  373. return true;
  374. }
  375. void SSARewriter::PrintPhiCandidates() const {
  376. std::cerr << "\nPhi candidates:\n";
  377. for (const auto& phi_it : phi_candidates_) {
  378. std::cerr << "\tBB %" << phi_it.second.bb()->id() << ": "
  379. << phi_it.second.PrettyPrint(pass_->cfg()) << "\n";
  380. }
  381. std::cerr << "\n";
  382. }
  383. void SSARewriter::PrintReplacementTable() const {
  384. std::cerr << "\nLoad replacement table\n";
  385. for (const auto& it : load_replacement_) {
  386. std::cerr << "\t%" << it.first << " -> %" << it.second << "\n";
  387. }
  388. std::cerr << "\n";
  389. }
  390. bool SSARewriter::GenerateSSAReplacements(BasicBlock* bb) {
  391. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  392. std::cerr << "Generating SSA replacements for block: " << bb->id() << "\n";
  393. std::cerr << bb->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  394. << "\n";
  395. #endif
  396. for (auto& inst : *bb) {
  397. auto opcode = inst.opcode();
  398. if (opcode == spv::Op::OpStore || opcode == spv::Op::OpVariable) {
  399. ProcessStore(&inst, bb);
  400. } else if (inst.opcode() == spv::Op::OpLoad) {
  401. if (!ProcessLoad(&inst, bb)) {
  402. return false;
  403. }
  404. }
  405. }
  406. // Seal |bb|. This means that all the stores in it have been scanned and
  407. // it's ready to feed them into its successors.
  408. SealBlock(bb);
  409. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  410. PrintPhiCandidates();
  411. PrintReplacementTable();
  412. std::cerr << "\n\n";
  413. #endif
  414. return true;
  415. }
  416. uint32_t SSARewriter::GetReplacement(std::pair<uint32_t, uint32_t> repl) {
  417. uint32_t val_id = repl.second;
  418. auto it = load_replacement_.find(val_id);
  419. while (it != load_replacement_.end()) {
  420. val_id = it->second;
  421. it = load_replacement_.find(val_id);
  422. }
  423. return val_id;
  424. }
  425. uint32_t SSARewriter::GetPhiArgument(const PhiCandidate* phi_candidate,
  426. uint32_t ix) {
  427. assert(phi_candidate->IsReady() &&
  428. "Tried to get the final argument from an incomplete/trivial Phi");
  429. uint32_t arg_id = phi_candidate->phi_args()[ix];
  430. while (arg_id != 0) {
  431. PhiCandidate* phi_user = GetPhiCandidate(arg_id);
  432. if (phi_user == nullptr || phi_user->IsReady()) {
  433. // If the argument is not a Phi or it's a Phi candidate ready to be
  434. // emitted, return it.
  435. return arg_id;
  436. }
  437. arg_id = phi_user->copy_of();
  438. }
  439. assert(false &&
  440. "No Phi candidates in the copy-of chain are ready to be generated");
  441. return 0;
  442. }
  443. bool SSARewriter::ApplyReplacements() {
  444. bool modified = false;
  445. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  446. std::cerr << "\n\nApplying replacement decisions to IR\n\n";
  447. PrintPhiCandidates();
  448. PrintReplacementTable();
  449. std::cerr << "\n\n";
  450. #endif
  451. // Add Phi instructions from completed Phi candidates.
  452. std::vector<Instruction*> generated_phis;
  453. for (const PhiCandidate* phi_candidate : phis_to_generate_) {
  454. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  455. std::cerr << "Phi candidate: " << phi_candidate->PrettyPrint(pass_->cfg())
  456. << "\n";
  457. #endif
  458. assert(phi_candidate->is_complete() &&
  459. "Tried to instantiate a Phi instruction from an incomplete Phi "
  460. "candidate");
  461. auto* local_var = pass_->get_def_use_mgr()->GetDef(phi_candidate->var_id());
  462. // Build the vector of operands for the new OpPhi instruction.
  463. uint32_t type_id = pass_->GetPointeeTypeId(local_var);
  464. std::vector<Operand> phi_operands;
  465. uint32_t arg_ix = 0;
  466. std::unordered_map<uint32_t, uint32_t> already_seen;
  467. for (uint32_t pred_label : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  468. uint32_t op_val_id = GetPhiArgument(phi_candidate, arg_ix++);
  469. if (already_seen.count(pred_label) == 0) {
  470. phi_operands.push_back(
  471. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {op_val_id}});
  472. phi_operands.push_back(
  473. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {pred_label}});
  474. already_seen[pred_label] = op_val_id;
  475. } else {
  476. // It is possible that there are two edges from the same parent block.
  477. // Since the OpPhi can have only one entry for each parent, we have to
  478. // make sure the two edges are consistent with each other.
  479. assert(already_seen[pred_label] == op_val_id &&
  480. "Inconsistent value for duplicate edges.");
  481. }
  482. }
  483. // Generate a new OpPhi instruction and insert it in its basic
  484. // block.
  485. std::unique_ptr<Instruction> phi_inst(
  486. new Instruction(pass_->context(), spv::Op::OpPhi, type_id,
  487. phi_candidate->result_id(), phi_operands));
  488. generated_phis.push_back(phi_inst.get());
  489. pass_->get_def_use_mgr()->AnalyzeInstDef(&*phi_inst);
  490. pass_->context()->set_instr_block(&*phi_inst, phi_candidate->bb());
  491. auto insert_it = phi_candidate->bb()->begin();
  492. insert_it = insert_it.InsertBefore(std::move(phi_inst));
  493. pass_->context()->get_decoration_mgr()->CloneDecorations(
  494. phi_candidate->var_id(), phi_candidate->result_id(),
  495. {spv::Decoration::RelaxedPrecision});
  496. // Add DebugValue for the new OpPhi instruction.
  497. insert_it->SetDebugScope(local_var->GetDebugScope());
  498. pass_->context()->get_debug_info_mgr()->AddDebugValueForVariable(
  499. &*insert_it, phi_candidate->var_id(), phi_candidate->result_id(),
  500. &*insert_it);
  501. modified = true;
  502. }
  503. // Scan uses for all inserted Phi instructions. Do this separately from the
  504. // registration of the Phi instruction itself to avoid trying to analyze
  505. // uses of Phi instructions that have not been registered yet.
  506. for (Instruction* phi_inst : generated_phis) {
  507. pass_->get_def_use_mgr()->AnalyzeInstUse(&*phi_inst);
  508. }
  509. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  510. std::cerr << "\n\nReplacing the result of load instructions with the "
  511. "corresponding SSA id\n\n";
  512. #endif
  513. // Apply replacements from the load replacement table.
  514. for (auto& repl : load_replacement_) {
  515. uint32_t load_id = repl.first;
  516. uint32_t val_id = GetReplacement(repl);
  517. Instruction* load_inst =
  518. pass_->context()->get_def_use_mgr()->GetDef(load_id);
  519. #if SSA_REWRITE_DEBUGGING_LEVEL > 2
  520. std::cerr << "\t"
  521. << load_inst->PrettyPrint(
  522. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  523. << " (%" << load_id << " -> %" << val_id << ")\n";
  524. #endif
  525. // Remove the load instruction and replace all the uses of this load's
  526. // result with |val_id|. Kill any names or decorates using the load's
  527. // result before replacing to prevent incorrect replacement in those
  528. // instructions.
  529. pass_->context()->KillNamesAndDecorates(load_id);
  530. pass_->context()->ReplaceAllUsesWith(load_id, val_id);
  531. pass_->context()->KillInst(load_inst);
  532. modified = true;
  533. }
  534. return modified;
  535. }
  536. void SSARewriter::FinalizePhiCandidate(PhiCandidate* phi_candidate) {
  537. assert(phi_candidate->phi_args().size() > 0 &&
  538. "Phi candidate should have arguments");
  539. uint32_t ix = 0;
  540. for (uint32_t pred : pass_->cfg()->preds(phi_candidate->bb()->id())) {
  541. BasicBlock* pred_bb = pass_->cfg()->block(pred);
  542. uint32_t& arg_id = phi_candidate->phi_args()[ix++];
  543. if (arg_id == 0) {
  544. // If |pred_bb| is still not sealed, it means it's unreachable. In this
  545. // case, we just use Undef as an argument.
  546. arg_id = IsBlockSealed(pred_bb)
  547. ? GetReachingDef(phi_candidate->var_id(), pred_bb)
  548. : pass_->GetUndefVal(phi_candidate->var_id());
  549. }
  550. }
  551. // This candidate is now completed.
  552. phi_candidate->MarkComplete();
  553. // If |phi_candidate| is not trivial, add it to the list of Phis to
  554. // generate.
  555. if (TryRemoveTrivialPhi(phi_candidate) == phi_candidate->result_id()) {
  556. // If we could not remove |phi_candidate|, it means that it is complete
  557. // and not trivial. Add it to the list of Phis to generate.
  558. assert(!phi_candidate->copy_of() && "A completed Phi cannot be trivial.");
  559. phis_to_generate_.push_back(phi_candidate);
  560. }
  561. }
  562. void SSARewriter::FinalizePhiCandidates() {
  563. #if SSA_REWRITE_DEBUGGING_LEVEL > 1
  564. std::cerr << "Finalizing Phi candidates:\n\n";
  565. PrintPhiCandidates();
  566. std::cerr << "\n";
  567. #endif
  568. // Now, complete the collected candidates.
  569. while (incomplete_phis_.size() > 0) {
  570. PhiCandidate* phi_candidate = incomplete_phis_.front();
  571. incomplete_phis_.pop();
  572. FinalizePhiCandidate(phi_candidate);
  573. }
  574. }
  575. Pass::Status SSARewriter::RewriteFunctionIntoSSA(Function* fp) {
  576. #if SSA_REWRITE_DEBUGGING_LEVEL > 0
  577. std::cerr << "Function before SSA rewrite:\n"
  578. << fp->PrettyPrint(0) << "\n\n\n";
  579. #endif
  580. // Collect variables that can be converted into SSA IDs.
  581. pass_->CollectTargetVars(fp);
  582. // Generate all the SSA replacements and Phi candidates. This will
  583. // generate incomplete and trivial Phis.
  584. bool succeeded = pass_->cfg()->WhileEachBlockInReversePostOrder(
  585. fp->entry().get(), [this](BasicBlock* bb) {
  586. if (!GenerateSSAReplacements(bb)) {
  587. return false;
  588. }
  589. return true;
  590. });
  591. if (!succeeded) {
  592. return Pass::Status::Failure;
  593. }
  594. // Remove trivial Phis and add arguments to incomplete Phis.
  595. FinalizePhiCandidates();
  596. // Finally, apply all the replacements in the IR.
  597. bool modified = ApplyReplacements();
  598. #if SSA_REWRITE_DEBUGGING_LEVEL > 0
  599. std::cerr << "\n\n\nFunction after SSA rewrite:\n"
  600. << fp->PrettyPrint(0) << "\n";
  601. #endif
  602. return modified ? Pass::Status::SuccessWithChange
  603. : Pass::Status::SuccessWithoutChange;
  604. }
  605. Pass::Status SSARewritePass::Process() {
  606. Status status = Status::SuccessWithoutChange;
  607. for (auto& fn : *get_module()) {
  608. if (fn.IsDeclaration()) {
  609. continue;
  610. }
  611. status =
  612. CombineStatus(status, SSARewriter(this).RewriteFunctionIntoSSA(&fn));
  613. // Kill DebugDeclares for target variables.
  614. for (auto var_id : seen_target_vars_) {
  615. context()->get_debug_info_mgr()->KillDebugDeclares(var_id);
  616. }
  617. if (status == Status::Failure) {
  618. break;
  619. }
  620. }
  621. return status;
  622. }
  623. } // namespace opt
  624. } // namespace spvtools