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