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