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