1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===// 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 promotes memory references to be register references. It promotes 11 // alloca instructions which only have loads and stores as uses. An alloca is 12 // transformed by using iterated dominator frontiers to place PHI nodes, then 13 // traversing the function in depth-first order to rewrite loads and stores as 14 // appropriate. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasSetTracker.h" 25 #include "llvm/Analysis/AssumptionCache.h" 26 #include "llvm/Analysis/InstructionSimplify.h" 27 #include "llvm/Analysis/IteratedDominanceFrontier.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DIBuilder.h" 32 #include "llvm/IR/DebugInfo.h" 33 #include "llvm/IR/DerivedTypes.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Metadata.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/Transforms/Utils/Local.h" 41 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 42 #include <algorithm> 43 using namespace llvm; 44 45 #define DEBUG_TYPE "mem2reg" 46 47 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block"); 48 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store"); 49 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed"); 50 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted"); 51 52 bool llvm::isAllocaPromotable(const AllocaInst *AI) { 53 // FIXME: If the memory unit is of pointer or integer type, we can permit 54 // assignments to subsections of the memory unit. 55 unsigned AS = AI->getType()->getAddressSpace(); 56 57 // Only allow direct and non-volatile loads and stores... 58 for (const User *U : AI->users()) { 59 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) { 60 // Note that atomic loads can be transformed; atomic semantics do 61 // not have any meaning for a local alloca. 62 if (LI->isVolatile()) 63 return false; 64 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 65 if (SI->getOperand(0) == AI) 66 return false; // Don't allow a store OF the AI, only INTO the AI. 67 // Note that atomic stores can be transformed; atomic semantics do 68 // not have any meaning for a local alloca. 69 if (SI->isVolatile()) 70 return false; 71 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) { 72 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 73 II->getIntrinsicID() != Intrinsic::lifetime_end) 74 return false; 75 } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) { 76 if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS)) 77 return false; 78 if (!onlyUsedByLifetimeMarkers(BCI)) 79 return false; 80 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 81 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS)) 82 return false; 83 if (!GEPI->hasAllZeroIndices()) 84 return false; 85 if (!onlyUsedByLifetimeMarkers(GEPI)) 86 return false; 87 } else { 88 return false; 89 } 90 } 91 92 return true; 93 } 94 95 namespace { 96 97 struct AllocaInfo { 98 SmallVector<BasicBlock *, 32> DefiningBlocks; 99 SmallVector<BasicBlock *, 32> UsingBlocks; 100 101 StoreInst *OnlyStore; 102 BasicBlock *OnlyBlock; 103 bool OnlyUsedInOneBlock; 104 105 Value *AllocaPointerVal; 106 DbgDeclareInst *DbgDeclare; 107 108 void clear() { 109 DefiningBlocks.clear(); 110 UsingBlocks.clear(); 111 OnlyStore = nullptr; 112 OnlyBlock = nullptr; 113 OnlyUsedInOneBlock = true; 114 AllocaPointerVal = nullptr; 115 DbgDeclare = nullptr; 116 } 117 118 /// Scan the uses of the specified alloca, filling in the AllocaInfo used 119 /// by the rest of the pass to reason about the uses of this alloca. 120 void AnalyzeAlloca(AllocaInst *AI) { 121 clear(); 122 123 // As we scan the uses of the alloca instruction, keep track of stores, 124 // and decide whether all of the loads and stores to the alloca are within 125 // the same basic block. 126 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) { 127 Instruction *User = cast<Instruction>(*UI++); 128 129 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 130 // Remember the basic blocks which define new values for the alloca 131 DefiningBlocks.push_back(SI->getParent()); 132 AllocaPointerVal = SI->getOperand(0); 133 OnlyStore = SI; 134 } else { 135 LoadInst *LI = cast<LoadInst>(User); 136 // Otherwise it must be a load instruction, keep track of variable 137 // reads. 138 UsingBlocks.push_back(LI->getParent()); 139 AllocaPointerVal = LI; 140 } 141 142 if (OnlyUsedInOneBlock) { 143 if (!OnlyBlock) 144 OnlyBlock = User->getParent(); 145 else if (OnlyBlock != User->getParent()) 146 OnlyUsedInOneBlock = false; 147 } 148 } 149 150 DbgDeclare = FindAllocaDbgDeclare(AI); 151 } 152 }; 153 154 // Data package used by RenamePass() 155 class RenamePassData { 156 public: 157 typedef std::vector<Value *> ValVector; 158 159 RenamePassData() : BB(nullptr), Pred(nullptr), Values() {} 160 RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V) 161 : BB(B), Pred(P), Values(V) {} 162 BasicBlock *BB; 163 BasicBlock *Pred; 164 ValVector Values; 165 166 void swap(RenamePassData &RHS) { 167 std::swap(BB, RHS.BB); 168 std::swap(Pred, RHS.Pred); 169 Values.swap(RHS.Values); 170 } 171 }; 172 173 /// \brief This assigns and keeps a per-bb relative ordering of load/store 174 /// instructions in the block that directly load or store an alloca. 175 /// 176 /// This functionality is important because it avoids scanning large basic 177 /// blocks multiple times when promoting many allocas in the same block. 178 class LargeBlockInfo { 179 /// \brief For each instruction that we track, keep the index of the 180 /// instruction. 181 /// 182 /// The index starts out as the number of the instruction from the start of 183 /// the block. 184 DenseMap<const Instruction *, unsigned> InstNumbers; 185 186 public: 187 188 /// This code only looks at accesses to allocas. 189 static bool isInterestingInstruction(const Instruction *I) { 190 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) || 191 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1))); 192 } 193 194 /// Get or calculate the index of the specified instruction. 195 unsigned getInstructionIndex(const Instruction *I) { 196 assert(isInterestingInstruction(I) && 197 "Not a load/store to/from an alloca?"); 198 199 // If we already have this instruction number, return it. 200 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I); 201 if (It != InstNumbers.end()) 202 return It->second; 203 204 // Scan the whole block to get the instruction. This accumulates 205 // information for every interesting instruction in the block, in order to 206 // avoid gratuitus rescans. 207 const BasicBlock *BB = I->getParent(); 208 unsigned InstNo = 0; 209 for (const Instruction &BBI : *BB) 210 if (isInterestingInstruction(&BBI)) 211 InstNumbers[&BBI] = InstNo++; 212 It = InstNumbers.find(I); 213 214 assert(It != InstNumbers.end() && "Didn't insert instruction?"); 215 return It->second; 216 } 217 218 void deleteValue(const Instruction *I) { InstNumbers.erase(I); } 219 220 void clear() { InstNumbers.clear(); } 221 }; 222 223 struct PromoteMem2Reg { 224 /// The alloca instructions being promoted. 225 std::vector<AllocaInst *> Allocas; 226 DominatorTree &DT; 227 DIBuilder DIB; 228 229 /// A cache of @llvm.assume intrinsics used by SimplifyInstruction. 230 AssumptionCache *AC; 231 232 /// Reverse mapping of Allocas. 233 DenseMap<AllocaInst *, unsigned> AllocaLookup; 234 235 /// \brief The PhiNodes we're adding. 236 /// 237 /// That map is used to simplify some Phi nodes as we iterate over it, so 238 /// it should have deterministic iterators. We could use a MapVector, but 239 /// since we already maintain a map from BasicBlock* to a stable numbering 240 /// (BBNumbers), the DenseMap is more efficient (also supports removal). 241 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes; 242 243 /// For each PHI node, keep track of which entry in Allocas it corresponds 244 /// to. 245 DenseMap<PHINode *, unsigned> PhiToAllocaMap; 246 247 /// If we are updating an AliasSetTracker, then for each alloca that is of 248 /// pointer type, we keep track of what to copyValue to the inserted PHI 249 /// nodes here. 250 std::vector<Value *> PointerAllocaValues; 251 252 /// For each alloca, we keep track of the dbg.declare intrinsic that 253 /// describes it, if any, so that we can convert it to a dbg.value 254 /// intrinsic if the alloca gets promoted. 255 SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares; 256 257 /// The set of basic blocks the renamer has already visited. 258 /// 259 SmallPtrSet<BasicBlock *, 16> Visited; 260 261 /// Contains a stable numbering of basic blocks to avoid non-determinstic 262 /// behavior. 263 DenseMap<BasicBlock *, unsigned> BBNumbers; 264 265 /// Lazily compute the number of predecessors a block has. 266 DenseMap<const BasicBlock *, unsigned> BBNumPreds; 267 268 public: 269 PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT, 270 AssumptionCache *AC) 271 : Allocas(Allocas.begin(), Allocas.end()), DT(DT), 272 DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false), 273 AC(AC) {} 274 275 void run(); 276 277 private: 278 void RemoveFromAllocasList(unsigned &AllocaIdx) { 279 Allocas[AllocaIdx] = Allocas.back(); 280 Allocas.pop_back(); 281 --AllocaIdx; 282 } 283 284 unsigned getNumPreds(const BasicBlock *BB) { 285 unsigned &NP = BBNumPreds[BB]; 286 if (NP == 0) 287 NP = std::distance(pred_begin(BB), pred_end(BB)) + 1; 288 return NP - 1; 289 } 290 291 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info, 292 const SmallPtrSetImpl<BasicBlock *> &DefBlocks, 293 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks); 294 void RenamePass(BasicBlock *BB, BasicBlock *Pred, 295 RenamePassData::ValVector &IncVals, 296 std::vector<RenamePassData> &Worklist); 297 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version); 298 }; 299 300 } // end of anonymous namespace 301 302 /// Given a LoadInst LI this adds assume(LI != null) after it. 303 static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) { 304 Function *AssumeIntrinsic = 305 Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume); 306 ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI, 307 Constant::getNullValue(LI->getType())); 308 LoadNotNull->insertAfter(LI); 309 CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull}); 310 CI->insertAfter(LoadNotNull); 311 AC->registerAssumption(CI); 312 } 313 314 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) { 315 // Knowing that this alloca is promotable, we know that it's safe to kill all 316 // instructions except for load and store. 317 318 for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) { 319 Instruction *I = cast<Instruction>(*UI); 320 ++UI; 321 if (isa<LoadInst>(I) || isa<StoreInst>(I)) 322 continue; 323 324 if (!I->getType()->isVoidTy()) { 325 // The only users of this bitcast/GEP instruction are lifetime intrinsics. 326 // Follow the use/def chain to erase them now instead of leaving it for 327 // dead code elimination later. 328 for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) { 329 Instruction *Inst = cast<Instruction>(*UUI); 330 ++UUI; 331 Inst->eraseFromParent(); 332 } 333 } 334 I->eraseFromParent(); 335 } 336 } 337 338 /// \brief Rewrite as many loads as possible given a single store. 339 /// 340 /// When there is only a single store, we can use the domtree to trivially 341 /// replace all of the dominated loads with the stored value. Do so, and return 342 /// true if this has successfully promoted the alloca entirely. If this returns 343 /// false there were some loads which were not dominated by the single store 344 /// and thus must be phi-ed with undef. We fall back to the standard alloca 345 /// promotion algorithm in that case. 346 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info, 347 LargeBlockInfo &LBI, DominatorTree &DT, 348 AssumptionCache *AC) { 349 StoreInst *OnlyStore = Info.OnlyStore; 350 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0)); 351 BasicBlock *StoreBB = OnlyStore->getParent(); 352 int StoreIndex = -1; 353 354 // Clear out UsingBlocks. We will reconstruct it here if needed. 355 Info.UsingBlocks.clear(); 356 357 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) { 358 Instruction *UserInst = cast<Instruction>(*UI++); 359 if (!isa<LoadInst>(UserInst)) { 360 assert(UserInst == OnlyStore && "Should only have load/stores"); 361 continue; 362 } 363 LoadInst *LI = cast<LoadInst>(UserInst); 364 365 // Okay, if we have a load from the alloca, we want to replace it with the 366 // only value stored to the alloca. We can do this if the value is 367 // dominated by the store. If not, we use the rest of the mem2reg machinery 368 // to insert the phi nodes as needed. 369 if (!StoringGlobalVal) { // Non-instructions are always dominated. 370 if (LI->getParent() == StoreBB) { 371 // If we have a use that is in the same block as the store, compare the 372 // indices of the two instructions to see which one came first. If the 373 // load came before the store, we can't handle it. 374 if (StoreIndex == -1) 375 StoreIndex = LBI.getInstructionIndex(OnlyStore); 376 377 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) { 378 // Can't handle this load, bail out. 379 Info.UsingBlocks.push_back(StoreBB); 380 continue; 381 } 382 383 } else if (LI->getParent() != StoreBB && 384 !DT.dominates(StoreBB, LI->getParent())) { 385 // If the load and store are in different blocks, use BB dominance to 386 // check their relationships. If the store doesn't dom the use, bail 387 // out. 388 Info.UsingBlocks.push_back(LI->getParent()); 389 continue; 390 } 391 } 392 393 // Otherwise, we *can* safely rewrite this load. 394 Value *ReplVal = OnlyStore->getOperand(0); 395 // If the replacement value is the load, this must occur in unreachable 396 // code. 397 if (ReplVal == LI) 398 ReplVal = UndefValue::get(LI->getType()); 399 400 // If the load was marked as nonnull we don't want to lose 401 // that information when we erase this Load. So we preserve 402 // it with an assume. 403 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) && 404 !llvm::isKnownNonNullAt(ReplVal, LI, &DT)) 405 addAssumeNonNull(AC, LI); 406 407 LI->replaceAllUsesWith(ReplVal); 408 LI->eraseFromParent(); 409 LBI.deleteValue(LI); 410 } 411 412 // Finally, after the scan, check to see if the store is all that is left. 413 if (!Info.UsingBlocks.empty()) 414 return false; // If not, we'll have to fall back for the remainder. 415 416 // Record debuginfo for the store and remove the declaration's 417 // debuginfo. 418 if (DbgDeclareInst *DDI = Info.DbgDeclare) { 419 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false); 420 ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB); 421 DDI->eraseFromParent(); 422 LBI.deleteValue(DDI); 423 } 424 // Remove the (now dead) store and alloca. 425 Info.OnlyStore->eraseFromParent(); 426 LBI.deleteValue(Info.OnlyStore); 427 428 AI->eraseFromParent(); 429 LBI.deleteValue(AI); 430 return true; 431 } 432 433 /// Many allocas are only used within a single basic block. If this is the 434 /// case, avoid traversing the CFG and inserting a lot of potentially useless 435 /// PHI nodes by just performing a single linear pass over the basic block 436 /// using the Alloca. 437 /// 438 /// If we cannot promote this alloca (because it is read before it is written), 439 /// return false. This is necessary in cases where, due to control flow, the 440 /// alloca is undefined only on some control flow paths. e.g. code like 441 /// this is correct in LLVM IR: 442 /// // A is an alloca with no stores so far 443 /// for (...) { 444 /// int t = *A; 445 /// if (!first_iteration) 446 /// use(t); 447 /// *A = 42; 448 /// } 449 static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info, 450 LargeBlockInfo &LBI, 451 DominatorTree &DT, 452 AssumptionCache *AC) { 453 // The trickiest case to handle is when we have large blocks. Because of this, 454 // this code is optimized assuming that large blocks happen. This does not 455 // significantly pessimize the small block case. This uses LargeBlockInfo to 456 // make it efficient to get the index of various operations in the block. 457 458 // Walk the use-def list of the alloca, getting the locations of all stores. 459 typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy; 460 StoresByIndexTy StoresByIndex; 461 462 for (User *U : AI->users()) 463 if (StoreInst *SI = dyn_cast<StoreInst>(U)) 464 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI)); 465 466 // Sort the stores by their index, making it efficient to do a lookup with a 467 // binary search. 468 std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first()); 469 470 // Walk all of the loads from this alloca, replacing them with the nearest 471 // store above them, if any. 472 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) { 473 LoadInst *LI = dyn_cast<LoadInst>(*UI++); 474 if (!LI) 475 continue; 476 477 unsigned LoadIdx = LBI.getInstructionIndex(LI); 478 479 // Find the nearest store that has a lower index than this load. 480 StoresByIndexTy::iterator I = 481 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(), 482 std::make_pair(LoadIdx, 483 static_cast<StoreInst *>(nullptr)), 484 less_first()); 485 if (I == StoresByIndex.begin()) { 486 if (StoresByIndex.empty()) 487 // If there are no stores, the load takes the undef value. 488 LI->replaceAllUsesWith(UndefValue::get(LI->getType())); 489 else 490 // There is no store before this load, bail out (load may be affected 491 // by the following stores - see main comment). 492 return false; 493 } else { 494 // Otherwise, there was a store before this load, the load takes its value. 495 // Note, if the load was marked as nonnull we don't want to lose that 496 // information when we erase it. So we preserve it with an assume. 497 Value *ReplVal = std::prev(I)->second->getOperand(0); 498 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) && 499 !llvm::isKnownNonNullAt(ReplVal, LI, &DT)) 500 addAssumeNonNull(AC, LI); 501 502 LI->replaceAllUsesWith(ReplVal); 503 } 504 505 LI->eraseFromParent(); 506 LBI.deleteValue(LI); 507 } 508 509 // Remove the (now dead) stores and alloca. 510 while (!AI->use_empty()) { 511 StoreInst *SI = cast<StoreInst>(AI->user_back()); 512 // Record debuginfo for the store before removing it. 513 if (DbgDeclareInst *DDI = Info.DbgDeclare) { 514 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false); 515 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 516 } 517 SI->eraseFromParent(); 518 LBI.deleteValue(SI); 519 } 520 521 AI->eraseFromParent(); 522 LBI.deleteValue(AI); 523 524 // The alloca's debuginfo can be removed as well. 525 if (DbgDeclareInst *DDI = Info.DbgDeclare) { 526 DDI->eraseFromParent(); 527 LBI.deleteValue(DDI); 528 } 529 530 ++NumLocalPromoted; 531 return true; 532 } 533 534 void PromoteMem2Reg::run() { 535 Function &F = *DT.getRoot()->getParent(); 536 537 AllocaDbgDeclares.resize(Allocas.size()); 538 539 AllocaInfo Info; 540 LargeBlockInfo LBI; 541 ForwardIDFCalculator IDF(DT); 542 543 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) { 544 AllocaInst *AI = Allocas[AllocaNum]; 545 546 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!"); 547 assert(AI->getParent()->getParent() == &F && 548 "All allocas should be in the same function, which is same as DF!"); 549 550 removeLifetimeIntrinsicUsers(AI); 551 552 if (AI->use_empty()) { 553 // If there are no uses of the alloca, just delete it now. 554 AI->eraseFromParent(); 555 556 // Remove the alloca from the Allocas list, since it has been processed 557 RemoveFromAllocasList(AllocaNum); 558 ++NumDeadAlloca; 559 continue; 560 } 561 562 // Calculate the set of read and write-locations for each alloca. This is 563 // analogous to finding the 'uses' and 'definitions' of each variable. 564 Info.AnalyzeAlloca(AI); 565 566 // If there is only a single store to this value, replace any loads of 567 // it that are directly dominated by the definition with the value stored. 568 if (Info.DefiningBlocks.size() == 1) { 569 if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AC)) { 570 // The alloca has been processed, move on. 571 RemoveFromAllocasList(AllocaNum); 572 ++NumSingleStore; 573 continue; 574 } 575 } 576 577 // If the alloca is only read and written in one basic block, just perform a 578 // linear sweep over the block to eliminate it. 579 if (Info.OnlyUsedInOneBlock && 580 promoteSingleBlockAlloca(AI, Info, LBI, DT, AC)) { 581 // The alloca has been processed, move on. 582 RemoveFromAllocasList(AllocaNum); 583 continue; 584 } 585 586 // If we haven't computed a numbering for the BB's in the function, do so 587 // now. 588 if (BBNumbers.empty()) { 589 unsigned ID = 0; 590 for (auto &BB : F) 591 BBNumbers[&BB] = ID++; 592 } 593 594 // Remember the dbg.declare intrinsic describing this alloca, if any. 595 if (Info.DbgDeclare) 596 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare; 597 598 // Keep the reverse mapping of the 'Allocas' array for the rename pass. 599 AllocaLookup[Allocas[AllocaNum]] = AllocaNum; 600 601 // At this point, we're committed to promoting the alloca using IDF's, and 602 // the standard SSA construction algorithm. Determine which blocks need PHI 603 // nodes and see if we can optimize out some work by avoiding insertion of 604 // dead phi nodes. 605 606 607 // Unique the set of defining blocks for efficient lookup. 608 SmallPtrSet<BasicBlock *, 32> DefBlocks; 609 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end()); 610 611 // Determine which blocks the value is live in. These are blocks which lead 612 // to uses. 613 SmallPtrSet<BasicBlock *, 32> LiveInBlocks; 614 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks); 615 616 // At this point, we're committed to promoting the alloca using IDF's, and 617 // the standard SSA construction algorithm. Determine which blocks need phi 618 // nodes and see if we can optimize out some work by avoiding insertion of 619 // dead phi nodes. 620 IDF.setLiveInBlocks(LiveInBlocks); 621 IDF.setDefiningBlocks(DefBlocks); 622 SmallVector<BasicBlock *, 32> PHIBlocks; 623 IDF.calculate(PHIBlocks); 624 if (PHIBlocks.size() > 1) 625 std::sort(PHIBlocks.begin(), PHIBlocks.end(), 626 [this](BasicBlock *A, BasicBlock *B) { 627 return BBNumbers.lookup(A) < BBNumbers.lookup(B); 628 }); 629 630 unsigned CurrentVersion = 0; 631 for (unsigned i = 0, e = PHIBlocks.size(); i != e; ++i) 632 QueuePhiNode(PHIBlocks[i], AllocaNum, CurrentVersion); 633 } 634 635 if (Allocas.empty()) 636 return; // All of the allocas must have been trivial! 637 638 LBI.clear(); 639 640 // Set the incoming values for the basic block to be null values for all of 641 // the alloca's. We do this in case there is a load of a value that has not 642 // been stored yet. In this case, it will get this null value. 643 // 644 RenamePassData::ValVector Values(Allocas.size()); 645 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) 646 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType()); 647 648 // Walks all basic blocks in the function performing the SSA rename algorithm 649 // and inserting the phi nodes we marked as necessary 650 // 651 std::vector<RenamePassData> RenamePassWorkList; 652 RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values)); 653 do { 654 RenamePassData RPD; 655 RPD.swap(RenamePassWorkList.back()); 656 RenamePassWorkList.pop_back(); 657 // RenamePass may add new worklist entries. 658 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList); 659 } while (!RenamePassWorkList.empty()); 660 661 // The renamer uses the Visited set to avoid infinite loops. Clear it now. 662 Visited.clear(); 663 664 // Remove the allocas themselves from the function. 665 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) { 666 Instruction *A = Allocas[i]; 667 668 // If there are any uses of the alloca instructions left, they must be in 669 // unreachable basic blocks that were not processed by walking the dominator 670 // tree. Just delete the users now. 671 if (!A->use_empty()) 672 A->replaceAllUsesWith(UndefValue::get(A->getType())); 673 A->eraseFromParent(); 674 } 675 676 const DataLayout &DL = F.getParent()->getDataLayout(); 677 678 // Remove alloca's dbg.declare instrinsics from the function. 679 for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i) 680 if (DbgDeclareInst *DDI = AllocaDbgDeclares[i]) 681 DDI->eraseFromParent(); 682 683 // Loop over all of the PHI nodes and see if there are any that we can get 684 // rid of because they merge all of the same incoming values. This can 685 // happen due to undef values coming into the PHI nodes. This process is 686 // iterative, because eliminating one PHI node can cause others to be removed. 687 bool EliminatedAPHI = true; 688 while (EliminatedAPHI) { 689 EliminatedAPHI = false; 690 691 // Iterating over NewPhiNodes is deterministic, so it is safe to try to 692 // simplify and RAUW them as we go. If it was not, we could add uses to 693 // the values we replace with in a non-deterministic order, thus creating 694 // non-deterministic def->use chains. 695 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator 696 I = NewPhiNodes.begin(), 697 E = NewPhiNodes.end(); 698 I != E;) { 699 PHINode *PN = I->second; 700 701 // If this PHI node merges one value and/or undefs, get the value. 702 if (Value *V = SimplifyInstruction(PN, DL, nullptr, &DT, AC)) { 703 PN->replaceAllUsesWith(V); 704 PN->eraseFromParent(); 705 NewPhiNodes.erase(I++); 706 EliminatedAPHI = true; 707 continue; 708 } 709 ++I; 710 } 711 } 712 713 // At this point, the renamer has added entries to PHI nodes for all reachable 714 // code. Unfortunately, there may be unreachable blocks which the renamer 715 // hasn't traversed. If this is the case, the PHI nodes may not 716 // have incoming values for all predecessors. Loop over all PHI nodes we have 717 // created, inserting undef values if they are missing any incoming values. 718 // 719 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator 720 I = NewPhiNodes.begin(), 721 E = NewPhiNodes.end(); 722 I != E; ++I) { 723 // We want to do this once per basic block. As such, only process a block 724 // when we find the PHI that is the first entry in the block. 725 PHINode *SomePHI = I->second; 726 BasicBlock *BB = SomePHI->getParent(); 727 if (&BB->front() != SomePHI) 728 continue; 729 730 // Only do work here if there the PHI nodes are missing incoming values. We 731 // know that all PHI nodes that were inserted in a block will have the same 732 // number of incoming values, so we can just check any of them. 733 if (SomePHI->getNumIncomingValues() == getNumPreds(BB)) 734 continue; 735 736 // Get the preds for BB. 737 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); 738 739 // Ok, now we know that all of the PHI nodes are missing entries for some 740 // basic blocks. Start by sorting the incoming predecessors for efficient 741 // access. 742 std::sort(Preds.begin(), Preds.end()); 743 744 // Now we loop through all BB's which have entries in SomePHI and remove 745 // them from the Preds list. 746 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) { 747 // Do a log(n) search of the Preds list for the entry we want. 748 SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound( 749 Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i)); 750 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) && 751 "PHI node has entry for a block which is not a predecessor!"); 752 753 // Remove the entry 754 Preds.erase(EntIt); 755 } 756 757 // At this point, the blocks left in the preds list must have dummy 758 // entries inserted into every PHI nodes for the block. Update all the phi 759 // nodes in this block that we are inserting (there could be phis before 760 // mem2reg runs). 761 unsigned NumBadPreds = SomePHI->getNumIncomingValues(); 762 BasicBlock::iterator BBI = BB->begin(); 763 while ((SomePHI = dyn_cast<PHINode>(BBI++)) && 764 SomePHI->getNumIncomingValues() == NumBadPreds) { 765 Value *UndefVal = UndefValue::get(SomePHI->getType()); 766 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred) 767 SomePHI->addIncoming(UndefVal, Preds[pred]); 768 } 769 } 770 771 NewPhiNodes.clear(); 772 } 773 774 /// \brief Determine which blocks the value is live in. 775 /// 776 /// These are blocks which lead to uses. Knowing this allows us to avoid 777 /// inserting PHI nodes into blocks which don't lead to uses (thus, the 778 /// inserted phi nodes would be dead). 779 void PromoteMem2Reg::ComputeLiveInBlocks( 780 AllocaInst *AI, AllocaInfo &Info, 781 const SmallPtrSetImpl<BasicBlock *> &DefBlocks, 782 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) { 783 784 // To determine liveness, we must iterate through the predecessors of blocks 785 // where the def is live. Blocks are added to the worklist if we need to 786 // check their predecessors. Start with all the using blocks. 787 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(), 788 Info.UsingBlocks.end()); 789 790 // If any of the using blocks is also a definition block, check to see if the 791 // definition occurs before or after the use. If it happens before the use, 792 // the value isn't really live-in. 793 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) { 794 BasicBlock *BB = LiveInBlockWorklist[i]; 795 if (!DefBlocks.count(BB)) 796 continue; 797 798 // Okay, this is a block that both uses and defines the value. If the first 799 // reference to the alloca is a def (store), then we know it isn't live-in. 800 for (BasicBlock::iterator I = BB->begin();; ++I) { 801 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 802 if (SI->getOperand(1) != AI) 803 continue; 804 805 // We found a store to the alloca before a load. The alloca is not 806 // actually live-in here. 807 LiveInBlockWorklist[i] = LiveInBlockWorklist.back(); 808 LiveInBlockWorklist.pop_back(); 809 --i; 810 --e; 811 break; 812 } 813 814 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 815 if (LI->getOperand(0) != AI) 816 continue; 817 818 // Okay, we found a load before a store to the alloca. It is actually 819 // live into this block. 820 break; 821 } 822 } 823 } 824 825 // Now that we have a set of blocks where the phi is live-in, recursively add 826 // their predecessors until we find the full region the value is live. 827 while (!LiveInBlockWorklist.empty()) { 828 BasicBlock *BB = LiveInBlockWorklist.pop_back_val(); 829 830 // The block really is live in here, insert it into the set. If already in 831 // the set, then it has already been processed. 832 if (!LiveInBlocks.insert(BB).second) 833 continue; 834 835 // Since the value is live into BB, it is either defined in a predecessor or 836 // live into it to. Add the preds to the worklist unless they are a 837 // defining block. 838 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 839 BasicBlock *P = *PI; 840 841 // The value is not live into a predecessor if it defines the value. 842 if (DefBlocks.count(P)) 843 continue; 844 845 // Otherwise it is, add to the worklist. 846 LiveInBlockWorklist.push_back(P); 847 } 848 } 849 } 850 851 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca. 852 /// 853 /// Returns true if there wasn't already a phi-node for that variable 854 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo, 855 unsigned &Version) { 856 // Look up the basic-block in question. 857 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)]; 858 859 // If the BB already has a phi node added for the i'th alloca then we're done! 860 if (PN) 861 return false; 862 863 // Create a PhiNode using the dereferenced type... and add the phi-node to the 864 // BasicBlock. 865 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB), 866 Allocas[AllocaNo]->getName() + "." + Twine(Version++), 867 &BB->front()); 868 ++NumPHIInsert; 869 PhiToAllocaMap[PN] = AllocaNo; 870 return true; 871 } 872 873 /// \brief Recursively traverse the CFG of the function, renaming loads and 874 /// stores to the allocas which we are promoting. 875 /// 876 /// IncomingVals indicates what value each Alloca contains on exit from the 877 /// predecessor block Pred. 878 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred, 879 RenamePassData::ValVector &IncomingVals, 880 std::vector<RenamePassData> &Worklist) { 881 NextIteration: 882 // If we are inserting any phi nodes into this BB, they will already be in the 883 // block. 884 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) { 885 // If we have PHI nodes to update, compute the number of edges from Pred to 886 // BB. 887 if (PhiToAllocaMap.count(APN)) { 888 // We want to be able to distinguish between PHI nodes being inserted by 889 // this invocation of mem2reg from those phi nodes that already existed in 890 // the IR before mem2reg was run. We determine that APN is being inserted 891 // because it is missing incoming edges. All other PHI nodes being 892 // inserted by this pass of mem2reg will have the same number of incoming 893 // operands so far. Remember this count. 894 unsigned NewPHINumOperands = APN->getNumOperands(); 895 896 unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB); 897 assert(NumEdges && "Must be at least one edge from Pred to BB!"); 898 899 // Add entries for all the phis. 900 BasicBlock::iterator PNI = BB->begin(); 901 do { 902 unsigned AllocaNo = PhiToAllocaMap[APN]; 903 904 // Add N incoming values to the PHI node. 905 for (unsigned i = 0; i != NumEdges; ++i) 906 APN->addIncoming(IncomingVals[AllocaNo], Pred); 907 908 // The currently active variable for this block is now the PHI. 909 IncomingVals[AllocaNo] = APN; 910 if (DbgDeclareInst *DDI = AllocaDbgDeclares[AllocaNo]) 911 ConvertDebugDeclareToDebugValue(DDI, APN, DIB); 912 913 // Get the next phi node. 914 ++PNI; 915 APN = dyn_cast<PHINode>(PNI); 916 if (!APN) 917 break; 918 919 // Verify that it is missing entries. If not, it is not being inserted 920 // by this mem2reg invocation so we want to ignore it. 921 } while (APN->getNumOperands() == NewPHINumOperands); 922 } 923 } 924 925 // Don't revisit blocks. 926 if (!Visited.insert(BB).second) 927 return; 928 929 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) { 930 Instruction *I = &*II++; // get the instruction, increment iterator 931 932 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 933 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand()); 934 if (!Src) 935 continue; 936 937 DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src); 938 if (AI == AllocaLookup.end()) 939 continue; 940 941 Value *V = IncomingVals[AI->second]; 942 943 // If the load was marked as nonnull we don't want to lose 944 // that information when we erase this Load. So we preserve 945 // it with an assume. 946 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) && 947 !llvm::isKnownNonNullAt(V, LI, &DT)) 948 addAssumeNonNull(AC, LI); 949 950 // Anything using the load now uses the current value. 951 LI->replaceAllUsesWith(V); 952 BB->getInstList().erase(LI); 953 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 954 // Delete this instruction and mark the name as the current holder of the 955 // value 956 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand()); 957 if (!Dest) 958 continue; 959 960 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest); 961 if (ai == AllocaLookup.end()) 962 continue; 963 964 // what value were we writing? 965 IncomingVals[ai->second] = SI->getOperand(0); 966 // Record debuginfo for the store before removing it. 967 if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second]) 968 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 969 BB->getInstList().erase(SI); 970 } 971 } 972 973 // 'Recurse' to our successors. 974 succ_iterator I = succ_begin(BB), E = succ_end(BB); 975 if (I == E) 976 return; 977 978 // Keep track of the successors so we don't visit the same successor twice 979 SmallPtrSet<BasicBlock *, 8> VisitedSuccs; 980 981 // Handle the first successor without using the worklist. 982 VisitedSuccs.insert(*I); 983 Pred = BB; 984 BB = *I; 985 ++I; 986 987 for (; I != E; ++I) 988 if (VisitedSuccs.insert(*I).second) 989 Worklist.emplace_back(*I, Pred, IncomingVals); 990 991 goto NextIteration; 992 } 993 994 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT, 995 AssumptionCache *AC) { 996 // If there is nothing to do, bail out... 997 if (Allocas.empty()) 998 return; 999 1000 PromoteMem2Reg(Allocas, DT, AC).run(); 1001 } 1002