681facdfd198274f010484a1e95a3c8d1aa54045
[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/DenseMap.h"
31 #include "llvm/ADT/Hashing.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(const std::vector<AllocaInst *> &Allocas, DominatorTree &DT,
283                  AliasSetTracker *AST)
284       : Allocas(Allocas), DT(DT), DIB(*DT.getRoot()->getParent()->getParent()),
285         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 /// If there is only a single store to this value, replace any loads of it that
343 /// are directly dominated by the definition with the value stored.
344 static void rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
345                                      LargeBlockInfo &LBI,
346                                      DominatorTree &DT,
347                                      AliasSetTracker *AST) {
348   StoreInst *OnlyStore = Info.OnlyStore;
349   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
350   BasicBlock *StoreBB = OnlyStore->getParent();
351   int StoreIndex = -1;
352
353   // Clear out UsingBlocks.  We will reconstruct it here if needed.
354   Info.UsingBlocks.clear();
355
356   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
357     Instruction *UserInst = cast<Instruction>(*UI++);
358     if (!isa<LoadInst>(UserInst)) {
359       assert(UserInst == OnlyStore && "Should only have load/stores");
360       continue;
361     }
362     LoadInst *LI = cast<LoadInst>(UserInst);
363
364     // Okay, if we have a load from the alloca, we want to replace it with the
365     // only value stored to the alloca.  We can do this if the value is
366     // dominated by the store.  If not, we use the rest of the mem2reg machinery
367     // to insert the phi nodes as needed.
368     if (!StoringGlobalVal) { // Non-instructions are always dominated.
369       if (LI->getParent() == StoreBB) {
370         // If we have a use that is in the same block as the store, compare the
371         // indices of the two instructions to see which one came first.  If the
372         // load came before the store, we can't handle it.
373         if (StoreIndex == -1)
374           StoreIndex = LBI.getInstructionIndex(OnlyStore);
375
376         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
377           // Can't handle this load, bail out.
378           Info.UsingBlocks.push_back(StoreBB);
379           continue;
380         }
381
382       } else if (LI->getParent() != StoreBB &&
383                  !DT.dominates(StoreBB, LI->getParent())) {
384         // If the load and store are in different blocks, use BB dominance to
385         // check their relationships.  If the store doesn't dom the use, bail
386         // out.
387         Info.UsingBlocks.push_back(LI->getParent());
388         continue;
389       }
390     }
391
392     // Otherwise, we *can* safely rewrite this load.
393     Value *ReplVal = OnlyStore->getOperand(0);
394     // If the replacement value is the load, this must occur in unreachable
395     // code.
396     if (ReplVal == LI)
397       ReplVal = UndefValue::get(LI->getType());
398     LI->replaceAllUsesWith(ReplVal);
399     if (AST && LI->getType()->isPointerTy())
400       AST->deleteValue(LI);
401     LI->eraseFromParent();
402     LBI.deleteValue(LI);
403   }
404 }
405
406 namespace {
407 /// This is a helper predicate used to search by the first element of a pair.
408 struct StoreIndexSearchPredicate {
409   bool operator()(const std::pair<unsigned, StoreInst *> &LHS,
410                   const std::pair<unsigned, StoreInst *> &RHS) {
411     return LHS.first < RHS.first;
412   }
413 };
414 }
415
416 /// Many allocas are only used within a single basic block.  If this is the
417 /// case, avoid traversing the CFG and inserting a lot of potentially useless
418 /// PHI nodes by just performing a single linear pass over the basic block
419 /// using the Alloca.
420 ///
421 /// If we cannot promote this alloca (because it is read before it is written),
422 /// return true.  This is necessary in cases where, due to control flow, the
423 /// alloca is potentially undefined on some control flow paths.  e.g. code like
424 /// this is potentially correct:
425 ///
426 ///   for (...) { if (c) { A = undef; undef = B; } }
427 ///
428 /// ... so long as A is not used before undef is set.
429 static void promoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
430                                      LargeBlockInfo &LBI,
431                                      AliasSetTracker *AST) {
432   // The trickiest case to handle is when we have large blocks. Because of this,
433   // this code is optimized assuming that large blocks happen.  This does not
434   // significantly pessimize the small block case.  This uses LargeBlockInfo to
435   // make it efficient to get the index of various operations in the block.
436
437   // Clear out UsingBlocks.  We will reconstruct it here if needed.
438   Info.UsingBlocks.clear();
439
440   // Walk the use-def list of the alloca, getting the locations of all stores.
441   typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
442   StoresByIndexTy StoresByIndex;
443
444   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;
445        ++UI)
446     if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
447       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
448
449   // If there are no stores to the alloca, just replace any loads with undef.
450   if (StoresByIndex.empty()) {
451     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;)
452       if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
453         LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
454         if (AST && LI->getType()->isPointerTy())
455           AST->deleteValue(LI);
456         LBI.deleteValue(LI);
457         LI->eraseFromParent();
458       }
459     return;
460   }
461
462   // Sort the stores by their index, making it efficient to do a lookup with a
463   // binary search.
464   std::sort(StoresByIndex.begin(), StoresByIndex.end());
465
466   // Walk all of the loads from this alloca, replacing them with the nearest
467   // store above them, if any.
468   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
469     LoadInst *LI = dyn_cast<LoadInst>(*UI++);
470     if (!LI)
471       continue;
472
473     unsigned LoadIdx = LBI.getInstructionIndex(LI);
474
475     // Find the nearest store that has a lower than this load.
476     StoresByIndexTy::iterator I = std::lower_bound(
477         StoresByIndex.begin(), StoresByIndex.end(),
478         std::pair<unsigned, StoreInst *>(LoadIdx, static_cast<StoreInst *>(0)),
479         StoreIndexSearchPredicate());
480
481     // If there is no store before this load, then we can't promote this load.
482     if (I == StoresByIndex.begin()) {
483       // Can't handle this load, bail out.
484       Info.UsingBlocks.push_back(LI->getParent());
485       continue;
486     }
487
488     // Otherwise, there was a store before this load, the load takes its value.
489     --I;
490     LI->replaceAllUsesWith(I->second->getOperand(0));
491     if (AST && LI->getType()->isPointerTy())
492       AST->deleteValue(LI);
493     LI->eraseFromParent();
494     LBI.deleteValue(LI);
495   }
496 }
497
498 void PromoteMem2Reg::run() {
499   Function &F = *DT.getRoot()->getParent();
500
501   if (AST)
502     PointerAllocaValues.resize(Allocas.size());
503   AllocaDbgDeclares.resize(Allocas.size());
504
505   AllocaInfo Info;
506   LargeBlockInfo LBI;
507
508   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
509     AllocaInst *AI = Allocas[AllocaNum];
510
511     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
512     assert(AI->getParent()->getParent() == &F &&
513            "All allocas should be in the same function, which is same as DF!");
514
515     removeLifetimeIntrinsicUsers(AI);
516
517     if (AI->use_empty()) {
518       // If there are no uses of the alloca, just delete it now.
519       if (AST)
520         AST->deleteValue(AI);
521       AI->eraseFromParent();
522
523       // Remove the alloca from the Allocas list, since it has been processed
524       RemoveFromAllocasList(AllocaNum);
525       ++NumDeadAlloca;
526       continue;
527     }
528
529     // Calculate the set of read and write-locations for each alloca.  This is
530     // analogous to finding the 'uses' and 'definitions' of each variable.
531     Info.AnalyzeAlloca(AI);
532
533     // If there is only a single store to this value, replace any loads of
534     // it that are directly dominated by the definition with the value stored.
535     if (Info.DefiningBlocks.size() == 1) {
536       rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST);
537
538       // Finally, after the scan, check to see if the store is all that is left.
539       if (Info.UsingBlocks.empty()) {
540         // Record debuginfo for the store and remove the declaration's
541         // debuginfo.
542         if (DbgDeclareInst *DDI = Info.DbgDeclare) {
543           ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
544           DDI->eraseFromParent();
545         }
546         // Remove the (now dead) store and alloca.
547         Info.OnlyStore->eraseFromParent();
548         LBI.deleteValue(Info.OnlyStore);
549
550         if (AST)
551           AST->deleteValue(AI);
552         AI->eraseFromParent();
553         LBI.deleteValue(AI);
554
555         // The alloca has been processed, move on.
556         RemoveFromAllocasList(AllocaNum);
557
558         ++NumSingleStore;
559         continue;
560       }
561     }
562
563     // If the alloca is only read and written in one basic block, just perform a
564     // linear sweep over the block to eliminate it.
565     if (Info.OnlyUsedInOneBlock) {
566       promoteSingleBlockAlloca(AI, Info, LBI, AST);
567
568       // Finally, after the scan, check to see if the stores are all that is
569       // left.
570       if (Info.UsingBlocks.empty()) {
571
572         // Remove the (now dead) stores and alloca.
573         while (!AI->use_empty()) {
574           StoreInst *SI = cast<StoreInst>(AI->use_back());
575           // Record debuginfo for the store before removing it.
576           if (DbgDeclareInst *DDI = Info.DbgDeclare)
577             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
578           SI->eraseFromParent();
579           LBI.deleteValue(SI);
580         }
581
582         if (AST)
583           AST->deleteValue(AI);
584         AI->eraseFromParent();
585         LBI.deleteValue(AI);
586
587         // The alloca has been processed, move on.
588         RemoveFromAllocasList(AllocaNum);
589
590         // The alloca's debuginfo can be removed as well.
591         if (DbgDeclareInst *DDI = Info.DbgDeclare)
592           DDI->eraseFromParent();
593
594         ++NumLocalPromoted;
595         continue;
596       }
597     }
598
599     // If we haven't computed dominator tree levels, do so now.
600     if (DomLevels.empty()) {
601       SmallVector<DomTreeNode *, 32> Worklist;
602
603       DomTreeNode *Root = DT.getRootNode();
604       DomLevels[Root] = 0;
605       Worklist.push_back(Root);
606
607       while (!Worklist.empty()) {
608         DomTreeNode *Node = Worklist.pop_back_val();
609         unsigned ChildLevel = DomLevels[Node] + 1;
610         for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
611              CI != CE; ++CI) {
612           DomLevels[*CI] = ChildLevel;
613           Worklist.push_back(*CI);
614         }
615       }
616     }
617
618     // If we haven't computed a numbering for the BB's in the function, do so
619     // now.
620     if (BBNumbers.empty()) {
621       unsigned ID = 0;
622       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
623         BBNumbers[I] = ID++;
624     }
625
626     // If we have an AST to keep updated, remember some pointer value that is
627     // stored into the alloca.
628     if (AST)
629       PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
630
631     // Remember the dbg.declare intrinsic describing this alloca, if any.
632     if (Info.DbgDeclare)
633       AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
634
635     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
636     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
637
638     // At this point, we're committed to promoting the alloca using IDF's, and
639     // the standard SSA construction algorithm.  Determine which blocks need PHI
640     // nodes and see if we can optimize out some work by avoiding insertion of
641     // dead phi nodes.
642     DetermineInsertionPoint(AI, AllocaNum, Info);
643   }
644
645   if (Allocas.empty())
646     return; // All of the allocas must have been trivial!
647
648   LBI.clear();
649
650   // Set the incoming values for the basic block to be null values for all of
651   // the alloca's.  We do this in case there is a load of a value that has not
652   // been stored yet.  In this case, it will get this null value.
653   //
654   RenamePassData::ValVector Values(Allocas.size());
655   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
656     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
657
658   // Walks all basic blocks in the function performing the SSA rename algorithm
659   // and inserting the phi nodes we marked as necessary
660   //
661   std::vector<RenamePassData> RenamePassWorkList;
662   RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
663   do {
664     RenamePassData RPD;
665     RPD.swap(RenamePassWorkList.back());
666     RenamePassWorkList.pop_back();
667     // RenamePass may add new worklist entries.
668     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
669   } while (!RenamePassWorkList.empty());
670
671   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
672   Visited.clear();
673
674   // Remove the allocas themselves from the function.
675   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
676     Instruction *A = Allocas[i];
677
678     // If there are any uses of the alloca instructions left, they must be in
679     // unreachable basic blocks that were not processed by walking the dominator
680     // tree. Just delete the users now.
681     if (!A->use_empty())
682       A->replaceAllUsesWith(UndefValue::get(A->getType()));
683     if (AST)
684       AST->deleteValue(A);
685     A->eraseFromParent();
686   }
687
688   // Remove alloca's dbg.declare instrinsics from the function.
689   for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
690     if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
691       DDI->eraseFromParent();
692
693   // Loop over all of the PHI nodes and see if there are any that we can get
694   // rid of because they merge all of the same incoming values.  This can
695   // happen due to undef values coming into the PHI nodes.  This process is
696   // iterative, because eliminating one PHI node can cause others to be removed.
697   bool EliminatedAPHI = true;
698   while (EliminatedAPHI) {
699     EliminatedAPHI = false;
700
701     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
702     // simplify and RAUW them as we go.  If it was not, we could add uses to
703     // the values we replace with in a non deterministic order, thus creating
704     // non deterministic def->use chains.
705     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
706              I = NewPhiNodes.begin(),
707              E = NewPhiNodes.end();
708          I != E;) {
709       PHINode *PN = I->second;
710
711       // If this PHI node merges one value and/or undefs, get the value.
712       if (Value *V = SimplifyInstruction(PN, 0, 0, &DT)) {
713         if (AST && PN->getType()->isPointerTy())
714           AST->deleteValue(PN);
715         PN->replaceAllUsesWith(V);
716         PN->eraseFromParent();
717         NewPhiNodes.erase(I++);
718         EliminatedAPHI = true;
719         continue;
720       }
721       ++I;
722     }
723   }
724
725   // At this point, the renamer has added entries to PHI nodes for all reachable
726   // code.  Unfortunately, there may be unreachable blocks which the renamer
727   // hasn't traversed.  If this is the case, the PHI nodes may not
728   // have incoming values for all predecessors.  Loop over all PHI nodes we have
729   // created, inserting undef values if they are missing any incoming values.
730   //
731   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
732            I = NewPhiNodes.begin(),
733            E = NewPhiNodes.end();
734        I != E; ++I) {
735     // We want to do this once per basic block.  As such, only process a block
736     // when we find the PHI that is the first entry in the block.
737     PHINode *SomePHI = I->second;
738     BasicBlock *BB = SomePHI->getParent();
739     if (&BB->front() != SomePHI)
740       continue;
741
742     // Only do work here if there the PHI nodes are missing incoming values.  We
743     // know that all PHI nodes that were inserted in a block will have the same
744     // number of incoming values, so we can just check any of them.
745     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
746       continue;
747
748     // Get the preds for BB.
749     SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
750
751     // Ok, now we know that all of the PHI nodes are missing entries for some
752     // basic blocks.  Start by sorting the incoming predecessors for efficient
753     // access.
754     std::sort(Preds.begin(), Preds.end());
755
756     // Now we loop through all BB's which have entries in SomePHI and remove
757     // them from the Preds list.
758     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
759       // Do a log(n) search of the Preds list for the entry we want.
760       SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
761           Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
762       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
763              "PHI node has entry for a block which is not a predecessor!");
764
765       // Remove the entry
766       Preds.erase(EntIt);
767     }
768
769     // At this point, the blocks left in the preds list must have dummy
770     // entries inserted into every PHI nodes for the block.  Update all the phi
771     // nodes in this block that we are inserting (there could be phis before
772     // mem2reg runs).
773     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
774     BasicBlock::iterator BBI = BB->begin();
775     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
776            SomePHI->getNumIncomingValues() == NumBadPreds) {
777       Value *UndefVal = UndefValue::get(SomePHI->getType());
778       for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
779         SomePHI->addIncoming(UndefVal, Preds[pred]);
780     }
781   }
782
783   NewPhiNodes.clear();
784 }
785
786 /// \brief Determine which blocks the value is live in.
787 ///
788 /// These are blocks which lead to uses.  Knowing this allows us to avoid
789 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
790 /// inserted phi nodes would be dead).
791 void PromoteMem2Reg::ComputeLiveInBlocks(
792     AllocaInst *AI, AllocaInfo &Info,
793     const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
794     SmallPtrSet<BasicBlock *, 32> &LiveInBlocks) {
795
796   // To determine liveness, we must iterate through the predecessors of blocks
797   // where the def is live.  Blocks are added to the worklist if we need to
798   // check their predecessors.  Start with all the using blocks.
799   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
800                                                     Info.UsingBlocks.end());
801
802   // If any of the using blocks is also a definition block, check to see if the
803   // definition occurs before or after the use.  If it happens before the use,
804   // the value isn't really live-in.
805   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
806     BasicBlock *BB = LiveInBlockWorklist[i];
807     if (!DefBlocks.count(BB))
808       continue;
809
810     // Okay, this is a block that both uses and defines the value.  If the first
811     // reference to the alloca is a def (store), then we know it isn't live-in.
812     for (BasicBlock::iterator I = BB->begin();; ++I) {
813       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
814         if (SI->getOperand(1) != AI)
815           continue;
816
817         // We found a store to the alloca before a load.  The alloca is not
818         // actually live-in here.
819         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
820         LiveInBlockWorklist.pop_back();
821         --i, --e;
822         break;
823       }
824
825       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
826         if (LI->getOperand(0) != AI)
827           continue;
828
829         // Okay, we found a load before a store to the alloca.  It is actually
830         // live into this block.
831         break;
832       }
833     }
834   }
835
836   // Now that we have a set of blocks where the phi is live-in, recursively add
837   // their predecessors until we find the full region the value is live.
838   while (!LiveInBlockWorklist.empty()) {
839     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
840
841     // The block really is live in here, insert it into the set.  If already in
842     // the set, then it has already been processed.
843     if (!LiveInBlocks.insert(BB))
844       continue;
845
846     // Since the value is live into BB, it is either defined in a predecessor or
847     // live into it to.  Add the preds to the worklist unless they are a
848     // defining block.
849     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
850       BasicBlock *P = *PI;
851
852       // The value is not live into a predecessor if it defines the value.
853       if (DefBlocks.count(P))
854         continue;
855
856       // Otherwise it is, add to the worklist.
857       LiveInBlockWorklist.push_back(P);
858     }
859   }
860 }
861
862 namespace {
863 typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
864
865 struct DomTreeNodeCompare {
866   bool operator()(const DomTreeNodePair &LHS, const DomTreeNodePair &RHS) {
867     return LHS.second < RHS.second;
868   }
869 };
870 } // end anonymous namespace
871
872 /// At this point, we're committed to promoting the alloca using IDF's, and the
873 /// standard SSA construction algorithm.  Determine which blocks need phi nodes
874 /// and see if we can optimize out some work by avoiding insertion of dead phi
875 /// nodes.
876 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
877                                              AllocaInfo &Info) {
878   // Unique the set of defining blocks for efficient lookup.
879   SmallPtrSet<BasicBlock *, 32> DefBlocks;
880   DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
881
882   // Determine which blocks the value is live in.  These are blocks which lead
883   // to uses.
884   SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
885   ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
886
887   // Use a priority queue keyed on dominator tree level so that inserted nodes
888   // are handled from the bottom of the dominator tree upwards.
889   typedef std::priority_queue<DomTreeNodePair,
890                               SmallVector<DomTreeNodePair, 32>,
891                               DomTreeNodeCompare> IDFPriorityQueue;
892   IDFPriorityQueue PQ;
893
894   for (SmallPtrSet<BasicBlock *, 32>::const_iterator I = DefBlocks.begin(),
895                                                      E = DefBlocks.end();
896        I != E; ++I) {
897     if (DomTreeNode *Node = DT.getNode(*I))
898       PQ.push(std::make_pair(Node, DomLevels[Node]));
899   }
900
901   SmallVector<std::pair<unsigned, BasicBlock *>, 32> DFBlocks;
902   SmallPtrSet<DomTreeNode *, 32> Visited;
903   SmallVector<DomTreeNode *, 32> Worklist;
904   while (!PQ.empty()) {
905     DomTreeNodePair RootPair = PQ.top();
906     PQ.pop();
907     DomTreeNode *Root = RootPair.first;
908     unsigned RootLevel = RootPair.second;
909
910     // Walk all dominator tree children of Root, inspecting their CFG edges with
911     // targets elsewhere on the dominator tree. Only targets whose level is at
912     // most Root's level are added to the iterated dominance frontier of the
913     // definition set.
914
915     Worklist.clear();
916     Worklist.push_back(Root);
917
918     while (!Worklist.empty()) {
919       DomTreeNode *Node = Worklist.pop_back_val();
920       BasicBlock *BB = Node->getBlock();
921
922       for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
923            ++SI) {
924         DomTreeNode *SuccNode = DT.getNode(*SI);
925
926         // Quickly skip all CFG edges that are also dominator tree edges instead
927         // of catching them below.
928         if (SuccNode->getIDom() == Node)
929           continue;
930
931         unsigned SuccLevel = DomLevels[SuccNode];
932         if (SuccLevel > RootLevel)
933           continue;
934
935         if (!Visited.insert(SuccNode))
936           continue;
937
938         BasicBlock *SuccBB = SuccNode->getBlock();
939         if (!LiveInBlocks.count(SuccBB))
940           continue;
941
942         DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
943         if (!DefBlocks.count(SuccBB))
944           PQ.push(std::make_pair(SuccNode, SuccLevel));
945       }
946
947       for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
948            ++CI) {
949         if (!Visited.count(*CI))
950           Worklist.push_back(*CI);
951       }
952     }
953   }
954
955   if (DFBlocks.size() > 1)
956     std::sort(DFBlocks.begin(), DFBlocks.end());
957
958   unsigned CurrentVersion = 0;
959   for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
960     QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
961 }
962
963 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
964 ///
965 /// Returns true if there wasn't already a phi-node for that variable
966 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
967                                   unsigned &Version) {
968   // Look up the basic-block in question.
969   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
970
971   // If the BB already has a phi node added for the i'th alloca then we're done!
972   if (PN)
973     return false;
974
975   // Create a PhiNode using the dereferenced type... and add the phi-node to the
976   // BasicBlock.
977   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
978                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
979                        BB->begin());
980   ++NumPHIInsert;
981   PhiToAllocaMap[PN] = AllocaNo;
982
983   if (AST && PN->getType()->isPointerTy())
984     AST->copyValue(PointerAllocaValues[AllocaNo], PN);
985
986   return true;
987 }
988
989 /// \brief Recursively traverse the CFG of the function, renaming loads and
990 /// stores to the allocas which we are promoting.
991 ///
992 /// IncomingVals indicates what value each Alloca contains on exit from the
993 /// predecessor block Pred.
994 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
995                                 RenamePassData::ValVector &IncomingVals,
996                                 std::vector<RenamePassData> &Worklist) {
997 NextIteration:
998   // If we are inserting any phi nodes into this BB, they will already be in the
999   // block.
1000   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1001     // If we have PHI nodes to update, compute the number of edges from Pred to
1002     // BB.
1003     if (PhiToAllocaMap.count(APN)) {
1004       // We want to be able to distinguish between PHI nodes being inserted by
1005       // this invocation of mem2reg from those phi nodes that already existed in
1006       // the IR before mem2reg was run.  We determine that APN is being inserted
1007       // because it is missing incoming edges.  All other PHI nodes being
1008       // inserted by this pass of mem2reg will have the same number of incoming
1009       // operands so far.  Remember this count.
1010       unsigned NewPHINumOperands = APN->getNumOperands();
1011
1012       unsigned NumEdges = 0;
1013       for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
1014         if (*I == BB)
1015           ++NumEdges;
1016       assert(NumEdges && "Must be at least one edge from Pred to BB!");
1017
1018       // Add entries for all the phis.
1019       BasicBlock::iterator PNI = BB->begin();
1020       do {
1021         unsigned AllocaNo = PhiToAllocaMap[APN];
1022
1023         // Add N incoming values to the PHI node.
1024         for (unsigned i = 0; i != NumEdges; ++i)
1025           APN->addIncoming(IncomingVals[AllocaNo], Pred);
1026
1027         // The currently active variable for this block is now the PHI.
1028         IncomingVals[AllocaNo] = APN;
1029
1030         // Get the next phi node.
1031         ++PNI;
1032         APN = dyn_cast<PHINode>(PNI);
1033         if (APN == 0)
1034           break;
1035
1036         // Verify that it is missing entries.  If not, it is not being inserted
1037         // by this mem2reg invocation so we want to ignore it.
1038       } while (APN->getNumOperands() == NewPHINumOperands);
1039     }
1040   }
1041
1042   // Don't revisit blocks.
1043   if (!Visited.insert(BB))
1044     return;
1045
1046   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
1047     Instruction *I = II++; // get the instruction, increment iterator
1048
1049     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1050       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1051       if (!Src)
1052         continue;
1053
1054       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
1055       if (AI == AllocaLookup.end())
1056         continue;
1057
1058       Value *V = IncomingVals[AI->second];
1059
1060       // Anything using the load now uses the current value.
1061       LI->replaceAllUsesWith(V);
1062       if (AST && LI->getType()->isPointerTy())
1063         AST->deleteValue(LI);
1064       BB->getInstList().erase(LI);
1065     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1066       // Delete this instruction and mark the name as the current holder of the
1067       // value
1068       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1069       if (!Dest)
1070         continue;
1071
1072       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1073       if (ai == AllocaLookup.end())
1074         continue;
1075
1076       // what value were we writing?
1077       IncomingVals[ai->second] = SI->getOperand(0);
1078       // Record debuginfo for the store before removing it.
1079       if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
1080         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1081       BB->getInstList().erase(SI);
1082     }
1083   }
1084
1085   // 'Recurse' to our successors.
1086   succ_iterator I = succ_begin(BB), E = succ_end(BB);
1087   if (I == E)
1088     return;
1089
1090   // Keep track of the successors so we don't visit the same successor twice
1091   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1092
1093   // Handle the first successor without using the worklist.
1094   VisitedSuccs.insert(*I);
1095   Pred = BB;
1096   BB = *I;
1097   ++I;
1098
1099   for (; I != E; ++I)
1100     if (VisitedSuccs.insert(*I))
1101       Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
1102
1103   goto NextIteration;
1104 }
1105
1106 void llvm::PromoteMemToReg(const std::vector<AllocaInst *> &Allocas,
1107                            DominatorTree &DT, AliasSetTracker *AST) {
1108   // If there is nothing to do, bail out...
1109   if (Allocas.empty())
1110     return;
1111
1112   PromoteMem2Reg(Allocas, DT, AST).run();
1113 }