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