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