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