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