1193323Sed//===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file promotes memory references to be register references.  It promotes
11193323Sed// alloca instructions which only have loads and stores as uses.  An alloca is
12218893Sdim// transformed by using iterated dominator frontiers to place PHI nodes, then
13218893Sdim// traversing the function in depth-first order to rewrite loads and stores as
14218893Sdim// appropriate.
15193323Sed//
16218893Sdim// The algorithm used here is based on:
17218893Sdim//
18218893Sdim//   Sreedhar and Gao. A linear time algorithm for placing phi-nodes.
19218893Sdim//   In Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of
20218893Sdim//   Programming Languages
21218893Sdim//   POPL '95. ACM, New York, NY, 62-73.
22218893Sdim//
23218893Sdim// It has been modified to not explicitly use the DJ graph data structure and to
24218893Sdim// directly compute pruned SSA using per-variable liveness information.
25218893Sdim//
26193323Sed//===----------------------------------------------------------------------===//
27193323Sed
28193323Sed#define DEBUG_TYPE "mem2reg"
29193323Sed#include "llvm/Transforms/Utils/PromoteMemToReg.h"
30263508Sdim#include "llvm/ADT/ArrayRef.h"
31193323Sed#include "llvm/ADT/DenseMap.h"
32249423Sdim#include "llvm/ADT/STLExtras.h"
33193323Sed#include "llvm/ADT/SmallPtrSet.h"
34193323Sed#include "llvm/ADT/SmallVector.h"
35193323Sed#include "llvm/ADT/Statistic.h"
36249423Sdim#include "llvm/Analysis/AliasSetTracker.h"
37249423Sdim#include "llvm/Analysis/Dominators.h"
38249423Sdim#include "llvm/Analysis/InstructionSimplify.h"
39249423Sdim#include "llvm/Analysis/ValueTracking.h"
40249423Sdim#include "llvm/DIBuilder.h"
41249423Sdim#include "llvm/DebugInfo.h"
42249423Sdim#include "llvm/IR/Constants.h"
43249423Sdim#include "llvm/IR/DerivedTypes.h"
44249423Sdim#include "llvm/IR/Function.h"
45249423Sdim#include "llvm/IR/Instructions.h"
46249423Sdim#include "llvm/IR/IntrinsicInst.h"
47249423Sdim#include "llvm/IR/Metadata.h"
48193323Sed#include "llvm/Support/CFG.h"
49249423Sdim#include "llvm/Transforms/Utils/Local.h"
50193323Sed#include <algorithm>
51218893Sdim#include <queue>
52193323Sedusing namespace llvm;
53193323Sed
54193323SedSTATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
55193323SedSTATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
56193323SedSTATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
57193323SedSTATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
58193323Sed
59193323Sedbool llvm::isAllocaPromotable(const AllocaInst *AI) {
60193323Sed  // FIXME: If the memory unit is of pointer or integer type, we can permit
61193323Sed  // assignments to subsections of the memory unit.
62193323Sed
63193323Sed  // Only allow direct and non-volatile loads and stores...
64206083Srdivacky  for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
65263508Sdim       UI != UE; ++UI) { // Loop over all of the uses of the alloca
66210299Sed    const User *U = *UI;
67210299Sed    if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
68226633Sdim      // Note that atomic loads can be transformed; atomic semantics do
69226633Sdim      // not have any meaning for a local alloca.
70193323Sed      if (LI->isVolatile())
71193323Sed        return false;
72210299Sed    } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
73193323Sed      if (SI->getOperand(0) == AI)
74263508Sdim        return false; // Don't allow a store OF the AI, only INTO the AI.
75226633Sdim      // Note that atomic stores can be transformed; atomic semantics do
76226633Sdim      // not have any meaning for a local alloca.
77193323Sed      if (SI->isVolatile())
78193323Sed        return false;
79224145Sdim    } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
80224145Sdim      if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
81224145Sdim          II->getIntrinsicID() != Intrinsic::lifetime_end)
82224145Sdim        return false;
83224145Sdim    } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
84224145Sdim      if (BCI->getType() != Type::getInt8PtrTy(U->getContext()))
85224145Sdim        return false;
86224145Sdim      if (!onlyUsedByLifetimeMarkers(BCI))
87224145Sdim        return false;
88224145Sdim    } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
89224145Sdim      if (GEPI->getType() != Type::getInt8PtrTy(U->getContext()))
90224145Sdim        return false;
91224145Sdim      if (!GEPI->hasAllZeroIndices())
92224145Sdim        return false;
93224145Sdim      if (!onlyUsedByLifetimeMarkers(GEPI))
94224145Sdim        return false;
95193323Sed    } else {
96193323Sed      return false;
97193323Sed    }
98210299Sed  }
99193323Sed
100193323Sed  return true;
101193323Sed}
102193323Sed
103193323Sednamespace {
104193323Sed
105263508Sdimstruct AllocaInfo {
106263508Sdim  SmallVector<BasicBlock *, 32> DefiningBlocks;
107263508Sdim  SmallVector<BasicBlock *, 32> UsingBlocks;
108263508Sdim
109263508Sdim  StoreInst *OnlyStore;
110263508Sdim  BasicBlock *OnlyBlock;
111263508Sdim  bool OnlyUsedInOneBlock;
112263508Sdim
113263508Sdim  Value *AllocaPointerVal;
114263508Sdim  DbgDeclareInst *DbgDeclare;
115263508Sdim
116263508Sdim  void clear() {
117263508Sdim    DefiningBlocks.clear();
118263508Sdim    UsingBlocks.clear();
119263508Sdim    OnlyStore = 0;
120263508Sdim    OnlyBlock = 0;
121263508Sdim    OnlyUsedInOneBlock = true;
122263508Sdim    AllocaPointerVal = 0;
123263508Sdim    DbgDeclare = 0;
124263508Sdim  }
125263508Sdim
126263508Sdim  /// Scan the uses of the specified alloca, filling in the AllocaInfo used
127263508Sdim  /// by the rest of the pass to reason about the uses of this alloca.
128263508Sdim  void AnalyzeAlloca(AllocaInst *AI) {
129263508Sdim    clear();
130263508Sdim
131263508Sdim    // As we scan the uses of the alloca instruction, keep track of stores,
132263508Sdim    // and decide whether all of the loads and stores to the alloca are within
133263508Sdim    // the same basic block.
134263508Sdim    for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
135263508Sdim         UI != E;) {
136263508Sdim      Instruction *User = cast<Instruction>(*UI++);
137263508Sdim
138263508Sdim      if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
139263508Sdim        // Remember the basic blocks which define new values for the alloca
140263508Sdim        DefiningBlocks.push_back(SI->getParent());
141263508Sdim        AllocaPointerVal = SI->getOperand(0);
142263508Sdim        OnlyStore = SI;
143263508Sdim      } else {
144263508Sdim        LoadInst *LI = cast<LoadInst>(User);
145263508Sdim        // Otherwise it must be a load instruction, keep track of variable
146263508Sdim        // reads.
147263508Sdim        UsingBlocks.push_back(LI->getParent());
148263508Sdim        AllocaPointerVal = LI;
149263508Sdim      }
150263508Sdim
151263508Sdim      if (OnlyUsedInOneBlock) {
152263508Sdim        if (OnlyBlock == 0)
153263508Sdim          OnlyBlock = User->getParent();
154263508Sdim        else if (OnlyBlock != User->getParent())
155263508Sdim          OnlyUsedInOneBlock = false;
156263508Sdim      }
157193323Sed    }
158263508Sdim
159263508Sdim    DbgDeclare = FindAllocaDbgDeclare(AI);
160263508Sdim  }
161263508Sdim};
162263508Sdim
163263508Sdim// Data package used by RenamePass()
164263508Sdimclass RenamePassData {
165263508Sdimpublic:
166263508Sdim  typedef std::vector<Value *> ValVector;
167263508Sdim
168263508Sdim  RenamePassData() : BB(NULL), Pred(NULL), Values() {}
169263508Sdim  RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
170263508Sdim      : BB(B), Pred(P), Values(V) {}
171263508Sdim  BasicBlock *BB;
172263508Sdim  BasicBlock *Pred;
173263508Sdim  ValVector Values;
174263508Sdim
175263508Sdim  void swap(RenamePassData &RHS) {
176263508Sdim    std::swap(BB, RHS.BB);
177263508Sdim    std::swap(Pred, RHS.Pred);
178263508Sdim    Values.swap(RHS.Values);
179263508Sdim  }
180263508Sdim};
181263508Sdim
182263508Sdim/// \brief This assigns and keeps a per-bb relative ordering of load/store
183263508Sdim/// instructions in the block that directly load or store an alloca.
184263508Sdim///
185263508Sdim/// This functionality is important because it avoids scanning large basic
186263508Sdim/// blocks multiple times when promoting many allocas in the same block.
187263508Sdimclass LargeBlockInfo {
188263508Sdim  /// \brief For each instruction that we track, keep the index of the
189263508Sdim  /// instruction.
190193323Sed  ///
191263508Sdim  /// The index starts out as the number of the instruction from the start of
192263508Sdim  /// the block.
193263508Sdim  DenseMap<const Instruction *, unsigned> InstNumbers;
194263508Sdim
195263508Sdimpublic:
196263508Sdim
197263508Sdim  /// This code only looks at accesses to allocas.
198263508Sdim  static bool isInterestingInstruction(const Instruction *I) {
199263508Sdim    return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
200263508Sdim           (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
201263508Sdim  }
202263508Sdim
203263508Sdim  /// Get or calculate the index of the specified instruction.
204263508Sdim  unsigned getInstructionIndex(const Instruction *I) {
205263508Sdim    assert(isInterestingInstruction(I) &&
206263508Sdim           "Not a load/store to/from an alloca?");
207263508Sdim
208263508Sdim    // If we already have this instruction number, return it.
209263508Sdim    DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
210263508Sdim    if (It != InstNumbers.end())
211193323Sed      return It->second;
212193323Sed
213263508Sdim    // Scan the whole block to get the instruction.  This accumulates
214263508Sdim    // information for every interesting instruction in the block, in order to
215263508Sdim    // avoid gratuitus rescans.
216263508Sdim    const BasicBlock *BB = I->getParent();
217263508Sdim    unsigned InstNo = 0;
218263508Sdim    for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
219263508Sdim         ++BBI)
220263508Sdim      if (isInterestingInstruction(BBI))
221263508Sdim        InstNumbers[BBI] = InstNo++;
222263508Sdim    It = InstNumbers.find(I);
223193323Sed
224263508Sdim    assert(It != InstNumbers.end() && "Didn't insert instruction?");
225263508Sdim    return It->second;
226263508Sdim  }
227193323Sed
228263508Sdim  void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
229193323Sed
230263508Sdim  void clear() { InstNumbers.clear(); }
231263508Sdim};
232203954Srdivacky
233263508Sdimstruct PromoteMem2Reg {
234263508Sdim  /// The alloca instructions being promoted.
235263508Sdim  std::vector<AllocaInst *> Allocas;
236263508Sdim  DominatorTree &DT;
237263508Sdim  DIBuilder DIB;
238193323Sed
239263508Sdim  /// An AliasSetTracker object to update.  If null, don't update it.
240263508Sdim  AliasSetTracker *AST;
241193323Sed
242263508Sdim  /// Reverse mapping of Allocas.
243263508Sdim  DenseMap<AllocaInst *, unsigned> AllocaLookup;
244218893Sdim
245263508Sdim  /// \brief The PhiNodes we're adding.
246263508Sdim  ///
247263508Sdim  /// That map is used to simplify some Phi nodes as we iterate over it, so
248263508Sdim  /// it should have deterministic iterators.  We could use a MapVector, but
249263508Sdim  /// since we already maintain a map from BasicBlock* to a stable numbering
250263508Sdim  /// (BBNumbers), the DenseMap is more efficient (also supports removal).
251263508Sdim  DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
252193323Sed
253263508Sdim  /// For each PHI node, keep track of which entry in Allocas it corresponds
254263508Sdim  /// to.
255263508Sdim  DenseMap<PHINode *, unsigned> PhiToAllocaMap;
256193323Sed
257263508Sdim  /// If we are updating an AliasSetTracker, then for each alloca that is of
258263508Sdim  /// pointer type, we keep track of what to copyValue to the inserted PHI
259263508Sdim  /// nodes here.
260263508Sdim  std::vector<Value *> PointerAllocaValues;
261193323Sed
262263508Sdim  /// For each alloca, we keep track of the dbg.declare intrinsic that
263263508Sdim  /// describes it, if any, so that we can convert it to a dbg.value
264263508Sdim  /// intrinsic if the alloca gets promoted.
265263508Sdim  SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
266193323Sed
267263508Sdim  /// The set of basic blocks the renamer has already visited.
268263508Sdim  ///
269263508Sdim  SmallPtrSet<BasicBlock *, 16> Visited;
270193323Sed
271263508Sdim  /// Contains a stable numbering of basic blocks to avoid non-determinstic
272263508Sdim  /// behavior.
273263508Sdim  DenseMap<BasicBlock *, unsigned> BBNumbers;
274193323Sed
275263508Sdim  /// Maps DomTreeNodes to their level in the dominator tree.
276263508Sdim  DenseMap<DomTreeNode *, unsigned> DomLevels;
277202878Srdivacky
278263508Sdim  /// Lazily compute the number of predecessors a block has.
279263508Sdim  DenseMap<const BasicBlock *, unsigned> BBNumPreds;
280218893Sdim
281263508Sdimpublic:
282263508Sdim  PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
283263508Sdim                 AliasSetTracker *AST)
284263508Sdim      : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
285263508Sdim        DIB(*DT.getRoot()->getParent()->getParent()), AST(AST) {}
286218893Sdim
287263508Sdim  void run();
288193323Sed
289263508Sdimprivate:
290263508Sdim  void RemoveFromAllocasList(unsigned &AllocaIdx) {
291263508Sdim    Allocas[AllocaIdx] = Allocas.back();
292263508Sdim    Allocas.pop_back();
293263508Sdim    --AllocaIdx;
294263508Sdim  }
295263508Sdim
296263508Sdim  unsigned getNumPreds(const BasicBlock *BB) {
297263508Sdim    unsigned &NP = BBNumPreds[BB];
298263508Sdim    if (NP == 0)
299263508Sdim      NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
300263508Sdim    return NP - 1;
301263508Sdim  }
302263508Sdim
303263508Sdim  void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
304263508Sdim                               AllocaInfo &Info);
305263508Sdim  void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
306263508Sdim                           const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
307263508Sdim                           SmallPtrSet<BasicBlock *, 32> &LiveInBlocks);
308263508Sdim  void RenamePass(BasicBlock *BB, BasicBlock *Pred,
309263508Sdim                  RenamePassData::ValVector &IncVals,
310263508Sdim                  std::vector<RenamePassData> &Worklist);
311263508Sdim  bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
312263508Sdim};
313263508Sdim
314263508Sdim} // end of anonymous namespace
315263508Sdim
316224145Sdimstatic void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
317224145Sdim  // Knowing that this alloca is promotable, we know that it's safe to kill all
318224145Sdim  // instructions except for load and store.
319193323Sed
320224145Sdim  for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
321224145Sdim       UI != UE;) {
322224145Sdim    Instruction *I = cast<Instruction>(*UI);
323224145Sdim    ++UI;
324224145Sdim    if (isa<LoadInst>(I) || isa<StoreInst>(I))
325224145Sdim      continue;
326224145Sdim
327224145Sdim    if (!I->getType()->isVoidTy()) {
328224145Sdim      // The only users of this bitcast/GEP instruction are lifetime intrinsics.
329224145Sdim      // Follow the use/def chain to erase them now instead of leaving it for
330224145Sdim      // dead code elimination later.
331224145Sdim      for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
332224145Sdim           UI != UE;) {
333224145Sdim        Instruction *Inst = cast<Instruction>(*UI);
334224145Sdim        ++UI;
335224145Sdim        Inst->eraseFromParent();
336224145Sdim      }
337224145Sdim    }
338224145Sdim    I->eraseFromParent();
339224145Sdim  }
340224145Sdim}
341224145Sdim
342263508Sdim/// \brief Rewrite as many loads as possible given a single store.
343263508Sdim///
344263508Sdim/// When there is only a single store, we can use the domtree to trivially
345263508Sdim/// replace all of the dominated loads with the stored value. Do so, and return
346263508Sdim/// true if this has successfully promoted the alloca entirely. If this returns
347263508Sdim/// false there were some loads which were not dominated by the single store
348263508Sdim/// and thus must be phi-ed with undef. We fall back to the standard alloca
349263508Sdim/// promotion algorithm in that case.
350263508Sdimstatic bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
351263508Sdim                                     LargeBlockInfo &LBI,
352263508Sdim                                     DominatorTree &DT,
353263508Sdim                                     AliasSetTracker *AST) {
354263508Sdim  StoreInst *OnlyStore = Info.OnlyStore;
355263508Sdim  bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
356263508Sdim  BasicBlock *StoreBB = OnlyStore->getParent();
357263508Sdim  int StoreIndex = -1;
358263508Sdim
359263508Sdim  // Clear out UsingBlocks.  We will reconstruct it here if needed.
360263508Sdim  Info.UsingBlocks.clear();
361263508Sdim
362263508Sdim  for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
363263508Sdim    Instruction *UserInst = cast<Instruction>(*UI++);
364263508Sdim    if (!isa<LoadInst>(UserInst)) {
365263508Sdim      assert(UserInst == OnlyStore && "Should only have load/stores");
366263508Sdim      continue;
367263508Sdim    }
368263508Sdim    LoadInst *LI = cast<LoadInst>(UserInst);
369263508Sdim
370263508Sdim    // Okay, if we have a load from the alloca, we want to replace it with the
371263508Sdim    // only value stored to the alloca.  We can do this if the value is
372263508Sdim    // dominated by the store.  If not, we use the rest of the mem2reg machinery
373263508Sdim    // to insert the phi nodes as needed.
374263508Sdim    if (!StoringGlobalVal) { // Non-instructions are always dominated.
375263508Sdim      if (LI->getParent() == StoreBB) {
376263508Sdim        // If we have a use that is in the same block as the store, compare the
377263508Sdim        // indices of the two instructions to see which one came first.  If the
378263508Sdim        // load came before the store, we can't handle it.
379263508Sdim        if (StoreIndex == -1)
380263508Sdim          StoreIndex = LBI.getInstructionIndex(OnlyStore);
381263508Sdim
382263508Sdim        if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
383263508Sdim          // Can't handle this load, bail out.
384263508Sdim          Info.UsingBlocks.push_back(StoreBB);
385263508Sdim          continue;
386263508Sdim        }
387263508Sdim
388263508Sdim      } else if (LI->getParent() != StoreBB &&
389263508Sdim                 !DT.dominates(StoreBB, LI->getParent())) {
390263508Sdim        // If the load and store are in different blocks, use BB dominance to
391263508Sdim        // check their relationships.  If the store doesn't dom the use, bail
392263508Sdim        // out.
393263508Sdim        Info.UsingBlocks.push_back(LI->getParent());
394263508Sdim        continue;
395263508Sdim      }
396263508Sdim    }
397263508Sdim
398263508Sdim    // Otherwise, we *can* safely rewrite this load.
399263508Sdim    Value *ReplVal = OnlyStore->getOperand(0);
400263508Sdim    // If the replacement value is the load, this must occur in unreachable
401263508Sdim    // code.
402263508Sdim    if (ReplVal == LI)
403263508Sdim      ReplVal = UndefValue::get(LI->getType());
404263508Sdim    LI->replaceAllUsesWith(ReplVal);
405263508Sdim    if (AST && LI->getType()->isPointerTy())
406263508Sdim      AST->deleteValue(LI);
407263508Sdim    LI->eraseFromParent();
408263508Sdim    LBI.deleteValue(LI);
409263508Sdim  }
410263508Sdim
411263508Sdim  // Finally, after the scan, check to see if the store is all that is left.
412263508Sdim  if (!Info.UsingBlocks.empty())
413263508Sdim    return false; // If not, we'll have to fall back for the remainder.
414263508Sdim
415263508Sdim  // Record debuginfo for the store and remove the declaration's
416263508Sdim  // debuginfo.
417263508Sdim  if (DbgDeclareInst *DDI = Info.DbgDeclare) {
418263508Sdim    DIBuilder DIB(*AI->getParent()->getParent()->getParent());
419263508Sdim    ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
420263508Sdim    DDI->eraseFromParent();
421263508Sdim    LBI.deleteValue(DDI);
422263508Sdim  }
423263508Sdim  // Remove the (now dead) store and alloca.
424263508Sdim  Info.OnlyStore->eraseFromParent();
425263508Sdim  LBI.deleteValue(Info.OnlyStore);
426263508Sdim
427263508Sdim  if (AST)
428263508Sdim    AST->deleteValue(AI);
429263508Sdim  AI->eraseFromParent();
430263508Sdim  LBI.deleteValue(AI);
431263508Sdim  return true;
432263508Sdim}
433263508Sdim
434263508Sdim/// Many allocas are only used within a single basic block.  If this is the
435263508Sdim/// case, avoid traversing the CFG and inserting a lot of potentially useless
436263508Sdim/// PHI nodes by just performing a single linear pass over the basic block
437263508Sdim/// using the Alloca.
438263508Sdim///
439263508Sdim/// If we cannot promote this alloca (because it is read before it is written),
440263508Sdim/// return true.  This is necessary in cases where, due to control flow, the
441263508Sdim/// alloca is potentially undefined on some control flow paths.  e.g. code like
442263508Sdim/// this is potentially correct:
443263508Sdim///
444263508Sdim///   for (...) { if (c) { A = undef; undef = B; } }
445263508Sdim///
446263508Sdim/// ... so long as A is not used before undef is set.
447263508Sdimstatic void promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
448263508Sdim                                     LargeBlockInfo &LBI,
449263508Sdim                                     AliasSetTracker *AST) {
450263508Sdim  // The trickiest case to handle is when we have large blocks. Because of this,
451263508Sdim  // this code is optimized assuming that large blocks happen.  This does not
452263508Sdim  // significantly pessimize the small block case.  This uses LargeBlockInfo to
453263508Sdim  // make it efficient to get the index of various operations in the block.
454263508Sdim
455263508Sdim  // Walk the use-def list of the alloca, getting the locations of all stores.
456263508Sdim  typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
457263508Sdim  StoresByIndexTy StoresByIndex;
458263508Sdim
459263508Sdim  for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;
460263508Sdim       ++UI)
461263508Sdim    if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
462263508Sdim      StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
463263508Sdim
464263508Sdim  // Sort the stores by their index, making it efficient to do a lookup with a
465263508Sdim  // binary search.
466263508Sdim  std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
467263508Sdim
468263508Sdim  // Walk all of the loads from this alloca, replacing them with the nearest
469263508Sdim  // store above them, if any.
470263508Sdim  for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
471263508Sdim    LoadInst *LI = dyn_cast<LoadInst>(*UI++);
472263508Sdim    if (!LI)
473263508Sdim      continue;
474263508Sdim
475263508Sdim    unsigned LoadIdx = LBI.getInstructionIndex(LI);
476263508Sdim
477263508Sdim    // Find the nearest store that has a lower index than this load.
478263508Sdim    StoresByIndexTy::iterator I =
479263508Sdim        std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
480263508Sdim                         std::make_pair(LoadIdx, static_cast<StoreInst *>(0)),
481263508Sdim                         less_first());
482263508Sdim
483263508Sdim    if (I == StoresByIndex.begin())
484263508Sdim      // If there is no store before this load, the load takes the undef value.
485263508Sdim      LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
486263508Sdim    else
487263508Sdim      // Otherwise, there was a store before this load, the load takes its value.
488263508Sdim      LI->replaceAllUsesWith(llvm::prior(I)->second->getOperand(0));
489263508Sdim
490263508Sdim    if (AST && LI->getType()->isPointerTy())
491263508Sdim      AST->deleteValue(LI);
492263508Sdim    LI->eraseFromParent();
493263508Sdim    LBI.deleteValue(LI);
494263508Sdim  }
495263508Sdim
496263508Sdim  // Remove the (now dead) stores and alloca.
497263508Sdim  while (!AI->use_empty()) {
498263508Sdim    StoreInst *SI = cast<StoreInst>(AI->use_back());
499263508Sdim    // Record debuginfo for the store before removing it.
500263508Sdim    if (DbgDeclareInst *DDI = Info.DbgDeclare) {
501263508Sdim      DIBuilder DIB(*AI->getParent()->getParent()->getParent());
502263508Sdim      ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
503263508Sdim    }
504263508Sdim    SI->eraseFromParent();
505263508Sdim    LBI.deleteValue(SI);
506263508Sdim  }
507263508Sdim
508263508Sdim  if (AST)
509263508Sdim    AST->deleteValue(AI);
510263508Sdim  AI->eraseFromParent();
511263508Sdim  LBI.deleteValue(AI);
512263508Sdim
513263508Sdim  // The alloca's debuginfo can be removed as well.
514263508Sdim  if (DbgDeclareInst *DDI = Info.DbgDeclare) {
515263508Sdim    DDI->eraseFromParent();
516263508Sdim    LBI.deleteValue(DDI);
517263508Sdim  }
518263508Sdim
519263508Sdim  ++NumLocalPromoted;
520263508Sdim}
521263508Sdim
522193323Sedvoid PromoteMem2Reg::run() {
523218893Sdim  Function &F = *DT.getRoot()->getParent();
524193323Sed
525263508Sdim  if (AST)
526263508Sdim    PointerAllocaValues.resize(Allocas.size());
527203954Srdivacky  AllocaDbgDeclares.resize(Allocas.size());
528193323Sed
529193323Sed  AllocaInfo Info;
530193323Sed  LargeBlockInfo LBI;
531193323Sed
532193323Sed  for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
533193323Sed    AllocaInst *AI = Allocas[AllocaNum];
534193323Sed
535263508Sdim    assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
536193323Sed    assert(AI->getParent()->getParent() == &F &&
537193323Sed           "All allocas should be in the same function, which is same as DF!");
538193323Sed
539224145Sdim    removeLifetimeIntrinsicUsers(AI);
540224145Sdim
541193323Sed    if (AI->use_empty()) {
542193323Sed      // If there are no uses of the alloca, just delete it now.
543263508Sdim      if (AST)
544263508Sdim        AST->deleteValue(AI);
545193323Sed      AI->eraseFromParent();
546193323Sed
547193323Sed      // Remove the alloca from the Allocas list, since it has been processed
548193323Sed      RemoveFromAllocasList(AllocaNum);
549193323Sed      ++NumDeadAlloca;
550193323Sed      continue;
551193323Sed    }
552263508Sdim
553193323Sed    // Calculate the set of read and write-locations for each alloca.  This is
554193323Sed    // analogous to finding the 'uses' and 'definitions' of each variable.
555193323Sed    Info.AnalyzeAlloca(AI);
556193323Sed
557193323Sed    // If there is only a single store to this value, replace any loads of
558193323Sed    // it that are directly dominated by the definition with the value stored.
559193323Sed    if (Info.DefiningBlocks.size() == 1) {
560263508Sdim      if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
561193323Sed        // The alloca has been processed, move on.
562193323Sed        RemoveFromAllocasList(AllocaNum);
563193323Sed        ++NumSingleStore;
564193323Sed        continue;
565193323Sed      }
566193323Sed    }
567263508Sdim
568193323Sed    // If the alloca is only read and written in one basic block, just perform a
569193323Sed    // linear sweep over the block to eliminate it.
570193323Sed    if (Info.OnlyUsedInOneBlock) {
571263508Sdim      promoteSingleBlockAlloca(AI, Info, LBI, AST);
572203954Srdivacky
573263508Sdim      // The alloca has been processed, move on.
574263508Sdim      RemoveFromAllocasList(AllocaNum);
575263508Sdim      continue;
576193323Sed    }
577218893Sdim
578218893Sdim    // If we haven't computed dominator tree levels, do so now.
579218893Sdim    if (DomLevels.empty()) {
580263508Sdim      SmallVector<DomTreeNode *, 32> Worklist;
581218893Sdim
582218893Sdim      DomTreeNode *Root = DT.getRootNode();
583218893Sdim      DomLevels[Root] = 0;
584218893Sdim      Worklist.push_back(Root);
585218893Sdim
586218893Sdim      while (!Worklist.empty()) {
587218893Sdim        DomTreeNode *Node = Worklist.pop_back_val();
588218893Sdim        unsigned ChildLevel = DomLevels[Node] + 1;
589218893Sdim        for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
590218893Sdim             CI != CE; ++CI) {
591218893Sdim          DomLevels[*CI] = ChildLevel;
592218893Sdim          Worklist.push_back(*CI);
593218893Sdim        }
594218893Sdim      }
595218893Sdim    }
596218893Sdim
597193323Sed    // If we haven't computed a numbering for the BB's in the function, do so
598193323Sed    // now.
599193323Sed    if (BBNumbers.empty()) {
600193323Sed      unsigned ID = 0;
601193323Sed      for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
602193323Sed        BBNumbers[I] = ID++;
603193323Sed    }
604193323Sed
605193323Sed    // If we have an AST to keep updated, remember some pointer value that is
606193323Sed    // stored into the alloca.
607193323Sed    if (AST)
608193323Sed      PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
609263508Sdim
610203954Srdivacky    // Remember the dbg.declare intrinsic describing this alloca, if any.
611263508Sdim    if (Info.DbgDeclare)
612263508Sdim      AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
613263508Sdim
614193323Sed    // Keep the reverse mapping of the 'Allocas' array for the rename pass.
615193323Sed    AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
616193323Sed
617193323Sed    // At this point, we're committed to promoting the alloca using IDF's, and
618193323Sed    // the standard SSA construction algorithm.  Determine which blocks need PHI
619193323Sed    // nodes and see if we can optimize out some work by avoiding insertion of
620193323Sed    // dead phi nodes.
621193323Sed    DetermineInsertionPoint(AI, AllocaNum, Info);
622193323Sed  }
623193323Sed
624193323Sed  if (Allocas.empty())
625193323Sed    return; // All of the allocas must have been trivial!
626193323Sed
627193323Sed  LBI.clear();
628263508Sdim
629193323Sed  // Set the incoming values for the basic block to be null values for all of
630193323Sed  // the alloca's.  We do this in case there is a load of a value that has not
631193323Sed  // been stored yet.  In this case, it will get this null value.
632193323Sed  //
633193323Sed  RenamePassData::ValVector Values(Allocas.size());
634193323Sed  for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
635193323Sed    Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
636193323Sed
637193323Sed  // Walks all basic blocks in the function performing the SSA rename algorithm
638193323Sed  // and inserting the phi nodes we marked as necessary
639193323Sed  //
640193323Sed  std::vector<RenamePassData> RenamePassWorkList;
641193323Sed  RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
642202375Srdivacky  do {
643193323Sed    RenamePassData RPD;
644193323Sed    RPD.swap(RenamePassWorkList.back());
645193323Sed    RenamePassWorkList.pop_back();
646193323Sed    // RenamePass may add new worklist entries.
647193323Sed    RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
648202375Srdivacky  } while (!RenamePassWorkList.empty());
649263508Sdim
650193323Sed  // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
651193323Sed  Visited.clear();
652193323Sed
653193323Sed  // Remove the allocas themselves from the function.
654193323Sed  for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
655193323Sed    Instruction *A = Allocas[i];
656193323Sed
657193323Sed    // If there are any uses of the alloca instructions left, they must be in
658218893Sdim    // unreachable basic blocks that were not processed by walking the dominator
659218893Sdim    // tree. Just delete the users now.
660193323Sed    if (!A->use_empty())
661193323Sed      A->replaceAllUsesWith(UndefValue::get(A->getType()));
662263508Sdim    if (AST)
663263508Sdim      AST->deleteValue(A);
664193323Sed    A->eraseFromParent();
665193323Sed  }
666193323Sed
667203954Srdivacky  // Remove alloca's dbg.declare instrinsics from the function.
668203954Srdivacky  for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
669203954Srdivacky    if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
670203954Srdivacky      DDI->eraseFromParent();
671203954Srdivacky
672193323Sed  // Loop over all of the PHI nodes and see if there are any that we can get
673193323Sed  // rid of because they merge all of the same incoming values.  This can
674193323Sed  // happen due to undef values coming into the PHI nodes.  This process is
675193323Sed  // iterative, because eliminating one PHI node can cause others to be removed.
676193323Sed  bool EliminatedAPHI = true;
677193323Sed  while (EliminatedAPHI) {
678193323Sed    EliminatedAPHI = false;
679263508Sdim
680243830Sdim    // Iterating over NewPhiNodes is deterministic, so it is safe to try to
681243830Sdim    // simplify and RAUW them as we go.  If it was not, we could add uses to
682243830Sdim    // the values we replace with in a non deterministic order, thus creating
683243830Sdim    // non deterministic def->use chains.
684263508Sdim    for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
685263508Sdim             I = NewPhiNodes.begin(),
686263508Sdim             E = NewPhiNodes.end();
687263508Sdim         I != E;) {
688193323Sed      PHINode *PN = I->second;
689218893Sdim
690193323Sed      // If this PHI node merges one value and/or undefs, get the value.
691234353Sdim      if (Value *V = SimplifyInstruction(PN, 0, 0, &DT)) {
692204642Srdivacky        if (AST && PN->getType()->isPointerTy())
693198090Srdivacky          AST->deleteValue(PN);
694198090Srdivacky        PN->replaceAllUsesWith(V);
695198090Srdivacky        PN->eraseFromParent();
696198090Srdivacky        NewPhiNodes.erase(I++);
697198090Srdivacky        EliminatedAPHI = true;
698198090Srdivacky        continue;
699193323Sed      }
700193323Sed      ++I;
701193323Sed    }
702193323Sed  }
703263508Sdim
704193323Sed  // At this point, the renamer has added entries to PHI nodes for all reachable
705193323Sed  // code.  Unfortunately, there may be unreachable blocks which the renamer
706193323Sed  // hasn't traversed.  If this is the case, the PHI nodes may not
707193323Sed  // have incoming values for all predecessors.  Loop over all PHI nodes we have
708193323Sed  // created, inserting undef values if they are missing any incoming values.
709193323Sed  //
710263508Sdim  for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
711263508Sdim           I = NewPhiNodes.begin(),
712263508Sdim           E = NewPhiNodes.end();
713263508Sdim       I != E; ++I) {
714193323Sed    // We want to do this once per basic block.  As such, only process a block
715193323Sed    // when we find the PHI that is the first entry in the block.
716193323Sed    PHINode *SomePHI = I->second;
717193323Sed    BasicBlock *BB = SomePHI->getParent();
718193323Sed    if (&BB->front() != SomePHI)
719193323Sed      continue;
720193323Sed
721193323Sed    // Only do work here if there the PHI nodes are missing incoming values.  We
722193323Sed    // know that all PHI nodes that were inserted in a block will have the same
723193323Sed    // number of incoming values, so we can just check any of them.
724193323Sed    if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
725193323Sed      continue;
726193323Sed
727193323Sed    // Get the preds for BB.
728263508Sdim    SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
729263508Sdim
730193323Sed    // Ok, now we know that all of the PHI nodes are missing entries for some
731193323Sed    // basic blocks.  Start by sorting the incoming predecessors for efficient
732193323Sed    // access.
733193323Sed    std::sort(Preds.begin(), Preds.end());
734263508Sdim
735193323Sed    // Now we loop through all BB's which have entries in SomePHI and remove
736193323Sed    // them from the Preds list.
737193323Sed    for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
738193323Sed      // Do a log(n) search of the Preds list for the entry we want.
739263508Sdim      SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
740263508Sdim          Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
741263508Sdim      assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
742193323Sed             "PHI node has entry for a block which is not a predecessor!");
743193323Sed
744193323Sed      // Remove the entry
745193323Sed      Preds.erase(EntIt);
746193323Sed    }
747193323Sed
748193323Sed    // At this point, the blocks left in the preds list must have dummy
749193323Sed    // entries inserted into every PHI nodes for the block.  Update all the phi
750193323Sed    // nodes in this block that we are inserting (there could be phis before
751193323Sed    // mem2reg runs).
752193323Sed    unsigned NumBadPreds = SomePHI->getNumIncomingValues();
753193323Sed    BasicBlock::iterator BBI = BB->begin();
754193323Sed    while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
755193323Sed           SomePHI->getNumIncomingValues() == NumBadPreds) {
756193323Sed      Value *UndefVal = UndefValue::get(SomePHI->getType());
757193323Sed      for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
758193323Sed        SomePHI->addIncoming(UndefVal, Preds[pred]);
759193323Sed    }
760193323Sed  }
761263508Sdim
762193323Sed  NewPhiNodes.clear();
763193323Sed}
764193323Sed
765263508Sdim/// \brief Determine which blocks the value is live in.
766263508Sdim///
767263508Sdim/// These are blocks which lead to uses.  Knowing this allows us to avoid
768263508Sdim/// inserting PHI nodes into blocks which don't lead to uses (thus, the
769263508Sdim/// inserted phi nodes would be dead).
770263508Sdimvoid PromoteMem2Reg::ComputeLiveInBlocks(
771263508Sdim    AllocaInst *AI, AllocaInfo &Info,
772263508Sdim    const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
773263508Sdim    SmallPtrSet<BasicBlock *, 32> &LiveInBlocks) {
774193323Sed
775193323Sed  // To determine liveness, we must iterate through the predecessors of blocks
776193323Sed  // where the def is live.  Blocks are added to the worklist if we need to
777193323Sed  // check their predecessors.  Start with all the using blocks.
778263508Sdim  SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
779263508Sdim                                                    Info.UsingBlocks.end());
780263508Sdim
781193323Sed  // If any of the using blocks is also a definition block, check to see if the
782193323Sed  // definition occurs before or after the use.  If it happens before the use,
783193323Sed  // the value isn't really live-in.
784193323Sed  for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
785193323Sed    BasicBlock *BB = LiveInBlockWorklist[i];
786263508Sdim    if (!DefBlocks.count(BB))
787263508Sdim      continue;
788263508Sdim
789193323Sed    // Okay, this is a block that both uses and defines the value.  If the first
790193323Sed    // reference to the alloca is a def (store), then we know it isn't live-in.
791263508Sdim    for (BasicBlock::iterator I = BB->begin();; ++I) {
792193323Sed      if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
793263508Sdim        if (SI->getOperand(1) != AI)
794263508Sdim          continue;
795263508Sdim
796193323Sed        // We found a store to the alloca before a load.  The alloca is not
797193323Sed        // actually live-in here.
798193323Sed        LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
799193323Sed        LiveInBlockWorklist.pop_back();
800193323Sed        --i, --e;
801193323Sed        break;
802198090Srdivacky      }
803263508Sdim
804198090Srdivacky      if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
805263508Sdim        if (LI->getOperand(0) != AI)
806263508Sdim          continue;
807263508Sdim
808193323Sed        // Okay, we found a load before a store to the alloca.  It is actually
809193323Sed        // live into this block.
810193323Sed        break;
811193323Sed      }
812193323Sed    }
813193323Sed  }
814263508Sdim
815193323Sed  // Now that we have a set of blocks where the phi is live-in, recursively add
816193323Sed  // their predecessors until we find the full region the value is live.
817193323Sed  while (!LiveInBlockWorklist.empty()) {
818193323Sed    BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
819263508Sdim
820193323Sed    // The block really is live in here, insert it into the set.  If already in
821193323Sed    // the set, then it has already been processed.
822193323Sed    if (!LiveInBlocks.insert(BB))
823193323Sed      continue;
824263508Sdim
825193323Sed    // Since the value is live into BB, it is either defined in a predecessor or
826193323Sed    // live into it to.  Add the preds to the worklist unless they are a
827193323Sed    // defining block.
828193323Sed    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
829193323Sed      BasicBlock *P = *PI;
830263508Sdim
831193323Sed      // The value is not live into a predecessor if it defines the value.
832193323Sed      if (DefBlocks.count(P))
833193323Sed        continue;
834263508Sdim
835193323Sed      // Otherwise it is, add to the worklist.
836193323Sed      LiveInBlockWorklist.push_back(P);
837193323Sed    }
838193323Sed  }
839193323Sed}
840193323Sed
841263508Sdim/// At this point, we're committed to promoting the alloca using IDF's, and the
842263508Sdim/// standard SSA construction algorithm.  Determine which blocks need phi nodes
843263508Sdim/// and see if we can optimize out some work by avoiding insertion of dead phi
844263508Sdim/// nodes.
845193323Sedvoid PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
846193323Sed                                             AllocaInfo &Info) {
847193323Sed  // Unique the set of defining blocks for efficient lookup.
848263508Sdim  SmallPtrSet<BasicBlock *, 32> DefBlocks;
849193323Sed  DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
850193323Sed
851193323Sed  // Determine which blocks the value is live in.  These are blocks which lead
852193323Sed  // to uses.
853263508Sdim  SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
854193323Sed  ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
855193323Sed
856218893Sdim  // Use a priority queue keyed on dominator tree level so that inserted nodes
857218893Sdim  // are handled from the bottom of the dominator tree upwards.
858263508Sdim  typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
859218893Sdim  typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
860263508Sdim                              less_second> IDFPriorityQueue;
861218893Sdim  IDFPriorityQueue PQ;
862218893Sdim
863263508Sdim  for (SmallPtrSet<BasicBlock *, 32>::const_iterator I = DefBlocks.begin(),
864263508Sdim                                                     E = DefBlocks.end();
865263508Sdim       I != E; ++I) {
866218893Sdim    if (DomTreeNode *Node = DT.getNode(*I))
867218893Sdim      PQ.push(std::make_pair(Node, DomLevels[Node]));
868218893Sdim  }
869218893Sdim
870263508Sdim  SmallVector<std::pair<unsigned, BasicBlock *>, 32> DFBlocks;
871263508Sdim  SmallPtrSet<DomTreeNode *, 32> Visited;
872263508Sdim  SmallVector<DomTreeNode *, 32> Worklist;
873218893Sdim  while (!PQ.empty()) {
874218893Sdim    DomTreeNodePair RootPair = PQ.top();
875218893Sdim    PQ.pop();
876218893Sdim    DomTreeNode *Root = RootPair.first;
877218893Sdim    unsigned RootLevel = RootPair.second;
878218893Sdim
879218893Sdim    // Walk all dominator tree children of Root, inspecting their CFG edges with
880218893Sdim    // targets elsewhere on the dominator tree. Only targets whose level is at
881218893Sdim    // most Root's level are added to the iterated dominance frontier of the
882218893Sdim    // definition set.
883218893Sdim
884218893Sdim    Worklist.clear();
885218893Sdim    Worklist.push_back(Root);
886218893Sdim
887218893Sdim    while (!Worklist.empty()) {
888218893Sdim      DomTreeNode *Node = Worklist.pop_back_val();
889218893Sdim      BasicBlock *BB = Node->getBlock();
890218893Sdim
891218893Sdim      for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
892218893Sdim           ++SI) {
893218893Sdim        DomTreeNode *SuccNode = DT.getNode(*SI);
894218893Sdim
895218893Sdim        // Quickly skip all CFG edges that are also dominator tree edges instead
896218893Sdim        // of catching them below.
897218893Sdim        if (SuccNode->getIDom() == Node)
898218893Sdim          continue;
899218893Sdim
900218893Sdim        unsigned SuccLevel = DomLevels[SuccNode];
901218893Sdim        if (SuccLevel > RootLevel)
902218893Sdim          continue;
903218893Sdim
904218893Sdim        if (!Visited.insert(SuccNode))
905218893Sdim          continue;
906218893Sdim
907218893Sdim        BasicBlock *SuccBB = SuccNode->getBlock();
908218893Sdim        if (!LiveInBlocks.count(SuccBB))
909218893Sdim          continue;
910218893Sdim
911218893Sdim        DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
912218893Sdim        if (!DefBlocks.count(SuccBB))
913218893Sdim          PQ.push(std::make_pair(SuccNode, SuccLevel));
914218893Sdim      }
915218893Sdim
916218893Sdim      for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
917218893Sdim           ++CI) {
918218893Sdim        if (!Visited.count(*CI))
919218893Sdim          Worklist.push_back(*CI);
920218893Sdim      }
921193323Sed    }
922193323Sed  }
923218893Sdim
924218893Sdim  if (DFBlocks.size() > 1)
925218893Sdim    std::sort(DFBlocks.begin(), DFBlocks.end());
926218893Sdim
927218893Sdim  unsigned CurrentVersion = 0;
928218893Sdim  for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
929218893Sdim    QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
930193323Sed}
931193323Sed
932263508Sdim/// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
933193323Sed///
934263508Sdim/// Returns true if there wasn't already a phi-node for that variable
935193323Sedbool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
936218893Sdim                                  unsigned &Version) {
937193323Sed  // Look up the basic-block in question.
938243830Sdim  PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
939193323Sed
940193323Sed  // If the BB already has a phi node added for the i'th alloca then we're done!
941263508Sdim  if (PN)
942263508Sdim    return false;
943193323Sed
944193323Sed  // Create a PhiNode using the dereferenced type... and add the phi-node to the
945193323Sed  // BasicBlock.
946221345Sdim  PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
947263508Sdim                       Allocas[AllocaNo]->getName() + "." + Twine(Version++),
948198090Srdivacky                       BB->begin());
949193323Sed  ++NumPHIInsert;
950193323Sed  PhiToAllocaMap[PN] = AllocaNo;
951193323Sed
952204642Srdivacky  if (AST && PN->getType()->isPointerTy())
953193323Sed    AST->copyValue(PointerAllocaValues[AllocaNo], PN);
954193323Sed
955193323Sed  return true;
956193323Sed}
957193323Sed
958263508Sdim/// \brief Recursively traverse the CFG of the function, renaming loads and
959263508Sdim/// stores to the allocas which we are promoting.
960263508Sdim///
961263508Sdim/// IncomingVals indicates what value each Alloca contains on exit from the
962263508Sdim/// predecessor block Pred.
963193323Sedvoid PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
964193323Sed                                RenamePassData::ValVector &IncomingVals,
965193323Sed                                std::vector<RenamePassData> &Worklist) {
966193323SedNextIteration:
967193323Sed  // If we are inserting any phi nodes into this BB, they will already be in the
968193323Sed  // block.
969193323Sed  if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
970193323Sed    // If we have PHI nodes to update, compute the number of edges from Pred to
971193323Sed    // BB.
972193323Sed    if (PhiToAllocaMap.count(APN)) {
973193323Sed      // We want to be able to distinguish between PHI nodes being inserted by
974193323Sed      // this invocation of mem2reg from those phi nodes that already existed in
975193323Sed      // the IR before mem2reg was run.  We determine that APN is being inserted
976193323Sed      // because it is missing incoming edges.  All other PHI nodes being
977193323Sed      // inserted by this pass of mem2reg will have the same number of incoming
978193323Sed      // operands so far.  Remember this count.
979193323Sed      unsigned NewPHINumOperands = APN->getNumOperands();
980263508Sdim
981263508Sdim      unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
982193323Sed      assert(NumEdges && "Must be at least one edge from Pred to BB!");
983263508Sdim
984193323Sed      // Add entries for all the phis.
985193323Sed      BasicBlock::iterator PNI = BB->begin();
986193323Sed      do {
987193323Sed        unsigned AllocaNo = PhiToAllocaMap[APN];
988263508Sdim
989193323Sed        // Add N incoming values to the PHI node.
990193323Sed        for (unsigned i = 0; i != NumEdges; ++i)
991193323Sed          APN->addIncoming(IncomingVals[AllocaNo], Pred);
992263508Sdim
993193323Sed        // The currently active variable for this block is now the PHI.
994193323Sed        IncomingVals[AllocaNo] = APN;
995263508Sdim
996193323Sed        // Get the next phi node.
997193323Sed        ++PNI;
998193323Sed        APN = dyn_cast<PHINode>(PNI);
999263508Sdim        if (APN == 0)
1000263508Sdim          break;
1001263508Sdim
1002193323Sed        // Verify that it is missing entries.  If not, it is not being inserted
1003193323Sed        // by this mem2reg invocation so we want to ignore it.
1004193323Sed      } while (APN->getNumOperands() == NewPHINumOperands);
1005193323Sed    }
1006193323Sed  }
1007263508Sdim
1008193323Sed  // Don't revisit blocks.
1009263508Sdim  if (!Visited.insert(BB))
1010263508Sdim    return;
1011193323Sed
1012263508Sdim  for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
1013193323Sed    Instruction *I = II++; // get the instruction, increment iterator
1014193323Sed
1015193323Sed    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1016193323Sed      AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1017263508Sdim      if (!Src)
1018263508Sdim        continue;
1019193323Sed
1020263508Sdim      DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
1021263508Sdim      if (AI == AllocaLookup.end())
1022263508Sdim        continue;
1023263508Sdim
1024193323Sed      Value *V = IncomingVals[AI->second];
1025193323Sed
1026193323Sed      // Anything using the load now uses the current value.
1027193323Sed      LI->replaceAllUsesWith(V);
1028204642Srdivacky      if (AST && LI->getType()->isPointerTy())
1029193323Sed        AST->deleteValue(LI);
1030193323Sed      BB->getInstList().erase(LI);
1031193323Sed    } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1032193323Sed      // Delete this instruction and mark the name as the current holder of the
1033193323Sed      // value
1034193323Sed      AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1035263508Sdim      if (!Dest)
1036263508Sdim        continue;
1037263508Sdim
1038218893Sdim      DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1039193323Sed      if (ai == AllocaLookup.end())
1040193323Sed        continue;
1041263508Sdim
1042193323Sed      // what value were we writing?
1043193323Sed      IncomingVals[ai->second] = SI->getOperand(0);
1044202878Srdivacky      // Record debuginfo for the store before removing it.
1045263508Sdim      if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
1046263508Sdim        ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1047193323Sed      BB->getInstList().erase(SI);
1048193323Sed    }
1049193323Sed  }
1050193323Sed
1051193323Sed  // 'Recurse' to our successors.
1052193323Sed  succ_iterator I = succ_begin(BB), E = succ_end(BB);
1053263508Sdim  if (I == E)
1054263508Sdim    return;
1055193323Sed
1056193323Sed  // Keep track of the successors so we don't visit the same successor twice
1057263508Sdim  SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1058193323Sed
1059193323Sed  // Handle the first successor without using the worklist.
1060193323Sed  VisitedSuccs.insert(*I);
1061193323Sed  Pred = BB;
1062193323Sed  BB = *I;
1063193323Sed  ++I;
1064193323Sed
1065193323Sed  for (; I != E; ++I)
1066193323Sed    if (VisitedSuccs.insert(*I))
1067193323Sed      Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
1068193323Sed
1069193323Sed  goto NextIteration;
1070193323Sed}
1071193323Sed
1072263508Sdimvoid llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
1073263508Sdim                           AliasSetTracker *AST) {
1074193323Sed  // If there is nothing to do, bail out...
1075263508Sdim  if (Allocas.empty())
1076263508Sdim    return;
1077193323Sed
1078218893Sdim  PromoteMem2Reg(Allocas, DT, AST).run();
1079193323Sed}
1080