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