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