When inserting PHI nodes, don't insert any phi nodes that are obviously
[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 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/AliasSetTracker.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/StableBasicBlockNumbering.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
34 /// This is true if there are only loads and stores to the alloca.
35 ///
36 bool llvm::isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
37   // FIXME: If the memory unit is of pointer or integer type, we can permit
38   // assignments to subsections of the memory unit.
39
40   // Only allow direct loads and stores...
41   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
42        UI != UE; ++UI)     // Loop over all of the uses of the alloca
43     if (isa<LoadInst>(*UI)) {
44       // noop
45     } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
46       if (SI->getOperand(0) == AI)
47         return false;   // Don't allow a store OF the AI, only INTO the AI.
48     } else {
49       return false;   // Not a load or store.
50     }
51   
52   return true;
53 }
54
55 namespace {
56   struct PromoteMem2Reg {
57     /// Allocas - The alloca instructions being promoted.
58     ///
59     std::vector<AllocaInst*> Allocas;
60     DominatorTree &DT;
61     DominanceFrontier &DF;
62     const TargetData &TD;
63
64     /// AST - An AliasSetTracker object to update.  If null, don't update it.
65     ///
66     AliasSetTracker *AST;
67
68     /// AllocaLookup - Reverse mapping of Allocas.
69     ///
70     std::map<AllocaInst*, unsigned>  AllocaLookup;
71
72     /// NewPhiNodes - The PhiNodes we're adding.
73     ///
74     std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
75
76     /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
77     /// each alloca that is of pointer type, we keep track of what to copyValue
78     /// to the inserted PHI nodes here.
79     ///
80     std::vector<Value*> PointerAllocaValues;
81
82     /// Visited - The set of basic blocks the renamer has already visited.
83     ///
84     std::set<BasicBlock*> Visited;
85
86     /// BBNumbers - Contains a stable numbering of basic blocks to avoid
87     /// non-determinstic behavior.
88     StableBasicBlockNumbering BBNumbers;
89
90   public:
91     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
92                    DominanceFrontier &df, const TargetData &td,
93                    AliasSetTracker *ast)
94       : Allocas(A), DT(dt), DF(df), TD(td), AST(ast) {}
95
96     void run();
97
98     /// dominates - Return true if BB1 dominates BB2 using the DT.
99     ///
100     bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
101       return DT[BB1]->dominates(DT[BB2]);
102     }
103
104   private:
105     void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
106                                std::set<PHINode*> &DeadPHINodes);
107     void PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
108     void PromoteLocallyUsedAllocas(BasicBlock *BB, 
109                                    const std::vector<AllocaInst*> &AIs);
110
111     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
112                     std::vector<Value*> &IncVals);
113     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
114                       std::set<PHINode*> &InsertedPHINodes);
115   };
116 }  // end of anonymous namespace
117
118 void PromoteMem2Reg::run() {
119   Function &F = *DF.getRoot()->getParent();
120
121   // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
122   // only used in a single basic block.  These instructions can be efficiently
123   // promoted by performing a single linear scan over that one block.  Since
124   // individual basic blocks are sometimes large, we group together all allocas
125   // that are live in a single basic block by the basic block they are live in.
126   std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
127
128   if (AST) PointerAllocaValues.resize(Allocas.size());
129
130   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
131     AllocaInst *AI = Allocas[AllocaNum];
132
133     assert(isAllocaPromotable(AI, TD) &&
134            "Cannot promote non-promotable alloca!");
135     assert(AI->getParent()->getParent() == &F &&
136            "All allocas should be in the same function, which is same as DF!");
137
138     if (AI->use_empty()) {
139       // If there are no uses of the alloca, just delete it now.
140       if (AST) AST->deleteValue(AI);
141       AI->getParent()->getInstList().erase(AI);
142
143       // Remove the alloca from the Allocas list, since it has been processed
144       Allocas[AllocaNum] = Allocas.back();
145       Allocas.pop_back();
146       --AllocaNum;
147       continue;
148     }
149
150     // Calculate the set of read and write-locations for each alloca.  This is
151     // analogous to finding the 'uses' and 'definitions' of each variable.
152     std::vector<BasicBlock*> DefiningBlocks;
153     std::vector<BasicBlock*> UsingBlocks;
154
155     BasicBlock *OnlyBlock = 0;
156     bool OnlyUsedInOneBlock = true;
157
158     // As we scan the uses of the alloca instruction, keep track of stores, and
159     // decide whether all of the loads and stores to the alloca are within the
160     // same basic block.
161     Value *AllocaPointerVal = 0;
162     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
163       Instruction *User = cast<Instruction>(*U);
164       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
165         // Remember the basic blocks which define new values for the alloca
166         DefiningBlocks.push_back(SI->getParent());
167         AllocaPointerVal = SI->getOperand(0);
168       } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
169         // Otherwise it must be a load instruction, keep track of variable reads
170         UsingBlocks.push_back(LI->getParent());
171         AllocaPointerVal = LI;
172       }
173
174       if (OnlyUsedInOneBlock) {
175         if (OnlyBlock == 0)
176           OnlyBlock = User->getParent();
177         else if (OnlyBlock != User->getParent())
178           OnlyUsedInOneBlock = false;
179       }
180     }
181
182     // If the alloca is only read and written in one basic block, just perform a
183     // linear sweep over the block to eliminate it.
184     if (OnlyUsedInOneBlock) {
185       LocallyUsedAllocas[OnlyBlock].push_back(AI);
186
187       // Remove the alloca from the Allocas list, since it will be processed.
188       Allocas[AllocaNum] = Allocas.back();
189       Allocas.pop_back();
190       --AllocaNum;
191       continue;
192     }
193
194     if (AST)
195       PointerAllocaValues[AllocaNum] = AllocaPointerVal;
196
197     // If we haven't computed a numbering for the BB's in the function, do so
198     // now.
199     BBNumbers.compute(F);
200
201     // Compute the locations where PhiNodes need to be inserted.  Look at the
202     // dominance frontier of EACH basic-block we have a write in.
203     //
204     unsigned CurrentVersion = 0;
205     std::set<PHINode*> InsertedPHINodes;
206     std::vector<unsigned> DFBlocks;
207     while (!DefiningBlocks.empty()) {
208       BasicBlock *BB = DefiningBlocks.back();
209       DefiningBlocks.pop_back();
210
211       // Look up the DF for this write, add it to PhiNodes
212       DominanceFrontier::const_iterator it = DF.find(BB);
213       if (it != DF.end()) {
214         const DominanceFrontier::DomSetType &S = it->second;
215
216         // In theory we don't need the indirection through the DFBlocks vector.
217         // In practice, the order of calling QueuePhiNode would depend on the
218         // (unspecified) ordering of basic blocks in the dominance frontier,
219         // which would give PHI nodes non-determinstic subscripts.  Fix this by
220         // processing blocks in order of the occurance in the function.
221         for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
222              P != PE; ++P)
223           DFBlocks.push_back(BBNumbers.getNumber(*P));
224
225         // Sort by which the block ordering in the function.
226         std::sort(DFBlocks.begin(), DFBlocks.end());
227
228         for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
229           BasicBlock *BB = BBNumbers.getBlock(DFBlocks[i]);
230           if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
231             DefiningBlocks.push_back(BB);
232         }
233         DFBlocks.clear();
234       }
235     }
236
237     // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
238     // of the writes to the variable, scan through the reads of the variable,
239     // marking PHI nodes which are actually necessary as alive (by removing them
240     // from the InsertedPHINodes set).  This is not perfect: there may PHI
241     // marked alive because of loads which are dominated by stores, but there
242     // will be no unmarked PHI nodes which are actually used.
243     //
244     for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
245       MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
246     UsingBlocks.clear();
247
248     // If there are any PHI nodes which are now known to be dead, remove them!
249     for (std::set<PHINode*>::iterator I = InsertedPHINodes.begin(),
250            E = InsertedPHINodes.end(); I != E; ++I) {
251       PHINode *PN = *I;
252       std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
253       BBPNs[AllocaNum] = 0;
254
255       // Check to see if we just removed the last inserted PHI node from this
256       // basic block.  If so, remove the entry for the basic block.
257       bool HasOtherPHIs = false;
258       for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
259         if (BBPNs[i]) {
260           HasOtherPHIs = true;
261           break;
262         }
263       if (!HasOtherPHIs)
264         NewPhiNodes.erase(PN->getParent());
265
266       if (AST && isa<PointerType>(PN->getType()))
267         AST->deleteValue(PN);
268       PN->getParent()->getInstList().erase(PN);      
269     }
270
271     // Keep the reverse mapping of the 'Allocas' array. 
272     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
273   }
274   
275   // Process all allocas which are only used in a single basic block.
276   for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
277          LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
278     const std::vector<AllocaInst*> &Allocas = I->second;
279     assert(!Allocas.empty() && "empty alloca list??");
280
281     // It's common for there to only be one alloca in the list.  Handle it
282     // efficiently.
283     if (Allocas.size() == 1)
284       PromoteLocallyUsedAlloca(I->first, Allocas[0]);
285     else
286       PromoteLocallyUsedAllocas(I->first, Allocas);
287   }
288
289   if (Allocas.empty())
290     return; // All of the allocas must have been trivial!
291
292   // Set the incoming values for the basic block to be null values for all of
293   // the alloca's.  We do this in case there is a load of a value that has not
294   // been stored yet.  In this case, it will get this null value.
295   //
296   std::vector<Value *> Values(Allocas.size());
297   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
298     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
299
300   // Walks all basic blocks in the function performing the SSA rename algorithm
301   // and inserting the phi nodes we marked as necessary
302   //
303   RenamePass(F.begin(), 0, Values);
304
305   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
306   Visited.clear();
307
308   // Remove the allocas themselves from the function...
309   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
310     Instruction *A = Allocas[i];
311
312     // If there are any uses of the alloca instructions left, they must be in
313     // sections of dead code that were not processed on the dominance frontier.
314     // Just delete the users now.
315     //
316     if (!A->use_empty())
317       A->replaceAllUsesWith(UndefValue::get(A->getType()));
318     if (AST) AST->deleteValue(A);
319     A->getParent()->getInstList().erase(A);
320   }
321
322   // At this point, the renamer has added entries to PHI nodes for all reachable
323   // code.  Unfortunately, there may be blocks which are not reachable, which
324   // the renamer hasn't traversed.  If this is the case, the PHI nodes may not
325   // have incoming values for all predecessors.  Loop over all PHI nodes we have
326   // created, inserting undef values if they are missing any incoming values.
327   //
328   for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I = 
329          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
330
331     std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
332     std::vector<PHINode*> &PNs = I->second;
333     assert(!PNs.empty() && "Empty PHI node list??");
334
335     // Loop over all of the PHI nodes and see if there are any that we can get
336     // rid of because they merge all of the same incoming values.  This can
337     // happen due to undef values coming into the PHI nodes.
338     PHINode *SomePHI = 0;
339     for (unsigned i = 0, e = PNs.size(); i != e; ++i)
340       if (PNs[i]) {
341         if (Value *V = hasConstantValue(PNs[i])) {
342           if (!isa<Instruction>(V) ||
343               dominates(cast<Instruction>(V)->getParent(), I->first)) {
344             PNs[i]->replaceAllUsesWith(V);
345             PNs[i]->eraseFromParent();
346             PNs[i] = 0;
347           }
348         }
349         if (PNs[i])
350           SomePHI = PNs[i];
351       }
352
353     // Only do work here if there the PHI nodes are missing incoming values.  We
354     // know that all PHI nodes that were inserted in a block will have the same
355     // number of incoming values, so we can just check any PHI node.
356     if (SomePHI && Preds.size() != SomePHI->getNumIncomingValues()) {
357       // Ok, now we know that all of the PHI nodes are missing entries for some
358       // basic blocks.  Start by sorting the incoming predecessors for efficient
359       // access.
360       std::sort(Preds.begin(), Preds.end());
361
362       // Now we loop through all BB's which have entries in SomePHI and remove
363       // them from the Preds list.
364       for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
365         // Do a log(n) search of the Preds list for the entry we want.
366         std::vector<BasicBlock*>::iterator EntIt =
367           std::lower_bound(Preds.begin(), Preds.end(),
368                            SomePHI->getIncomingBlock(i));
369         assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
370                "PHI node has entry for a block which is not a predecessor!");
371
372         // Remove the entry
373         Preds.erase(EntIt);
374       }
375
376       // At this point, the blocks left in the preds list must have dummy
377       // entries inserted into every PHI nodes for the block.
378       for (unsigned i = 0, e = PNs.size(); i != e; ++i)
379         if (PHINode *PN = PNs[i]) {
380           Value *UndefVal = UndefValue::get(PN->getType());
381           for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
382             PN->addIncoming(UndefVal, Preds[pred]);
383         }
384     }
385   }
386 }
387
388 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
389 // "minimal" SSA form.  To do this, it inserts all of the PHI nodes on the IDF
390 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
391 // each read of the variable.  For each block that reads the variable, this
392 // function is called, which removes used PHI nodes from the DeadPHINodes set.
393 // After all of the reads have been processed, any PHI nodes left in the
394 // DeadPHINodes set are removed.
395 //
396 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
397                                            std::set<PHINode*> &DeadPHINodes) {
398   // Scan the immediate dominators of this block looking for a block which has a
399   // PHI node for Alloca num.  If we find it, mark the PHI node as being alive!
400   for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
401     BasicBlock *DomBB = N->getBlock();
402     std::map<BasicBlock*, std::vector<PHINode*> >::iterator
403       I = NewPhiNodes.find(DomBB);
404     if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
405       // Ok, we found an inserted PHI node which dominates this value.
406       PHINode *DominatingPHI = I->second[AllocaNum];
407
408       // Find out if we previously thought it was dead.
409       std::set<PHINode*>::iterator DPNI = DeadPHINodes.find(DominatingPHI);
410       if (DPNI != DeadPHINodes.end()) {
411         // Ok, until now, we thought this PHI node was dead.  Mark it as being
412         // alive/needed.
413         DeadPHINodes.erase(DPNI);
414
415         // Now that we have marked the PHI node alive, also mark any PHI nodes
416         // which it might use as being alive as well.
417         for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
418              PI != PE; ++PI)
419           MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
420       }
421     }
422   }
423 }
424
425 /// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
426 /// block.  If this is the case, avoid traversing the CFG and inserting a lot of
427 /// potentially useless PHI nodes by just performing a single linear pass over
428 /// the basic block using the Alloca.
429 ///
430 void PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
431   assert(!AI->use_empty() && "There are no uses of the alloca!");
432
433   // Handle degenerate cases quickly.
434   if (AI->hasOneUse()) {
435     Instruction *U = cast<Instruction>(AI->use_back());
436     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
437       // Must be a load of uninitialized value.
438       LI->replaceAllUsesWith(UndefValue::get(AI->getAllocatedType()));
439       if (AST && isa<PointerType>(LI->getType()))
440         AST->deleteValue(LI);
441     } else {
442       // Otherwise it must be a store which is never read.
443       assert(isa<StoreInst>(U));
444     }
445     BB->getInstList().erase(U);
446   } else {
447     // Uses of the uninitialized memory location shall get undef.
448     Value *CurVal = UndefValue::get(AI->getAllocatedType());
449   
450     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
451       Instruction *Inst = I++;
452       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
453         if (LI->getOperand(0) == AI) {
454           // Loads just returns the "current value"...
455           LI->replaceAllUsesWith(CurVal);
456           if (AST && isa<PointerType>(LI->getType()))
457             AST->deleteValue(LI);
458           BB->getInstList().erase(LI);
459         }
460       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
461         if (SI->getOperand(1) == AI) {
462           // Store updates the "current value"...
463           CurVal = SI->getOperand(0);
464           BB->getInstList().erase(SI);
465         }
466       }
467     }
468   }
469
470   // After traversing the basic block, there should be no more uses of the
471   // alloca, remove it now.
472   assert(AI->use_empty() && "Uses of alloca from more than one BB??");
473   if (AST) AST->deleteValue(AI);
474   AI->getParent()->getInstList().erase(AI);
475 }
476
477 /// PromoteLocallyUsedAllocas - This method is just like
478 /// PromoteLocallyUsedAlloca, except that it processes multiple alloca
479 /// instructions in parallel.  This is important in cases where we have large
480 /// basic blocks, as we don't want to rescan the entire basic block for each
481 /// alloca which is locally used in it (which might be a lot).
482 void PromoteMem2Reg::
483 PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
484   std::map<AllocaInst*, Value*> CurValues;
485   for (unsigned i = 0, e = AIs.size(); i != e; ++i)
486     CurValues[AIs[i]] = 0; // Insert with null value
487
488   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
489     Instruction *Inst = I++;
490     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
491       // Is this a load of an alloca we are tracking?
492       if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
493         std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
494         if (AIt != CurValues.end()) {
495           // Loads just returns the "current value"...
496           if (AIt->second == 0)   // Uninitialized value??
497             AIt->second = UndefValue::get(AIt->first->getAllocatedType());
498           LI->replaceAllUsesWith(AIt->second);
499           if (AST && isa<PointerType>(LI->getType()))
500             AST->deleteValue(LI);
501           BB->getInstList().erase(LI);
502         }
503       }
504     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
505       if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
506         std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
507         if (AIt != CurValues.end()) {
508           // Store updates the "current value"...
509           AIt->second = SI->getOperand(0);
510           BB->getInstList().erase(SI);
511         }
512       }
513     }
514   }
515 }
516
517
518
519 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
520 // Alloca returns true if there wasn't already a phi-node for that variable
521 //
522 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
523                                   unsigned &Version,
524                                   std::set<PHINode*> &InsertedPHINodes) {
525   // Look up the basic-block in question.
526   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
527   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
528
529   // If the BB already has a phi node added for the i'th alloca then we're done!
530   if (BBPNs[AllocaNo]) return false;
531
532   // Create a PhiNode using the dereferenced type... and add the phi-node to the
533   // BasicBlock.
534   PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
535                             Allocas[AllocaNo]->getName() + "." +
536                                         utostr(Version++), BB->begin());
537   BBPNs[AllocaNo] = PN;
538   InsertedPHINodes.insert(PN);
539
540   if (AST && isa<PointerType>(PN->getType()))
541     AST->copyValue(PointerAllocaValues[AllocaNo], PN);
542
543   return true;
544 }
545
546
547 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
548 // stores to the allocas which we are promoting.  IncomingVals indicates what
549 // value each Alloca contains on exit from the predecessor block Pred.
550 //
551 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
552                                 std::vector<Value*> &IncomingVals) {
553
554   // If this BB needs a PHI node, update the PHI node for each variable we need
555   // PHI nodes for.
556   std::map<BasicBlock*, std::vector<PHINode *> >::iterator
557     BBPNI = NewPhiNodes.find(BB);
558   if (BBPNI != NewPhiNodes.end()) {
559     std::vector<PHINode *> &BBPNs = BBPNI->second;
560     for (unsigned k = 0; k != BBPNs.size(); ++k)
561       if (PHINode *PN = BBPNs[k]) {
562         // Add this incoming value to the PHI node.
563         PN->addIncoming(IncomingVals[k], Pred);
564
565         // The currently active variable for this block is now the PHI.
566         IncomingVals[k] = PN;
567       }
568   }
569
570   // don't revisit nodes
571   if (Visited.count(BB)) return;
572   
573   // mark as visited
574   Visited.insert(BB);
575
576   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
577     Instruction *I = II++; // get the instruction, increment iterator
578
579     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
580       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
581         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
582         if (AI != AllocaLookup.end()) {
583           Value *V = IncomingVals[AI->second];
584
585           // walk the use list of this load and replace all uses with r
586           LI->replaceAllUsesWith(V);
587           if (AST && isa<PointerType>(LI->getType()))
588             AST->deleteValue(LI);
589           BB->getInstList().erase(LI);
590         }
591       }
592     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
593       // Delete this instruction and mark the name as the current holder of the
594       // value
595       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
596         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
597         if (ai != AllocaLookup.end()) {
598           // what value were we writing?
599           IncomingVals[ai->second] = SI->getOperand(0);
600           BB->getInstList().erase(SI);
601         }
602       }
603     }
604   }
605
606   // Recurse to our successors.
607   TerminatorInst *TI = BB->getTerminator();
608   for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
609     std::vector<Value*> OutgoingVals(IncomingVals);
610     RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
611   }
612 }
613
614 /// PromoteMemToReg - Promote the specified list of alloca instructions into
615 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
616 /// use of DominanceFrontier information.  This function does not modify the CFG
617 /// of the function at all.  All allocas must be from the same function.
618 ///
619 /// If AST is specified, the specified tracker is updated to reflect changes
620 /// made to the IR.
621 ///
622 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
623                            DominatorTree &DT, DominanceFrontier &DF,
624                            const TargetData &TD, AliasSetTracker *AST) {
625   // If there is nothing to do, bail out...
626   if (Allocas.empty()) return;
627   PromoteMem2Reg(Allocas, DT, DF, TD, AST).run();
628 }