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