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