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