1 //===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------===// 8 // 9 // This file implements the MemorySSAUpdater class. 10 // 11 //===----------------------------------------------------------------===// 12 #include "llvm/Analysis/MemorySSAUpdater.h" 13 #include "llvm/ADT/STLExtras.h" 14 #include "llvm/ADT/SetVector.h" 15 #include "llvm/ADT/SmallPtrSet.h" 16 #include "llvm/Analysis/IteratedDominanceFrontier.h" 17 #include "llvm/Analysis/MemorySSA.h" 18 #include "llvm/IR/DataLayout.h" 19 #include "llvm/IR/Dominators.h" 20 #include "llvm/IR/GlobalVariable.h" 21 #include "llvm/IR/IRBuilder.h" 22 #include "llvm/IR/LLVMContext.h" 23 #include "llvm/IR/Metadata.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/FormattedStream.h" 27 #include <algorithm> 28 29 #define DEBUG_TYPE "memoryssa" 30 using namespace llvm; 31 32 // This is the marker algorithm from "Simple and Efficient Construction of 33 // Static Single Assignment Form" 34 // The simple, non-marker algorithm places phi nodes at any join 35 // Here, we place markers, and only place phi nodes if they end up necessary. 36 // They are only necessary if they break a cycle (IE we recursively visit 37 // ourselves again), or we discover, while getting the value of the operands, 38 // that there are two or more definitions needing to be merged. 39 // This still will leave non-minimal form in the case of irreducible control 40 // flow, where phi nodes may be in cycles with themselves, but unnecessary. 41 MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive( 42 BasicBlock *BB, 43 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) { 44 // First, do a cache lookup. Without this cache, certain CFG structures 45 // (like a series of if statements) take exponential time to visit. 46 auto Cached = CachedPreviousDef.find(BB); 47 if (Cached != CachedPreviousDef.end()) { 48 return Cached->second; 49 } 50 51 if (BasicBlock *Pred = BB->getSinglePredecessor()) { 52 // Single predecessor case, just recurse, we can only have one definition. 53 MemoryAccess *Result = getPreviousDefFromEnd(Pred, CachedPreviousDef); 54 CachedPreviousDef.insert({BB, Result}); 55 return Result; 56 } 57 58 if (VisitedBlocks.count(BB)) { 59 // We hit our node again, meaning we had a cycle, we must insert a phi 60 // node to break it so we have an operand. The only case this will 61 // insert useless phis is if we have irreducible control flow. 62 MemoryAccess *Result = MSSA->createMemoryPhi(BB); 63 CachedPreviousDef.insert({BB, Result}); 64 return Result; 65 } 66 67 if (VisitedBlocks.insert(BB).second) { 68 // Mark us visited so we can detect a cycle 69 SmallVector<TrackingVH<MemoryAccess>, 8> PhiOps; 70 71 // Recurse to get the values in our predecessors for placement of a 72 // potential phi node. This will insert phi nodes if we cycle in order to 73 // break the cycle and have an operand. 74 for (auto *Pred : predecessors(BB)) 75 if (MSSA->DT->isReachableFromEntry(Pred)) 76 PhiOps.push_back(getPreviousDefFromEnd(Pred, CachedPreviousDef)); 77 else 78 PhiOps.push_back(MSSA->getLiveOnEntryDef()); 79 80 // Now try to simplify the ops to avoid placing a phi. 81 // This may return null if we never created a phi yet, that's okay 82 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB)); 83 84 // See if we can avoid the phi by simplifying it. 85 auto *Result = tryRemoveTrivialPhi(Phi, PhiOps); 86 // If we couldn't simplify, we may have to create a phi 87 if (Result == Phi) { 88 if (!Phi) 89 Phi = MSSA->createMemoryPhi(BB); 90 91 // See if the existing phi operands match what we need. 92 // Unlike normal SSA, we only allow one phi node per block, so we can't just 93 // create a new one. 94 if (Phi->getNumOperands() != 0) { 95 // FIXME: Figure out whether this is dead code and if so remove it. 96 if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) { 97 // These will have been filled in by the recursive read we did above. 98 llvm::copy(PhiOps, Phi->op_begin()); 99 std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin()); 100 } 101 } else { 102 unsigned i = 0; 103 for (auto *Pred : predecessors(BB)) 104 Phi->addIncoming(&*PhiOps[i++], Pred); 105 InsertedPHIs.push_back(Phi); 106 } 107 Result = Phi; 108 } 109 110 // Set ourselves up for the next variable by resetting visited state. 111 VisitedBlocks.erase(BB); 112 CachedPreviousDef.insert({BB, Result}); 113 return Result; 114 } 115 llvm_unreachable("Should have hit one of the three cases above"); 116 } 117 118 // This starts at the memory access, and goes backwards in the block to find the 119 // previous definition. If a definition is not found the block of the access, 120 // it continues globally, creating phi nodes to ensure we have a single 121 // definition. 122 MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) { 123 if (auto *LocalResult = getPreviousDefInBlock(MA)) 124 return LocalResult; 125 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef; 126 return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef); 127 } 128 129 // This starts at the memory access, and goes backwards in the block to the find 130 // the previous definition. If the definition is not found in the block of the 131 // access, it returns nullptr. 132 MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) { 133 auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock()); 134 135 // It's possible there are no defs, or we got handed the first def to start. 136 if (Defs) { 137 // If this is a def, we can just use the def iterators. 138 if (!isa<MemoryUse>(MA)) { 139 auto Iter = MA->getReverseDefsIterator(); 140 ++Iter; 141 if (Iter != Defs->rend()) 142 return &*Iter; 143 } else { 144 // Otherwise, have to walk the all access iterator. 145 auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend(); 146 for (auto &U : make_range(++MA->getReverseIterator(), End)) 147 if (!isa<MemoryUse>(U)) 148 return cast<MemoryAccess>(&U); 149 // Note that if MA comes before Defs->begin(), we won't hit a def. 150 return nullptr; 151 } 152 } 153 return nullptr; 154 } 155 156 // This starts at the end of block 157 MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd( 158 BasicBlock *BB, 159 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) { 160 auto *Defs = MSSA->getWritableBlockDefs(BB); 161 162 if (Defs) { 163 CachedPreviousDef.insert({BB, &*Defs->rbegin()}); 164 return &*Defs->rbegin(); 165 } 166 167 return getPreviousDefRecursive(BB, CachedPreviousDef); 168 } 169 // Recurse over a set of phi uses to eliminate the trivial ones 170 MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) { 171 if (!Phi) 172 return nullptr; 173 TrackingVH<MemoryAccess> Res(Phi); 174 SmallVector<TrackingVH<Value>, 8> Uses; 175 std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses)); 176 for (auto &U : Uses) { 177 if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) { 178 auto OperRange = UsePhi->operands(); 179 tryRemoveTrivialPhi(UsePhi, OperRange); 180 } 181 } 182 return Res; 183 } 184 185 // Eliminate trivial phis 186 // Phis are trivial if they are defined either by themselves, or all the same 187 // argument. 188 // IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c) 189 // We recursively try to remove them. 190 template <class RangeType> 191 MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi, 192 RangeType &Operands) { 193 // Bail out on non-opt Phis. 194 if (NonOptPhis.count(Phi)) 195 return Phi; 196 197 // Detect equal or self arguments 198 MemoryAccess *Same = nullptr; 199 for (auto &Op : Operands) { 200 // If the same or self, good so far 201 if (Op == Phi || Op == Same) 202 continue; 203 // not the same, return the phi since it's not eliminatable by us 204 if (Same) 205 return Phi; 206 Same = cast<MemoryAccess>(&*Op); 207 } 208 // Never found a non-self reference, the phi is undef 209 if (Same == nullptr) 210 return MSSA->getLiveOnEntryDef(); 211 if (Phi) { 212 Phi->replaceAllUsesWith(Same); 213 removeMemoryAccess(Phi); 214 } 215 216 // We should only end up recursing in case we replaced something, in which 217 // case, we may have made other Phis trivial. 218 return recursePhi(Same); 219 } 220 221 void MemorySSAUpdater::insertUse(MemoryUse *MU, bool RenameUses) { 222 InsertedPHIs.clear(); 223 MU->setDefiningAccess(getPreviousDef(MU)); 224 // In cases without unreachable blocks, because uses do not create new 225 // may-defs, there are only two cases: 226 // 1. There was a def already below us, and therefore, we should not have 227 // created a phi node because it was already needed for the def. 228 // 229 // 2. There is no def below us, and therefore, there is no extra renaming work 230 // to do. 231 232 // In cases with unreachable blocks, where the unnecessary Phis were 233 // optimized out, adding the Use may re-insert those Phis. Hence, when 234 // inserting Uses outside of the MSSA creation process, and new Phis were 235 // added, rename all uses if we are asked. 236 237 if (!RenameUses && !InsertedPHIs.empty()) { 238 auto *Defs = MSSA->getBlockDefs(MU->getBlock()); 239 (void)Defs; 240 assert((!Defs || (++Defs->begin() == Defs->end())) && 241 "Block may have only a Phi or no defs"); 242 } 243 244 if (RenameUses && InsertedPHIs.size()) { 245 SmallPtrSet<BasicBlock *, 16> Visited; 246 BasicBlock *StartBlock = MU->getBlock(); 247 248 if (auto *Defs = MSSA->getWritableBlockDefs(StartBlock)) { 249 MemoryAccess *FirstDef = &*Defs->begin(); 250 // Convert to incoming value if it's a memorydef. A phi *is* already an 251 // incoming value. 252 if (auto *MD = dyn_cast<MemoryDef>(FirstDef)) 253 FirstDef = MD->getDefiningAccess(); 254 255 MSSA->renamePass(MU->getBlock(), FirstDef, Visited); 256 // We just inserted a phi into this block, so the incoming value will 257 // become the phi anyway, so it does not matter what we pass. 258 for (auto &MP : InsertedPHIs) 259 if (MemoryPhi *Phi = cast_or_null<MemoryPhi>(MP)) 260 MSSA->renamePass(Phi->getBlock(), nullptr, Visited); 261 } 262 } 263 } 264 265 // Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef. 266 static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB, 267 MemoryAccess *NewDef) { 268 // Replace any operand with us an incoming block with the new defining 269 // access. 270 int i = MP->getBasicBlockIndex(BB); 271 assert(i != -1 && "Should have found the basic block in the phi"); 272 // We can't just compare i against getNumOperands since one is signed and the 273 // other not. So use it to index into the block iterator. 274 for (auto BBIter = MP->block_begin() + i; BBIter != MP->block_end(); 275 ++BBIter) { 276 if (*BBIter != BB) 277 break; 278 MP->setIncomingValue(i, NewDef); 279 ++i; 280 } 281 } 282 283 // A brief description of the algorithm: 284 // First, we compute what should define the new def, using the SSA 285 // construction algorithm. 286 // Then, we update the defs below us (and any new phi nodes) in the graph to 287 // point to the correct new defs, to ensure we only have one variable, and no 288 // disconnected stores. 289 void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) { 290 InsertedPHIs.clear(); 291 292 // See if we had a local def, and if not, go hunting. 293 MemoryAccess *DefBefore = getPreviousDef(MD); 294 bool DefBeforeSameBlock = DefBefore->getBlock() == MD->getBlock(); 295 296 // There is a def before us, which means we can replace any store/phi uses 297 // of that thing with us, since we are in the way of whatever was there 298 // before. 299 // We now define that def's memorydefs and memoryphis 300 if (DefBeforeSameBlock) { 301 DefBefore->replaceUsesWithIf(MD, [MD](Use &U) { 302 // Leave the MemoryUses alone. 303 // Also make sure we skip ourselves to avoid self references. 304 User *Usr = U.getUser(); 305 return !isa<MemoryUse>(Usr) && Usr != MD; 306 // Defs are automatically unoptimized when the user is set to MD below, 307 // because the isOptimized() call will fail to find the same ID. 308 }); 309 } 310 311 // and that def is now our defining access. 312 MD->setDefiningAccess(DefBefore); 313 314 // Remember the index where we may insert new phis below. 315 unsigned NewPhiIndex = InsertedPHIs.size(); 316 317 SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end()); 318 if (!DefBeforeSameBlock) { 319 // If there was a local def before us, we must have the same effect it 320 // did. Because every may-def is the same, any phis/etc we would create, it 321 // would also have created. If there was no local def before us, we 322 // performed a global update, and have to search all successors and make 323 // sure we update the first def in each of them (following all paths until 324 // we hit the first def along each path). This may also insert phi nodes. 325 // TODO: There are other cases we can skip this work, such as when we have a 326 // single successor, and only used a straight line of single pred blocks 327 // backwards to find the def. To make that work, we'd have to track whether 328 // getDefRecursive only ever used the single predecessor case. These types 329 // of paths also only exist in between CFG simplifications. 330 331 // If this is the first def in the block and this insert is in an arbitrary 332 // place, compute IDF and place phis. 333 auto Iter = MD->getDefsIterator(); 334 ++Iter; 335 auto IterEnd = MSSA->getBlockDefs(MD->getBlock())->end(); 336 if (Iter == IterEnd) { 337 ForwardIDFCalculator IDFs(*MSSA->DT); 338 SmallVector<BasicBlock *, 32> IDFBlocks; 339 SmallPtrSet<BasicBlock *, 2> DefiningBlocks; 340 DefiningBlocks.insert(MD->getBlock()); 341 IDFs.setDefiningBlocks(DefiningBlocks); 342 IDFs.calculate(IDFBlocks); 343 SmallVector<AssertingVH<MemoryPhi>, 4> NewInsertedPHIs; 344 for (auto *BBIDF : IDFBlocks) 345 if (!MSSA->getMemoryAccess(BBIDF)) { 346 auto *MPhi = MSSA->createMemoryPhi(BBIDF); 347 NewInsertedPHIs.push_back(MPhi); 348 // Add the phis created into the IDF blocks to NonOptPhis, so they are 349 // not optimized out as trivial by the call to getPreviousDefFromEnd 350 // below. Once they are complete, all these Phis are added to the 351 // FixupList, and removed from NonOptPhis inside fixupDefs(). 352 NonOptPhis.insert(MPhi); 353 } 354 355 for (auto &MPhi : NewInsertedPHIs) { 356 auto *BBIDF = MPhi->getBlock(); 357 for (auto *Pred : predecessors(BBIDF)) { 358 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef; 359 MPhi->addIncoming(getPreviousDefFromEnd(Pred, CachedPreviousDef), 360 Pred); 361 } 362 } 363 364 // Re-take the index where we're adding the new phis, because the above 365 // call to getPreviousDefFromEnd, may have inserted into InsertedPHIs. 366 NewPhiIndex = InsertedPHIs.size(); 367 for (auto &MPhi : NewInsertedPHIs) { 368 InsertedPHIs.push_back(&*MPhi); 369 FixupList.push_back(&*MPhi); 370 } 371 } 372 373 FixupList.push_back(MD); 374 } 375 376 // Remember the index where we stopped inserting new phis above, since the 377 // fixupDefs call in the loop below may insert more, that are already minimal. 378 unsigned NewPhiIndexEnd = InsertedPHIs.size(); 379 380 while (!FixupList.empty()) { 381 unsigned StartingPHISize = InsertedPHIs.size(); 382 fixupDefs(FixupList); 383 FixupList.clear(); 384 // Put any new phis on the fixup list, and process them 385 FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end()); 386 } 387 388 // Optimize potentially non-minimal phis added in this method. 389 unsigned NewPhiSize = NewPhiIndexEnd - NewPhiIndex; 390 if (NewPhiSize) 391 tryRemoveTrivialPhis(ArrayRef<WeakVH>(&InsertedPHIs[NewPhiIndex], NewPhiSize)); 392 393 // Now that all fixups are done, rename all uses if we are asked. 394 if (RenameUses) { 395 SmallPtrSet<BasicBlock *, 16> Visited; 396 BasicBlock *StartBlock = MD->getBlock(); 397 // We are guaranteed there is a def in the block, because we just got it 398 // handed to us in this function. 399 MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin(); 400 // Convert to incoming value if it's a memorydef. A phi *is* already an 401 // incoming value. 402 if (auto *MD = dyn_cast<MemoryDef>(FirstDef)) 403 FirstDef = MD->getDefiningAccess(); 404 405 MSSA->renamePass(MD->getBlock(), FirstDef, Visited); 406 // We just inserted a phi into this block, so the incoming value will become 407 // the phi anyway, so it does not matter what we pass. 408 for (auto &MP : InsertedPHIs) { 409 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP); 410 if (Phi) 411 MSSA->renamePass(Phi->getBlock(), nullptr, Visited); 412 } 413 } 414 } 415 416 void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) { 417 SmallPtrSet<const BasicBlock *, 8> Seen; 418 SmallVector<const BasicBlock *, 16> Worklist; 419 for (auto &Var : Vars) { 420 MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var); 421 if (!NewDef) 422 continue; 423 // First, see if there is a local def after the operand. 424 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock()); 425 auto DefIter = NewDef->getDefsIterator(); 426 427 // The temporary Phi is being fixed, unmark it for not to optimize. 428 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef)) 429 NonOptPhis.erase(Phi); 430 431 // If there is a local def after us, we only have to rename that. 432 if (++DefIter != Defs->end()) { 433 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef); 434 continue; 435 } 436 437 // Otherwise, we need to search down through the CFG. 438 // For each of our successors, handle it directly if their is a phi, or 439 // place on the fixup worklist. 440 for (const auto *S : successors(NewDef->getBlock())) { 441 if (auto *MP = MSSA->getMemoryAccess(S)) 442 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef); 443 else 444 Worklist.push_back(S); 445 } 446 447 while (!Worklist.empty()) { 448 const BasicBlock *FixupBlock = Worklist.back(); 449 Worklist.pop_back(); 450 451 // Get the first def in the block that isn't a phi node. 452 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) { 453 auto *FirstDef = &*Defs->begin(); 454 // The loop above and below should have taken care of phi nodes 455 assert(!isa<MemoryPhi>(FirstDef) && 456 "Should have already handled phi nodes!"); 457 // We are now this def's defining access, make sure we actually dominate 458 // it 459 assert(MSSA->dominates(NewDef, FirstDef) && 460 "Should have dominated the new access"); 461 462 // This may insert new phi nodes, because we are not guaranteed the 463 // block we are processing has a single pred, and depending where the 464 // store was inserted, it may require phi nodes below it. 465 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef)); 466 return; 467 } 468 // We didn't find a def, so we must continue. 469 for (const auto *S : successors(FixupBlock)) { 470 // If there is a phi node, handle it. 471 // Otherwise, put the block on the worklist 472 if (auto *MP = MSSA->getMemoryAccess(S)) 473 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef); 474 else { 475 // If we cycle, we should have ended up at a phi node that we already 476 // processed. FIXME: Double check this 477 if (!Seen.insert(S).second) 478 continue; 479 Worklist.push_back(S); 480 } 481 } 482 } 483 } 484 } 485 486 void MemorySSAUpdater::removeEdge(BasicBlock *From, BasicBlock *To) { 487 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) { 488 MPhi->unorderedDeleteIncomingBlock(From); 489 if (MPhi->getNumIncomingValues() == 1) 490 removeMemoryAccess(MPhi); 491 } 492 } 493 494 void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock *From, 495 const BasicBlock *To) { 496 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) { 497 bool Found = false; 498 MPhi->unorderedDeleteIncomingIf([&](const MemoryAccess *, BasicBlock *B) { 499 if (From != B) 500 return false; 501 if (Found) 502 return true; 503 Found = true; 504 return false; 505 }); 506 if (MPhi->getNumIncomingValues() == 1) 507 removeMemoryAccess(MPhi); 508 } 509 } 510 511 static MemoryAccess *getNewDefiningAccessForClone(MemoryAccess *MA, 512 const ValueToValueMapTy &VMap, 513 PhiToDefMap &MPhiMap, 514 bool CloneWasSimplified, 515 MemorySSA *MSSA) { 516 MemoryAccess *InsnDefining = MA; 517 if (MemoryDef *DefMUD = dyn_cast<MemoryDef>(InsnDefining)) { 518 if (!MSSA->isLiveOnEntryDef(DefMUD)) { 519 Instruction *DefMUDI = DefMUD->getMemoryInst(); 520 assert(DefMUDI && "Found MemoryUseOrDef with no Instruction."); 521 if (Instruction *NewDefMUDI = 522 cast_or_null<Instruction>(VMap.lookup(DefMUDI))) { 523 InsnDefining = MSSA->getMemoryAccess(NewDefMUDI); 524 if (!CloneWasSimplified) 525 assert(InsnDefining && "Defining instruction cannot be nullptr."); 526 else if (!InsnDefining || isa<MemoryUse>(InsnDefining)) { 527 // The clone was simplified, it's no longer a MemoryDef, look up. 528 auto DefIt = DefMUD->getDefsIterator(); 529 // Since simplified clones only occur in single block cloning, a 530 // previous definition must exist, otherwise NewDefMUDI would not 531 // have been found in VMap. 532 assert(DefIt != MSSA->getBlockDefs(DefMUD->getBlock())->begin() && 533 "Previous def must exist"); 534 InsnDefining = getNewDefiningAccessForClone( 535 &*(--DefIt), VMap, MPhiMap, CloneWasSimplified, MSSA); 536 } 537 } 538 } 539 } else { 540 MemoryPhi *DefPhi = cast<MemoryPhi>(InsnDefining); 541 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(DefPhi)) 542 InsnDefining = NewDefPhi; 543 } 544 assert(InsnDefining && "Defining instruction cannot be nullptr."); 545 return InsnDefining; 546 } 547 548 void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB, 549 const ValueToValueMapTy &VMap, 550 PhiToDefMap &MPhiMap, 551 bool CloneWasSimplified) { 552 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB); 553 if (!Acc) 554 return; 555 for (const MemoryAccess &MA : *Acc) { 556 if (const MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&MA)) { 557 Instruction *Insn = MUD->getMemoryInst(); 558 // Entry does not exist if the clone of the block did not clone all 559 // instructions. This occurs in LoopRotate when cloning instructions 560 // from the old header to the old preheader. The cloned instruction may 561 // also be a simplified Value, not an Instruction (see LoopRotate). 562 // Also in LoopRotate, even when it's an instruction, due to it being 563 // simplified, it may be a Use rather than a Def, so we cannot use MUD as 564 // template. Calls coming from updateForClonedBlockIntoPred, ensure this. 565 if (Instruction *NewInsn = 566 dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) { 567 MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess( 568 NewInsn, 569 getNewDefiningAccessForClone(MUD->getDefiningAccess(), VMap, 570 MPhiMap, CloneWasSimplified, MSSA), 571 /*Template=*/CloneWasSimplified ? nullptr : MUD, 572 /*CreationMustSucceed=*/CloneWasSimplified ? false : true); 573 if (NewUseOrDef) 574 MSSA->insertIntoListsForBlock(NewUseOrDef, NewBB, MemorySSA::End); 575 } 576 } 577 } 578 } 579 580 void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock( 581 BasicBlock *Header, BasicBlock *Preheader, BasicBlock *BEBlock) { 582 auto *MPhi = MSSA->getMemoryAccess(Header); 583 if (!MPhi) 584 return; 585 586 // Create phi node in the backedge block and populate it with the same 587 // incoming values as MPhi. Skip incoming values coming from Preheader. 588 auto *NewMPhi = MSSA->createMemoryPhi(BEBlock); 589 bool HasUniqueIncomingValue = true; 590 MemoryAccess *UniqueValue = nullptr; 591 for (unsigned I = 0, E = MPhi->getNumIncomingValues(); I != E; ++I) { 592 BasicBlock *IBB = MPhi->getIncomingBlock(I); 593 MemoryAccess *IV = MPhi->getIncomingValue(I); 594 if (IBB != Preheader) { 595 NewMPhi->addIncoming(IV, IBB); 596 if (HasUniqueIncomingValue) { 597 if (!UniqueValue) 598 UniqueValue = IV; 599 else if (UniqueValue != IV) 600 HasUniqueIncomingValue = false; 601 } 602 } 603 } 604 605 // Update incoming edges into MPhi. Remove all but the incoming edge from 606 // Preheader. Add an edge from NewMPhi 607 auto *AccFromPreheader = MPhi->getIncomingValueForBlock(Preheader); 608 MPhi->setIncomingValue(0, AccFromPreheader); 609 MPhi->setIncomingBlock(0, Preheader); 610 for (unsigned I = MPhi->getNumIncomingValues() - 1; I >= 1; --I) 611 MPhi->unorderedDeleteIncoming(I); 612 MPhi->addIncoming(NewMPhi, BEBlock); 613 614 // If NewMPhi is a trivial phi, remove it. Its use in the header MPhi will be 615 // replaced with the unique value. 616 if (HasUniqueIncomingValue) 617 removeMemoryAccess(NewMPhi); 618 } 619 620 void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO &LoopBlocks, 621 ArrayRef<BasicBlock *> ExitBlocks, 622 const ValueToValueMapTy &VMap, 623 bool IgnoreIncomingWithNoClones) { 624 PhiToDefMap MPhiMap; 625 626 auto FixPhiIncomingValues = [&](MemoryPhi *Phi, MemoryPhi *NewPhi) { 627 assert(Phi && NewPhi && "Invalid Phi nodes."); 628 BasicBlock *NewPhiBB = NewPhi->getBlock(); 629 SmallPtrSet<BasicBlock *, 4> NewPhiBBPreds(pred_begin(NewPhiBB), 630 pred_end(NewPhiBB)); 631 for (unsigned It = 0, E = Phi->getNumIncomingValues(); It < E; ++It) { 632 MemoryAccess *IncomingAccess = Phi->getIncomingValue(It); 633 BasicBlock *IncBB = Phi->getIncomingBlock(It); 634 635 if (BasicBlock *NewIncBB = cast_or_null<BasicBlock>(VMap.lookup(IncBB))) 636 IncBB = NewIncBB; 637 else if (IgnoreIncomingWithNoClones) 638 continue; 639 640 // Now we have IncBB, and will need to add incoming from it to NewPhi. 641 642 // If IncBB is not a predecessor of NewPhiBB, then do not add it. 643 // NewPhiBB was cloned without that edge. 644 if (!NewPhiBBPreds.count(IncBB)) 645 continue; 646 647 // Determine incoming value and add it as incoming from IncBB. 648 if (MemoryUseOrDef *IncMUD = dyn_cast<MemoryUseOrDef>(IncomingAccess)) { 649 if (!MSSA->isLiveOnEntryDef(IncMUD)) { 650 Instruction *IncI = IncMUD->getMemoryInst(); 651 assert(IncI && "Found MemoryUseOrDef with no Instruction."); 652 if (Instruction *NewIncI = 653 cast_or_null<Instruction>(VMap.lookup(IncI))) { 654 IncMUD = MSSA->getMemoryAccess(NewIncI); 655 assert(IncMUD && 656 "MemoryUseOrDef cannot be null, all preds processed."); 657 } 658 } 659 NewPhi->addIncoming(IncMUD, IncBB); 660 } else { 661 MemoryPhi *IncPhi = cast<MemoryPhi>(IncomingAccess); 662 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(IncPhi)) 663 NewPhi->addIncoming(NewDefPhi, IncBB); 664 else 665 NewPhi->addIncoming(IncPhi, IncBB); 666 } 667 } 668 }; 669 670 auto ProcessBlock = [&](BasicBlock *BB) { 671 BasicBlock *NewBlock = cast_or_null<BasicBlock>(VMap.lookup(BB)); 672 if (!NewBlock) 673 return; 674 675 assert(!MSSA->getWritableBlockAccesses(NewBlock) && 676 "Cloned block should have no accesses"); 677 678 // Add MemoryPhi. 679 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) { 680 MemoryPhi *NewPhi = MSSA->createMemoryPhi(NewBlock); 681 MPhiMap[MPhi] = NewPhi; 682 } 683 // Update Uses and Defs. 684 cloneUsesAndDefs(BB, NewBlock, VMap, MPhiMap); 685 }; 686 687 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks)) 688 ProcessBlock(BB); 689 690 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks)) 691 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) 692 if (MemoryAccess *NewPhi = MPhiMap.lookup(MPhi)) 693 FixPhiIncomingValues(MPhi, cast<MemoryPhi>(NewPhi)); 694 } 695 696 void MemorySSAUpdater::updateForClonedBlockIntoPred( 697 BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM) { 698 // All defs/phis from outside BB that are used in BB, are valid uses in P1. 699 // Since those defs/phis must have dominated BB, and also dominate P1. 700 // Defs from BB being used in BB will be replaced with the cloned defs from 701 // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the 702 // incoming def into the Phi from P1. 703 // Instructions cloned into the predecessor are in practice sometimes 704 // simplified, so disable the use of the template, and create an access from 705 // scratch. 706 PhiToDefMap MPhiMap; 707 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) 708 MPhiMap[MPhi] = MPhi->getIncomingValueForBlock(P1); 709 cloneUsesAndDefs(BB, P1, VM, MPhiMap, /*CloneWasSimplified=*/true); 710 } 711 712 template <typename Iter> 713 void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop( 714 ArrayRef<BasicBlock *> ExitBlocks, Iter ValuesBegin, Iter ValuesEnd, 715 DominatorTree &DT) { 716 SmallVector<CFGUpdate, 4> Updates; 717 // Update/insert phis in all successors of exit blocks. 718 for (auto *Exit : ExitBlocks) 719 for (const ValueToValueMapTy *VMap : make_range(ValuesBegin, ValuesEnd)) 720 if (BasicBlock *NewExit = cast_or_null<BasicBlock>(VMap->lookup(Exit))) { 721 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0); 722 Updates.push_back({DT.Insert, NewExit, ExitSucc}); 723 } 724 applyInsertUpdates(Updates, DT); 725 } 726 727 void MemorySSAUpdater::updateExitBlocksForClonedLoop( 728 ArrayRef<BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap, 729 DominatorTree &DT) { 730 const ValueToValueMapTy *const Arr[] = {&VMap}; 731 privateUpdateExitBlocksForClonedLoop(ExitBlocks, std::begin(Arr), 732 std::end(Arr), DT); 733 } 734 735 void MemorySSAUpdater::updateExitBlocksForClonedLoop( 736 ArrayRef<BasicBlock *> ExitBlocks, 737 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT) { 738 auto GetPtr = [&](const std::unique_ptr<ValueToValueMapTy> &I) { 739 return I.get(); 740 }; 741 using MappedIteratorType = 742 mapped_iterator<const std::unique_ptr<ValueToValueMapTy> *, 743 decltype(GetPtr)>; 744 auto MapBegin = MappedIteratorType(VMaps.begin(), GetPtr); 745 auto MapEnd = MappedIteratorType(VMaps.end(), GetPtr); 746 privateUpdateExitBlocksForClonedLoop(ExitBlocks, MapBegin, MapEnd, DT); 747 } 748 749 void MemorySSAUpdater::applyUpdates(ArrayRef<CFGUpdate> Updates, 750 DominatorTree &DT) { 751 SmallVector<CFGUpdate, 4> RevDeleteUpdates; 752 SmallVector<CFGUpdate, 4> InsertUpdates; 753 for (auto &Update : Updates) { 754 if (Update.getKind() == DT.Insert) 755 InsertUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()}); 756 else 757 RevDeleteUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()}); 758 } 759 760 if (!RevDeleteUpdates.empty()) { 761 // Update for inserted edges: use newDT and snapshot CFG as if deletes had 762 // not occurred. 763 // FIXME: This creates a new DT, so it's more expensive to do mix 764 // delete/inserts vs just inserts. We can do an incremental update on the DT 765 // to revert deletes, than re-delete the edges. Teaching DT to do this, is 766 // part of a pending cleanup. 767 DominatorTree NewDT(DT, RevDeleteUpdates); 768 GraphDiff<BasicBlock *> GD(RevDeleteUpdates); 769 applyInsertUpdates(InsertUpdates, NewDT, &GD); 770 } else { 771 GraphDiff<BasicBlock *> GD; 772 applyInsertUpdates(InsertUpdates, DT, &GD); 773 } 774 775 // Update for deleted edges 776 for (auto &Update : RevDeleteUpdates) 777 removeEdge(Update.getFrom(), Update.getTo()); 778 } 779 780 void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates, 781 DominatorTree &DT) { 782 GraphDiff<BasicBlock *> GD; 783 applyInsertUpdates(Updates, DT, &GD); 784 } 785 786 void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates, 787 DominatorTree &DT, 788 const GraphDiff<BasicBlock *> *GD) { 789 // Get recursive last Def, assuming well formed MSSA and updated DT. 790 auto GetLastDef = [&](BasicBlock *BB) -> MemoryAccess * { 791 while (true) { 792 MemorySSA::DefsList *Defs = MSSA->getWritableBlockDefs(BB); 793 // Return last Def or Phi in BB, if it exists. 794 if (Defs) 795 return &*(--Defs->end()); 796 797 // Check number of predecessors, we only care if there's more than one. 798 unsigned Count = 0; 799 BasicBlock *Pred = nullptr; 800 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) { 801 Pred = Pair.second; 802 Count++; 803 if (Count == 2) 804 break; 805 } 806 807 // If BB has multiple predecessors, get last definition from IDom. 808 if (Count != 1) { 809 // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its 810 // DT is invalidated. Return LoE as its last def. This will be added to 811 // MemoryPhi node, and later deleted when the block is deleted. 812 if (!DT.getNode(BB)) 813 return MSSA->getLiveOnEntryDef(); 814 if (auto *IDom = DT.getNode(BB)->getIDom()) 815 if (IDom->getBlock() != BB) { 816 BB = IDom->getBlock(); 817 continue; 818 } 819 return MSSA->getLiveOnEntryDef(); 820 } else { 821 // Single predecessor, BB cannot be dead. GetLastDef of Pred. 822 assert(Count == 1 && Pred && "Single predecessor expected."); 823 BB = Pred; 824 } 825 }; 826 llvm_unreachable("Unable to get last definition."); 827 }; 828 829 // Get nearest IDom given a set of blocks. 830 // TODO: this can be optimized by starting the search at the node with the 831 // lowest level (highest in the tree). 832 auto FindNearestCommonDominator = 833 [&](const SmallSetVector<BasicBlock *, 2> &BBSet) -> BasicBlock * { 834 BasicBlock *PrevIDom = *BBSet.begin(); 835 for (auto *BB : BBSet) 836 PrevIDom = DT.findNearestCommonDominator(PrevIDom, BB); 837 return PrevIDom; 838 }; 839 840 // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not 841 // include CurrIDom. 842 auto GetNoLongerDomBlocks = 843 [&](BasicBlock *PrevIDom, BasicBlock *CurrIDom, 844 SmallVectorImpl<BasicBlock *> &BlocksPrevDom) { 845 if (PrevIDom == CurrIDom) 846 return; 847 BlocksPrevDom.push_back(PrevIDom); 848 BasicBlock *NextIDom = PrevIDom; 849 while (BasicBlock *UpIDom = 850 DT.getNode(NextIDom)->getIDom()->getBlock()) { 851 if (UpIDom == CurrIDom) 852 break; 853 BlocksPrevDom.push_back(UpIDom); 854 NextIDom = UpIDom; 855 } 856 }; 857 858 // Map a BB to its predecessors: added + previously existing. To get a 859 // deterministic order, store predecessors as SetVectors. The order in each 860 // will be defined by the order in Updates (fixed) and the order given by 861 // children<> (also fixed). Since we further iterate over these ordered sets, 862 // we lose the information of multiple edges possibly existing between two 863 // blocks, so we'll keep and EdgeCount map for that. 864 // An alternate implementation could keep unordered set for the predecessors, 865 // traverse either Updates or children<> each time to get the deterministic 866 // order, and drop the usage of EdgeCount. This alternate approach would still 867 // require querying the maps for each predecessor, and children<> call has 868 // additional computation inside for creating the snapshot-graph predecessors. 869 // As such, we favor using a little additional storage and less compute time. 870 // This decision can be revisited if we find the alternative more favorable. 871 872 struct PredInfo { 873 SmallSetVector<BasicBlock *, 2> Added; 874 SmallSetVector<BasicBlock *, 2> Prev; 875 }; 876 SmallDenseMap<BasicBlock *, PredInfo> PredMap; 877 878 for (auto &Edge : Updates) { 879 BasicBlock *BB = Edge.getTo(); 880 auto &AddedBlockSet = PredMap[BB].Added; 881 AddedBlockSet.insert(Edge.getFrom()); 882 } 883 884 // Store all existing predecessor for each BB, at least one must exist. 885 SmallDenseMap<std::pair<BasicBlock *, BasicBlock *>, int> EdgeCountMap; 886 SmallPtrSet<BasicBlock *, 2> NewBlocks; 887 for (auto &BBPredPair : PredMap) { 888 auto *BB = BBPredPair.first; 889 const auto &AddedBlockSet = BBPredPair.second.Added; 890 auto &PrevBlockSet = BBPredPair.second.Prev; 891 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) { 892 BasicBlock *Pi = Pair.second; 893 if (!AddedBlockSet.count(Pi)) 894 PrevBlockSet.insert(Pi); 895 EdgeCountMap[{Pi, BB}]++; 896 } 897 898 if (PrevBlockSet.empty()) { 899 assert(pred_size(BB) == AddedBlockSet.size() && "Duplicate edges added."); 900 LLVM_DEBUG( 901 dbgs() 902 << "Adding a predecessor to a block with no predecessors. " 903 "This must be an edge added to a new, likely cloned, block. " 904 "Its memory accesses must be already correct, assuming completed " 905 "via the updateExitBlocksForClonedLoop API. " 906 "Assert a single such edge is added so no phi addition or " 907 "additional processing is required.\n"); 908 assert(AddedBlockSet.size() == 1 && 909 "Can only handle adding one predecessor to a new block."); 910 // Need to remove new blocks from PredMap. Remove below to not invalidate 911 // iterator here. 912 NewBlocks.insert(BB); 913 } 914 } 915 // Nothing to process for new/cloned blocks. 916 for (auto *BB : NewBlocks) 917 PredMap.erase(BB); 918 919 SmallVector<BasicBlock *, 16> BlocksWithDefsToReplace; 920 SmallVector<WeakVH, 8> InsertedPhis; 921 922 // First create MemoryPhis in all blocks that don't have one. Create in the 923 // order found in Updates, not in PredMap, to get deterministic numbering. 924 for (auto &Edge : Updates) { 925 BasicBlock *BB = Edge.getTo(); 926 if (PredMap.count(BB) && !MSSA->getMemoryAccess(BB)) 927 InsertedPhis.push_back(MSSA->createMemoryPhi(BB)); 928 } 929 930 // Now we'll fill in the MemoryPhis with the right incoming values. 931 for (auto &BBPredPair : PredMap) { 932 auto *BB = BBPredPair.first; 933 const auto &PrevBlockSet = BBPredPair.second.Prev; 934 const auto &AddedBlockSet = BBPredPair.second.Added; 935 assert(!PrevBlockSet.empty() && 936 "At least one previous predecessor must exist."); 937 938 // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by 939 // keeping this map before the loop. We can reuse already populated entries 940 // if an edge is added from the same predecessor to two different blocks, 941 // and this does happen in rotate. Note that the map needs to be updated 942 // when deleting non-necessary phis below, if the phi is in the map by 943 // replacing the value with DefP1. 944 SmallDenseMap<BasicBlock *, MemoryAccess *> LastDefAddedPred; 945 for (auto *AddedPred : AddedBlockSet) { 946 auto *DefPn = GetLastDef(AddedPred); 947 assert(DefPn != nullptr && "Unable to find last definition."); 948 LastDefAddedPred[AddedPred] = DefPn; 949 } 950 951 MemoryPhi *NewPhi = MSSA->getMemoryAccess(BB); 952 // If Phi is not empty, add an incoming edge from each added pred. Must 953 // still compute blocks with defs to replace for this block below. 954 if (NewPhi->getNumOperands()) { 955 for (auto *Pred : AddedBlockSet) { 956 auto *LastDefForPred = LastDefAddedPred[Pred]; 957 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I) 958 NewPhi->addIncoming(LastDefForPred, Pred); 959 } 960 } else { 961 // Pick any existing predecessor and get its definition. All other 962 // existing predecessors should have the same one, since no phi existed. 963 auto *P1 = *PrevBlockSet.begin(); 964 MemoryAccess *DefP1 = GetLastDef(P1); 965 966 // Check DefP1 against all Defs in LastDefPredPair. If all the same, 967 // nothing to add. 968 bool InsertPhi = false; 969 for (auto LastDefPredPair : LastDefAddedPred) 970 if (DefP1 != LastDefPredPair.second) { 971 InsertPhi = true; 972 break; 973 } 974 if (!InsertPhi) { 975 // Since NewPhi may be used in other newly added Phis, replace all uses 976 // of NewPhi with the definition coming from all predecessors (DefP1), 977 // before deleting it. 978 NewPhi->replaceAllUsesWith(DefP1); 979 removeMemoryAccess(NewPhi); 980 continue; 981 } 982 983 // Update Phi with new values for new predecessors and old value for all 984 // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered 985 // sets, the order of entries in NewPhi is deterministic. 986 for (auto *Pred : AddedBlockSet) { 987 auto *LastDefForPred = LastDefAddedPred[Pred]; 988 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I) 989 NewPhi->addIncoming(LastDefForPred, Pred); 990 } 991 for (auto *Pred : PrevBlockSet) 992 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I) 993 NewPhi->addIncoming(DefP1, Pred); 994 } 995 996 // Get all blocks that used to dominate BB and no longer do after adding 997 // AddedBlockSet, where PrevBlockSet are the previously known predecessors. 998 assert(DT.getNode(BB)->getIDom() && "BB does not have valid idom"); 999 BasicBlock *PrevIDom = FindNearestCommonDominator(PrevBlockSet); 1000 assert(PrevIDom && "Previous IDom should exists"); 1001 BasicBlock *NewIDom = DT.getNode(BB)->getIDom()->getBlock(); 1002 assert(NewIDom && "BB should have a new valid idom"); 1003 assert(DT.dominates(NewIDom, PrevIDom) && 1004 "New idom should dominate old idom"); 1005 GetNoLongerDomBlocks(PrevIDom, NewIDom, BlocksWithDefsToReplace); 1006 } 1007 1008 tryRemoveTrivialPhis(InsertedPhis); 1009 // Create the set of blocks that now have a definition. We'll use this to 1010 // compute IDF and add Phis there next. 1011 SmallVector<BasicBlock *, 8> BlocksToProcess; 1012 for (auto &VH : InsertedPhis) 1013 if (auto *MPhi = cast_or_null<MemoryPhi>(VH)) 1014 BlocksToProcess.push_back(MPhi->getBlock()); 1015 1016 // Compute IDF and add Phis in all IDF blocks that do not have one. 1017 SmallVector<BasicBlock *, 32> IDFBlocks; 1018 if (!BlocksToProcess.empty()) { 1019 ForwardIDFCalculator IDFs(DT, GD); 1020 SmallPtrSet<BasicBlock *, 16> DefiningBlocks(BlocksToProcess.begin(), 1021 BlocksToProcess.end()); 1022 IDFs.setDefiningBlocks(DefiningBlocks); 1023 IDFs.calculate(IDFBlocks); 1024 1025 SmallSetVector<MemoryPhi *, 4> PhisToFill; 1026 // First create all needed Phis. 1027 for (auto *BBIDF : IDFBlocks) 1028 if (!MSSA->getMemoryAccess(BBIDF)) { 1029 auto *IDFPhi = MSSA->createMemoryPhi(BBIDF); 1030 InsertedPhis.push_back(IDFPhi); 1031 PhisToFill.insert(IDFPhi); 1032 } 1033 // Then update or insert their correct incoming values. 1034 for (auto *BBIDF : IDFBlocks) { 1035 auto *IDFPhi = MSSA->getMemoryAccess(BBIDF); 1036 assert(IDFPhi && "Phi must exist"); 1037 if (!PhisToFill.count(IDFPhi)) { 1038 // Update existing Phi. 1039 // FIXME: some updates may be redundant, try to optimize and skip some. 1040 for (unsigned I = 0, E = IDFPhi->getNumIncomingValues(); I < E; ++I) 1041 IDFPhi->setIncomingValue(I, GetLastDef(IDFPhi->getIncomingBlock(I))); 1042 } else { 1043 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BBIDF})) { 1044 BasicBlock *Pi = Pair.second; 1045 IDFPhi->addIncoming(GetLastDef(Pi), Pi); 1046 } 1047 } 1048 } 1049 } 1050 1051 // Now for all defs in BlocksWithDefsToReplace, if there are uses they no 1052 // longer dominate, replace those with the closest dominating def. 1053 // This will also update optimized accesses, as they're also uses. 1054 for (auto *BlockWithDefsToReplace : BlocksWithDefsToReplace) { 1055 if (auto DefsList = MSSA->getWritableBlockDefs(BlockWithDefsToReplace)) { 1056 for (auto &DefToReplaceUses : *DefsList) { 1057 BasicBlock *DominatingBlock = DefToReplaceUses.getBlock(); 1058 Value::use_iterator UI = DefToReplaceUses.use_begin(), 1059 E = DefToReplaceUses.use_end(); 1060 for (; UI != E;) { 1061 Use &U = *UI; 1062 ++UI; 1063 MemoryAccess *Usr = dyn_cast<MemoryAccess>(U.getUser()); 1064 if (MemoryPhi *UsrPhi = dyn_cast<MemoryPhi>(Usr)) { 1065 BasicBlock *DominatedBlock = UsrPhi->getIncomingBlock(U); 1066 if (!DT.dominates(DominatingBlock, DominatedBlock)) 1067 U.set(GetLastDef(DominatedBlock)); 1068 } else { 1069 BasicBlock *DominatedBlock = Usr->getBlock(); 1070 if (!DT.dominates(DominatingBlock, DominatedBlock)) { 1071 if (auto *DomBlPhi = MSSA->getMemoryAccess(DominatedBlock)) 1072 U.set(DomBlPhi); 1073 else { 1074 auto *IDom = DT.getNode(DominatedBlock)->getIDom(); 1075 assert(IDom && "Block must have a valid IDom."); 1076 U.set(GetLastDef(IDom->getBlock())); 1077 } 1078 cast<MemoryUseOrDef>(Usr)->resetOptimized(); 1079 } 1080 } 1081 } 1082 } 1083 } 1084 } 1085 tryRemoveTrivialPhis(InsertedPhis); 1086 } 1087 1088 // Move What before Where in the MemorySSA IR. 1089 template <class WhereType> 1090 void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB, 1091 WhereType Where) { 1092 // Mark MemoryPhi users of What not to be optimized. 1093 for (auto *U : What->users()) 1094 if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U)) 1095 NonOptPhis.insert(PhiUser); 1096 1097 // Replace all our users with our defining access. 1098 What->replaceAllUsesWith(What->getDefiningAccess()); 1099 1100 // Let MemorySSA take care of moving it around in the lists. 1101 MSSA->moveTo(What, BB, Where); 1102 1103 // Now reinsert it into the IR and do whatever fixups needed. 1104 if (auto *MD = dyn_cast<MemoryDef>(What)) 1105 insertDef(MD, /*RenameUses=*/true); 1106 else 1107 insertUse(cast<MemoryUse>(What), /*RenameUses=*/true); 1108 1109 // Clear dangling pointers. We added all MemoryPhi users, but not all 1110 // of them are removed by fixupDefs(). 1111 NonOptPhis.clear(); 1112 } 1113 1114 // Move What before Where in the MemorySSA IR. 1115 void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) { 1116 moveTo(What, Where->getBlock(), Where->getIterator()); 1117 } 1118 1119 // Move What after Where in the MemorySSA IR. 1120 void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) { 1121 moveTo(What, Where->getBlock(), ++Where->getIterator()); 1122 } 1123 1124 void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, 1125 MemorySSA::InsertionPlace Where) { 1126 return moveTo(What, BB, Where); 1127 } 1128 1129 // All accesses in To used to be in From. Move to end and update access lists. 1130 void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To, 1131 Instruction *Start) { 1132 1133 MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From); 1134 if (!Accs) 1135 return; 1136 1137 MemoryAccess *FirstInNew = nullptr; 1138 for (Instruction &I : make_range(Start->getIterator(), To->end())) 1139 if ((FirstInNew = MSSA->getMemoryAccess(&I))) 1140 break; 1141 if (!FirstInNew) 1142 return; 1143 1144 auto *MUD = cast<MemoryUseOrDef>(FirstInNew); 1145 do { 1146 auto NextIt = ++MUD->getIterator(); 1147 MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end()) 1148 ? nullptr 1149 : cast<MemoryUseOrDef>(&*NextIt); 1150 MSSA->moveTo(MUD, To, MemorySSA::End); 1151 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to 1152 // retrieve it again. 1153 Accs = MSSA->getWritableBlockAccesses(From); 1154 MUD = NextMUD; 1155 } while (MUD); 1156 } 1157 1158 void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From, 1159 BasicBlock *To, 1160 Instruction *Start) { 1161 assert(MSSA->getBlockAccesses(To) == nullptr && 1162 "To block is expected to be free of MemoryAccesses."); 1163 moveAllAccesses(From, To, Start); 1164 for (BasicBlock *Succ : successors(To)) 1165 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ)) 1166 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To); 1167 } 1168 1169 void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To, 1170 Instruction *Start) { 1171 assert(From->getSinglePredecessor() == To && 1172 "From block is expected to have a single predecessor (To)."); 1173 moveAllAccesses(From, To, Start); 1174 for (BasicBlock *Succ : successors(From)) 1175 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ)) 1176 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To); 1177 } 1178 1179 /// If all arguments of a MemoryPHI are defined by the same incoming 1180 /// argument, return that argument. 1181 static MemoryAccess *onlySingleValue(MemoryPhi *MP) { 1182 MemoryAccess *MA = nullptr; 1183 1184 for (auto &Arg : MP->operands()) { 1185 if (!MA) 1186 MA = cast<MemoryAccess>(Arg); 1187 else if (MA != Arg) 1188 return nullptr; 1189 } 1190 return MA; 1191 } 1192 1193 void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor( 1194 BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds, 1195 bool IdenticalEdgesWereMerged) { 1196 assert(!MSSA->getWritableBlockAccesses(New) && 1197 "Access list should be null for a new block."); 1198 MemoryPhi *Phi = MSSA->getMemoryAccess(Old); 1199 if (!Phi) 1200 return; 1201 if (Old->hasNPredecessors(1)) { 1202 assert(pred_size(New) == Preds.size() && 1203 "Should have moved all predecessors."); 1204 MSSA->moveTo(Phi, New, MemorySSA::Beginning); 1205 } else { 1206 assert(!Preds.empty() && "Must be moving at least one predecessor to the " 1207 "new immediate predecessor."); 1208 MemoryPhi *NewPhi = MSSA->createMemoryPhi(New); 1209 SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end()); 1210 // Currently only support the case of removing a single incoming edge when 1211 // identical edges were not merged. 1212 if (!IdenticalEdgesWereMerged) 1213 assert(PredsSet.size() == Preds.size() && 1214 "If identical edges were not merged, we cannot have duplicate " 1215 "blocks in the predecessors"); 1216 Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) { 1217 if (PredsSet.count(B)) { 1218 NewPhi->addIncoming(MA, B); 1219 if (!IdenticalEdgesWereMerged) 1220 PredsSet.erase(B); 1221 return true; 1222 } 1223 return false; 1224 }); 1225 Phi->addIncoming(NewPhi, New); 1226 if (onlySingleValue(NewPhi)) 1227 removeMemoryAccess(NewPhi); 1228 } 1229 } 1230 1231 void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA, bool OptimizePhis) { 1232 assert(!MSSA->isLiveOnEntryDef(MA) && 1233 "Trying to remove the live on entry def"); 1234 // We can only delete phi nodes if they have no uses, or we can replace all 1235 // uses with a single definition. 1236 MemoryAccess *NewDefTarget = nullptr; 1237 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) { 1238 // Note that it is sufficient to know that all edges of the phi node have 1239 // the same argument. If they do, by the definition of dominance frontiers 1240 // (which we used to place this phi), that argument must dominate this phi, 1241 // and thus, must dominate the phi's uses, and so we will not hit the assert 1242 // below. 1243 NewDefTarget = onlySingleValue(MP); 1244 assert((NewDefTarget || MP->use_empty()) && 1245 "We can't delete this memory phi"); 1246 } else { 1247 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess(); 1248 } 1249 1250 SmallSetVector<MemoryPhi *, 4> PhisToCheck; 1251 1252 // Re-point the uses at our defining access 1253 if (!isa<MemoryUse>(MA) && !MA->use_empty()) { 1254 // Reset optimized on users of this store, and reset the uses. 1255 // A few notes: 1256 // 1. This is a slightly modified version of RAUW to avoid walking the 1257 // uses twice here. 1258 // 2. If we wanted to be complete, we would have to reset the optimized 1259 // flags on users of phi nodes if doing the below makes a phi node have all 1260 // the same arguments. Instead, we prefer users to removeMemoryAccess those 1261 // phi nodes, because doing it here would be N^3. 1262 if (MA->hasValueHandle()) 1263 ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget); 1264 // Note: We assume MemorySSA is not used in metadata since it's not really 1265 // part of the IR. 1266 1267 while (!MA->use_empty()) { 1268 Use &U = *MA->use_begin(); 1269 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser())) 1270 MUD->resetOptimized(); 1271 if (OptimizePhis) 1272 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U.getUser())) 1273 PhisToCheck.insert(MP); 1274 U.set(NewDefTarget); 1275 } 1276 } 1277 1278 // The call below to erase will destroy MA, so we can't change the order we 1279 // are doing things here 1280 MSSA->removeFromLookups(MA); 1281 MSSA->removeFromLists(MA); 1282 1283 // Optionally optimize Phi uses. This will recursively remove trivial phis. 1284 if (!PhisToCheck.empty()) { 1285 SmallVector<WeakVH, 16> PhisToOptimize{PhisToCheck.begin(), 1286 PhisToCheck.end()}; 1287 PhisToCheck.clear(); 1288 1289 unsigned PhisSize = PhisToOptimize.size(); 1290 while (PhisSize-- > 0) 1291 if (MemoryPhi *MP = 1292 cast_or_null<MemoryPhi>(PhisToOptimize.pop_back_val())) { 1293 auto OperRange = MP->operands(); 1294 tryRemoveTrivialPhi(MP, OperRange); 1295 } 1296 } 1297 } 1298 1299 void MemorySSAUpdater::removeBlocks( 1300 const SmallSetVector<BasicBlock *, 8> &DeadBlocks) { 1301 // First delete all uses of BB in MemoryPhis. 1302 for (BasicBlock *BB : DeadBlocks) { 1303 Instruction *TI = BB->getTerminator(); 1304 assert(TI && "Basic block expected to have a terminator instruction"); 1305 for (BasicBlock *Succ : successors(TI)) 1306 if (!DeadBlocks.count(Succ)) 1307 if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) { 1308 MP->unorderedDeleteIncomingBlock(BB); 1309 if (MP->getNumIncomingValues() == 1) 1310 removeMemoryAccess(MP); 1311 } 1312 // Drop all references of all accesses in BB 1313 if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB)) 1314 for (MemoryAccess &MA : *Acc) 1315 MA.dropAllReferences(); 1316 } 1317 1318 // Next, delete all memory accesses in each block 1319 for (BasicBlock *BB : DeadBlocks) { 1320 MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB); 1321 if (!Acc) 1322 continue; 1323 for (auto AB = Acc->begin(), AE = Acc->end(); AB != AE;) { 1324 MemoryAccess *MA = &*AB; 1325 ++AB; 1326 MSSA->removeFromLookups(MA); 1327 MSSA->removeFromLists(MA); 1328 } 1329 } 1330 } 1331 1332 void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs) { 1333 for (auto &VH : UpdatedPHIs) 1334 if (auto *MPhi = cast_or_null<MemoryPhi>(VH)) { 1335 auto OperRange = MPhi->operands(); 1336 tryRemoveTrivialPhi(MPhi, OperRange); 1337 } 1338 } 1339 1340 void MemorySSAUpdater::changeToUnreachable(const Instruction *I) { 1341 const BasicBlock *BB = I->getParent(); 1342 // Remove memory accesses in BB for I and all following instructions. 1343 auto BBI = I->getIterator(), BBE = BB->end(); 1344 // FIXME: If this becomes too expensive, iterate until the first instruction 1345 // with a memory access, then iterate over MemoryAccesses. 1346 while (BBI != BBE) 1347 removeMemoryAccess(&*(BBI++)); 1348 // Update phis in BB's successors to remove BB. 1349 SmallVector<WeakVH, 16> UpdatedPHIs; 1350 for (const BasicBlock *Successor : successors(BB)) { 1351 removeDuplicatePhiEdgesBetween(BB, Successor); 1352 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Successor)) { 1353 MPhi->unorderedDeleteIncomingBlock(BB); 1354 UpdatedPHIs.push_back(MPhi); 1355 } 1356 } 1357 // Optimize trivial phis. 1358 tryRemoveTrivialPhis(UpdatedPHIs); 1359 } 1360 1361 void MemorySSAUpdater::changeCondBranchToUnconditionalTo(const BranchInst *BI, 1362 const BasicBlock *To) { 1363 const BasicBlock *BB = BI->getParent(); 1364 SmallVector<WeakVH, 16> UpdatedPHIs; 1365 for (const BasicBlock *Succ : successors(BB)) { 1366 removeDuplicatePhiEdgesBetween(BB, Succ); 1367 if (Succ != To) 1368 if (auto *MPhi = MSSA->getMemoryAccess(Succ)) { 1369 MPhi->unorderedDeleteIncomingBlock(BB); 1370 UpdatedPHIs.push_back(MPhi); 1371 } 1372 } 1373 // Optimize trivial phis. 1374 tryRemoveTrivialPhis(UpdatedPHIs); 1375 } 1376 1377 MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB( 1378 Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, 1379 MemorySSA::InsertionPlace Point) { 1380 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); 1381 MSSA->insertIntoListsForBlock(NewAccess, BB, Point); 1382 return NewAccess; 1383 } 1384 1385 MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore( 1386 Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) { 1387 assert(I->getParent() == InsertPt->getBlock() && 1388 "New and old access must be in the same block"); 1389 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); 1390 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(), 1391 InsertPt->getIterator()); 1392 return NewAccess; 1393 } 1394 1395 MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter( 1396 Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) { 1397 assert(I->getParent() == InsertPt->getBlock() && 1398 "New and old access must be in the same block"); 1399 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); 1400 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(), 1401 ++InsertPt->getIterator()); 1402 return NewAccess; 1403 } 1404