1 //===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------===// 9 // 10 // This file implements the MemorySSAUpdater class. 11 // 12 //===----------------------------------------------------------------===// 13 #include "llvm/Analysis/MemorySSAUpdater.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SmallPtrSet.h" 16 #include "llvm/Analysis/MemorySSA.h" 17 #include "llvm/IR/DataLayout.h" 18 #include "llvm/IR/Dominators.h" 19 #include "llvm/IR/GlobalVariable.h" 20 #include "llvm/IR/IRBuilder.h" 21 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/Metadata.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/FormattedStream.h" 26 #include <algorithm> 27 28 #define DEBUG_TYPE "memoryssa" 29 using namespace llvm; 30 31 // This is the marker algorithm from "Simple and Efficient Construction of 32 // Static Single Assignment Form" 33 // The simple, non-marker algorithm places phi nodes at any join 34 // Here, we place markers, and only place phi nodes if they end up necessary. 35 // They are only necessary if they break a cycle (IE we recursively visit 36 // ourselves again), or we discover, while getting the value of the operands, 37 // that there are two or more definitions needing to be merged. 38 // This still will leave non-minimal form in the case of irreducible control 39 // flow, where phi nodes may be in cycles with themselves, but unnecessary. 40 MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive( 41 BasicBlock *BB, 42 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) { 43 // First, do a cache lookup. Without this cache, certain CFG structures 44 // (like a series of if statements) take exponential time to visit. 45 auto Cached = CachedPreviousDef.find(BB); 46 if (Cached != CachedPreviousDef.end()) { 47 return Cached->second; 48 } else if (BasicBlock *Pred = BB->getSinglePredecessor()) { 49 // Single predecessor case, just recurse, we can only have one definition. 50 MemoryAccess *Result = getPreviousDefFromEnd(Pred, CachedPreviousDef); 51 CachedPreviousDef.insert({BB, Result}); 52 return Result; 53 } else if (VisitedBlocks.count(BB)) { 54 // We hit our node again, meaning we had a cycle, we must insert a phi 55 // node to break it so we have an operand. The only case this will 56 // insert useless phis is if we have irreducible control flow. 57 MemoryAccess *Result = MSSA->createMemoryPhi(BB); 58 CachedPreviousDef.insert({BB, Result}); 59 return Result; 60 } else if (VisitedBlocks.insert(BB).second) { 61 // Mark us visited so we can detect a cycle 62 SmallVector<MemoryAccess *, 8> PhiOps; 63 64 // Recurse to get the values in our predecessors for placement of a 65 // potential phi node. This will insert phi nodes if we cycle in order to 66 // break the cycle and have an operand. 67 for (auto *Pred : predecessors(BB)) 68 PhiOps.push_back(getPreviousDefFromEnd(Pred, CachedPreviousDef)); 69 70 // Now try to simplify the ops to avoid placing a phi. 71 // This may return null if we never created a phi yet, that's okay 72 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB)); 73 bool PHIExistsButNeedsUpdate = false; 74 // See if the existing phi operands match what we need. 75 // Unlike normal SSA, we only allow one phi node per block, so we can't just 76 // create a new one. 77 if (Phi && Phi->getNumOperands() != 0) 78 if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) { 79 PHIExistsButNeedsUpdate = true; 80 } 81 82 // See if we can avoid the phi by simplifying it. 83 auto *Result = tryRemoveTrivialPhi(Phi, PhiOps); 84 // If we couldn't simplify, we may have to create a phi 85 if (Result == Phi) { 86 if (!Phi) 87 Phi = MSSA->createMemoryPhi(BB); 88 89 // These will have been filled in by the recursive read we did above. 90 if (PHIExistsButNeedsUpdate) { 91 std::copy(PhiOps.begin(), PhiOps.end(), Phi->op_begin()); 92 std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin()); 93 } else { 94 unsigned i = 0; 95 for (auto *Pred : predecessors(BB)) 96 Phi->addIncoming(PhiOps[i++], Pred); 97 InsertedPHIs.push_back(Phi); 98 } 99 Result = Phi; 100 } 101 102 // Set ourselves up for the next variable by resetting visited state. 103 VisitedBlocks.erase(BB); 104 CachedPreviousDef.insert({BB, Result}); 105 return Result; 106 } 107 llvm_unreachable("Should have hit one of the three cases above"); 108 } 109 110 // This starts at the memory access, and goes backwards in the block to find the 111 // previous definition. If a definition is not found the block of the access, 112 // it continues globally, creating phi nodes to ensure we have a single 113 // definition. 114 MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) { 115 if (auto *LocalResult = getPreviousDefInBlock(MA)) 116 return LocalResult; 117 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef; 118 return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef); 119 } 120 121 // This starts at the memory access, and goes backwards in the block to the find 122 // the previous definition. If the definition is not found in the block of the 123 // access, it returns nullptr. 124 MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) { 125 auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock()); 126 127 // It's possible there are no defs, or we got handed the first def to start. 128 if (Defs) { 129 // If this is a def, we can just use the def iterators. 130 if (!isa<MemoryUse>(MA)) { 131 auto Iter = MA->getReverseDefsIterator(); 132 ++Iter; 133 if (Iter != Defs->rend()) 134 return &*Iter; 135 } else { 136 // Otherwise, have to walk the all access iterator. 137 auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend(); 138 for (auto &U : make_range(++MA->getReverseIterator(), End)) 139 if (!isa<MemoryUse>(U)) 140 return cast<MemoryAccess>(&U); 141 // Note that if MA comes before Defs->begin(), we won't hit a def. 142 return nullptr; 143 } 144 } 145 return nullptr; 146 } 147 148 // This starts at the end of block 149 MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd( 150 BasicBlock *BB, 151 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) { 152 auto *Defs = MSSA->getWritableBlockDefs(BB); 153 154 if (Defs) 155 return &*Defs->rbegin(); 156 157 return getPreviousDefRecursive(BB, CachedPreviousDef); 158 } 159 // Recurse over a set of phi uses to eliminate the trivial ones 160 MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) { 161 if (!Phi) 162 return nullptr; 163 TrackingVH<MemoryAccess> Res(Phi); 164 SmallVector<TrackingVH<Value>, 8> Uses; 165 std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses)); 166 for (auto &U : Uses) { 167 if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) { 168 auto OperRange = UsePhi->operands(); 169 tryRemoveTrivialPhi(UsePhi, OperRange); 170 } 171 } 172 return Res; 173 } 174 175 // Eliminate trivial phis 176 // Phis are trivial if they are defined either by themselves, or all the same 177 // argument. 178 // IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c) 179 // We recursively try to remove them. 180 template <class RangeType> 181 MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi, 182 RangeType &Operands) { 183 // Detect equal or self arguments 184 MemoryAccess *Same = nullptr; 185 for (auto &Op : Operands) { 186 // If the same or self, good so far 187 if (Op == Phi || Op == Same) 188 continue; 189 // not the same, return the phi since it's not eliminatable by us 190 if (Same) 191 return Phi; 192 Same = cast<MemoryAccess>(Op); 193 } 194 // Never found a non-self reference, the phi is undef 195 if (Same == nullptr) 196 return MSSA->getLiveOnEntryDef(); 197 if (Phi) { 198 Phi->replaceAllUsesWith(Same); 199 removeMemoryAccess(Phi); 200 } 201 202 // We should only end up recursing in case we replaced something, in which 203 // case, we may have made other Phis trivial. 204 return recursePhi(Same); 205 } 206 207 void MemorySSAUpdater::insertUse(MemoryUse *MU) { 208 InsertedPHIs.clear(); 209 MU->setDefiningAccess(getPreviousDef(MU)); 210 // Unlike for defs, there is no extra work to do. Because uses do not create 211 // new may-defs, there are only two cases: 212 // 213 // 1. There was a def already below us, and therefore, we should not have 214 // created a phi node because it was already needed for the def. 215 // 216 // 2. There is no def below us, and therefore, there is no extra renaming work 217 // to do. 218 } 219 220 // Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef. 221 static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB, 222 MemoryAccess *NewDef) { 223 // Replace any operand with us an incoming block with the new defining 224 // access. 225 int i = MP->getBasicBlockIndex(BB); 226 assert(i != -1 && "Should have found the basic block in the phi"); 227 // We can't just compare i against getNumOperands since one is signed and the 228 // other not. So use it to index into the block iterator. 229 for (auto BBIter = MP->block_begin() + i; BBIter != MP->block_end(); 230 ++BBIter) { 231 if (*BBIter != BB) 232 break; 233 MP->setIncomingValue(i, NewDef); 234 ++i; 235 } 236 } 237 238 // A brief description of the algorithm: 239 // First, we compute what should define the new def, using the SSA 240 // construction algorithm. 241 // Then, we update the defs below us (and any new phi nodes) in the graph to 242 // point to the correct new defs, to ensure we only have one variable, and no 243 // disconnected stores. 244 void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) { 245 InsertedPHIs.clear(); 246 247 // See if we had a local def, and if not, go hunting. 248 MemoryAccess *DefBefore = getPreviousDef(MD); 249 bool DefBeforeSameBlock = DefBefore->getBlock() == MD->getBlock(); 250 251 // There is a def before us, which means we can replace any store/phi uses 252 // of that thing with us, since we are in the way of whatever was there 253 // before. 254 // We now define that def's memorydefs and memoryphis 255 if (DefBeforeSameBlock) { 256 for (auto UI = DefBefore->use_begin(), UE = DefBefore->use_end(); 257 UI != UE;) { 258 Use &U = *UI++; 259 // Leave the uses alone 260 if (isa<MemoryUse>(U.getUser())) 261 continue; 262 U.set(MD); 263 } 264 } 265 266 // and that def is now our defining access. 267 // We change them in this order otherwise we will appear in the use list 268 // above and reset ourselves. 269 MD->setDefiningAccess(DefBefore); 270 271 SmallVector<MemoryAccess *, 8> FixupList(InsertedPHIs.begin(), 272 InsertedPHIs.end()); 273 if (!DefBeforeSameBlock) { 274 // If there was a local def before us, we must have the same effect it 275 // did. Because every may-def is the same, any phis/etc we would create, it 276 // would also have created. If there was no local def before us, we 277 // performed a global update, and have to search all successors and make 278 // sure we update the first def in each of them (following all paths until 279 // we hit the first def along each path). This may also insert phi nodes. 280 // TODO: There are other cases we can skip this work, such as when we have a 281 // single successor, and only used a straight line of single pred blocks 282 // backwards to find the def. To make that work, we'd have to track whether 283 // getDefRecursive only ever used the single predecessor case. These types 284 // of paths also only exist in between CFG simplifications. 285 FixupList.push_back(MD); 286 } 287 288 while (!FixupList.empty()) { 289 unsigned StartingPHISize = InsertedPHIs.size(); 290 fixupDefs(FixupList); 291 FixupList.clear(); 292 // Put any new phis on the fixup list, and process them 293 FixupList.append(InsertedPHIs.end() - StartingPHISize, InsertedPHIs.end()); 294 } 295 // Now that all fixups are done, rename all uses if we are asked. 296 if (RenameUses) { 297 SmallPtrSet<BasicBlock *, 16> Visited; 298 BasicBlock *StartBlock = MD->getBlock(); 299 // We are guaranteed there is a def in the block, because we just got it 300 // handed to us in this function. 301 MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin(); 302 // Convert to incoming value if it's a memorydef. A phi *is* already an 303 // incoming value. 304 if (auto *MD = dyn_cast<MemoryDef>(FirstDef)) 305 FirstDef = MD->getDefiningAccess(); 306 307 MSSA->renamePass(MD->getBlock(), FirstDef, Visited); 308 // We just inserted a phi into this block, so the incoming value will become 309 // the phi anyway, so it does not matter what we pass. 310 for (auto *MP : InsertedPHIs) 311 MSSA->renamePass(MP->getBlock(), nullptr, Visited); 312 } 313 } 314 315 void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<MemoryAccess *> &Vars) { 316 SmallPtrSet<const BasicBlock *, 8> Seen; 317 SmallVector<const BasicBlock *, 16> Worklist; 318 for (auto *NewDef : Vars) { 319 // First, see if there is a local def after the operand. 320 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock()); 321 auto DefIter = NewDef->getDefsIterator(); 322 323 // If there is a local def after us, we only have to rename that. 324 if (++DefIter != Defs->end()) { 325 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef); 326 continue; 327 } 328 329 // Otherwise, we need to search down through the CFG. 330 // For each of our successors, handle it directly if their is a phi, or 331 // place on the fixup worklist. 332 for (const auto *S : successors(NewDef->getBlock())) { 333 if (auto *MP = MSSA->getMemoryAccess(S)) 334 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef); 335 else 336 Worklist.push_back(S); 337 } 338 339 while (!Worklist.empty()) { 340 const BasicBlock *FixupBlock = Worklist.back(); 341 Worklist.pop_back(); 342 343 // Get the first def in the block that isn't a phi node. 344 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) { 345 auto *FirstDef = &*Defs->begin(); 346 // The loop above and below should have taken care of phi nodes 347 assert(!isa<MemoryPhi>(FirstDef) && 348 "Should have already handled phi nodes!"); 349 // We are now this def's defining access, make sure we actually dominate 350 // it 351 assert(MSSA->dominates(NewDef, FirstDef) && 352 "Should have dominated the new access"); 353 354 // This may insert new phi nodes, because we are not guaranteed the 355 // block we are processing has a single pred, and depending where the 356 // store was inserted, it may require phi nodes below it. 357 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef)); 358 return; 359 } 360 // We didn't find a def, so we must continue. 361 for (const auto *S : successors(FixupBlock)) { 362 // If there is a phi node, handle it. 363 // Otherwise, put the block on the worklist 364 if (auto *MP = MSSA->getMemoryAccess(S)) 365 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef); 366 else { 367 // If we cycle, we should have ended up at a phi node that we already 368 // processed. FIXME: Double check this 369 if (!Seen.insert(S).second) 370 continue; 371 Worklist.push_back(S); 372 } 373 } 374 } 375 } 376 } 377 378 // Move What before Where in the MemorySSA IR. 379 template <class WhereType> 380 void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB, 381 WhereType Where) { 382 // Replace all our users with our defining access. 383 What->replaceAllUsesWith(What->getDefiningAccess()); 384 385 // Let MemorySSA take care of moving it around in the lists. 386 MSSA->moveTo(What, BB, Where); 387 388 // Now reinsert it into the IR and do whatever fixups needed. 389 if (auto *MD = dyn_cast<MemoryDef>(What)) 390 insertDef(MD); 391 else 392 insertUse(cast<MemoryUse>(What)); 393 } 394 395 // Move What before Where in the MemorySSA IR. 396 void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) { 397 moveTo(What, Where->getBlock(), Where->getIterator()); 398 } 399 400 // Move What after Where in the MemorySSA IR. 401 void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) { 402 moveTo(What, Where->getBlock(), ++Where->getIterator()); 403 } 404 405 void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, 406 MemorySSA::InsertionPlace Where) { 407 return moveTo(What, BB, Where); 408 } 409 410 /// \brief If all arguments of a MemoryPHI are defined by the same incoming 411 /// argument, return that argument. 412 static MemoryAccess *onlySingleValue(MemoryPhi *MP) { 413 MemoryAccess *MA = nullptr; 414 415 for (auto &Arg : MP->operands()) { 416 if (!MA) 417 MA = cast<MemoryAccess>(Arg); 418 else if (MA != Arg) 419 return nullptr; 420 } 421 return MA; 422 } 423 424 void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA) { 425 assert(!MSSA->isLiveOnEntryDef(MA) && 426 "Trying to remove the live on entry def"); 427 // We can only delete phi nodes if they have no uses, or we can replace all 428 // uses with a single definition. 429 MemoryAccess *NewDefTarget = nullptr; 430 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) { 431 // Note that it is sufficient to know that all edges of the phi node have 432 // the same argument. If they do, by the definition of dominance frontiers 433 // (which we used to place this phi), that argument must dominate this phi, 434 // and thus, must dominate the phi's uses, and so we will not hit the assert 435 // below. 436 NewDefTarget = onlySingleValue(MP); 437 assert((NewDefTarget || MP->use_empty()) && 438 "We can't delete this memory phi"); 439 } else { 440 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess(); 441 } 442 443 // Re-point the uses at our defining access 444 if (!isa<MemoryUse>(MA) && !MA->use_empty()) { 445 // Reset optimized on users of this store, and reset the uses. 446 // A few notes: 447 // 1. This is a slightly modified version of RAUW to avoid walking the 448 // uses twice here. 449 // 2. If we wanted to be complete, we would have to reset the optimized 450 // flags on users of phi nodes if doing the below makes a phi node have all 451 // the same arguments. Instead, we prefer users to removeMemoryAccess those 452 // phi nodes, because doing it here would be N^3. 453 if (MA->hasValueHandle()) 454 ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget); 455 // Note: We assume MemorySSA is not used in metadata since it's not really 456 // part of the IR. 457 458 while (!MA->use_empty()) { 459 Use &U = *MA->use_begin(); 460 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser())) 461 MUD->resetOptimized(); 462 U.set(NewDefTarget); 463 } 464 } 465 466 // The call below to erase will destroy MA, so we can't change the order we 467 // are doing things here 468 MSSA->removeFromLookups(MA); 469 MSSA->removeFromLists(MA); 470 } 471 472 MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB( 473 Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, 474 MemorySSA::InsertionPlace Point) { 475 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); 476 MSSA->insertIntoListsForBlock(NewAccess, BB, Point); 477 return NewAccess; 478 } 479 480 MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore( 481 Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) { 482 assert(I->getParent() == InsertPt->getBlock() && 483 "New and old access must be in the same block"); 484 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); 485 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(), 486 InsertPt->getIterator()); 487 return NewAccess; 488 } 489 490 MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter( 491 Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) { 492 assert(I->getParent() == InsertPt->getBlock() && 493 "New and old access must be in the same block"); 494 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); 495 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(), 496 ++InsertPt->getIterator()); 497 return NewAccess; 498 } 499