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