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