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