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