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