LLVM API Documentation

PromoteMemoryToRegister.cpp
Go to the documentation of this file.
00001 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file promotes memory references to be register references.  It promotes
00011 // alloca instructions which only have loads and stores as uses.  An alloca is
00012 // transformed by using iterated dominator frontiers to place PHI nodes, then
00013 // traversing the function in depth-first order to rewrite loads and stores as
00014 // appropriate.
00015 //
00016 // The algorithm used here is based on:
00017 //
00018 //   Sreedhar and Gao. A linear time algorithm for placing phi-nodes.
00019 //   In Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of
00020 //   Programming Languages
00021 //   POPL '95. ACM, New York, NY, 62-73.
00022 //
00023 // It has been modified to not explicitly use the DJ graph data structure and to
00024 // directly compute pruned SSA using per-variable liveness information.
00025 //
00026 //===----------------------------------------------------------------------===//
00027 
00028 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00029 #include "llvm/ADT/ArrayRef.h"
00030 #include "llvm/ADT/DenseMap.h"
00031 #include "llvm/ADT/STLExtras.h"
00032 #include "llvm/ADT/SmallPtrSet.h"
00033 #include "llvm/ADT/SmallVector.h"
00034 #include "llvm/ADT/Statistic.h"
00035 #include "llvm/Analysis/AliasSetTracker.h"
00036 #include "llvm/Analysis/InstructionSimplify.h"
00037 #include "llvm/Analysis/ValueTracking.h"
00038 #include "llvm/IR/CFG.h"
00039 #include "llvm/IR/Constants.h"
00040 #include "llvm/IR/DIBuilder.h"
00041 #include "llvm/IR/DebugInfo.h"
00042 #include "llvm/IR/DerivedTypes.h"
00043 #include "llvm/IR/Dominators.h"
00044 #include "llvm/IR/Function.h"
00045 #include "llvm/IR/Instructions.h"
00046 #include "llvm/IR/IntrinsicInst.h"
00047 #include "llvm/IR/Metadata.h"
00048 #include "llvm/Transforms/Utils/Local.h"
00049 #include <algorithm>
00050 #include <queue>
00051 using namespace llvm;
00052 
00053 #define DEBUG_TYPE "mem2reg"
00054 
00055 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
00056 STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
00057 STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
00058 STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
00059 
00060 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
00061   // FIXME: If the memory unit is of pointer or integer type, we can permit
00062   // assignments to subsections of the memory unit.
00063   unsigned AS = AI->getType()->getAddressSpace();
00064 
00065   // Only allow direct and non-volatile loads and stores...
00066   for (const User *U : AI->users()) {
00067     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
00068       // Note that atomic loads can be transformed; atomic semantics do
00069       // not have any meaning for a local alloca.
00070       if (LI->isVolatile())
00071         return false;
00072     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
00073       if (SI->getOperand(0) == AI)
00074         return false; // Don't allow a store OF the AI, only INTO the AI.
00075       // Note that atomic stores can be transformed; atomic semantics do
00076       // not have any meaning for a local alloca.
00077       if (SI->isVolatile())
00078         return false;
00079     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
00080       if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
00081           II->getIntrinsicID() != Intrinsic::lifetime_end)
00082         return false;
00083     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
00084       if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
00085         return false;
00086       if (!onlyUsedByLifetimeMarkers(BCI))
00087         return false;
00088     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
00089       if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
00090         return false;
00091       if (!GEPI->hasAllZeroIndices())
00092         return false;
00093       if (!onlyUsedByLifetimeMarkers(GEPI))
00094         return false;
00095     } else {
00096       return false;
00097     }
00098   }
00099 
00100   return true;
00101 }
00102 
00103 namespace {
00104 
00105 struct AllocaInfo {
00106   SmallVector<BasicBlock *, 32> DefiningBlocks;
00107   SmallVector<BasicBlock *, 32> UsingBlocks;
00108 
00109   StoreInst *OnlyStore;
00110   BasicBlock *OnlyBlock;
00111   bool OnlyUsedInOneBlock;
00112 
00113   Value *AllocaPointerVal;
00114   DbgDeclareInst *DbgDeclare;
00115 
00116   void clear() {
00117     DefiningBlocks.clear();
00118     UsingBlocks.clear();
00119     OnlyStore = 0;
00120     OnlyBlock = 0;
00121     OnlyUsedInOneBlock = true;
00122     AllocaPointerVal = 0;
00123     DbgDeclare = 0;
00124   }
00125 
00126   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
00127   /// by the rest of the pass to reason about the uses of this alloca.
00128   void AnalyzeAlloca(AllocaInst *AI) {
00129     clear();
00130 
00131     // As we scan the uses of the alloca instruction, keep track of stores,
00132     // and decide whether all of the loads and stores to the alloca are within
00133     // the same basic block.
00134     for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
00135       Instruction *User = cast<Instruction>(*UI++);
00136 
00137       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00138         // Remember the basic blocks which define new values for the alloca
00139         DefiningBlocks.push_back(SI->getParent());
00140         AllocaPointerVal = SI->getOperand(0);
00141         OnlyStore = SI;
00142       } else {
00143         LoadInst *LI = cast<LoadInst>(User);
00144         // Otherwise it must be a load instruction, keep track of variable
00145         // reads.
00146         UsingBlocks.push_back(LI->getParent());
00147         AllocaPointerVal = LI;
00148       }
00149 
00150       if (OnlyUsedInOneBlock) {
00151         if (OnlyBlock == 0)
00152           OnlyBlock = User->getParent();
00153         else if (OnlyBlock != User->getParent())
00154           OnlyUsedInOneBlock = false;
00155       }
00156     }
00157 
00158     DbgDeclare = FindAllocaDbgDeclare(AI);
00159   }
00160 };
00161 
00162 // Data package used by RenamePass()
00163 class RenamePassData {
00164 public:
00165   typedef std::vector<Value *> ValVector;
00166 
00167   RenamePassData() : BB(NULL), Pred(NULL), Values() {}
00168   RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
00169       : BB(B), Pred(P), Values(V) {}
00170   BasicBlock *BB;
00171   BasicBlock *Pred;
00172   ValVector Values;
00173 
00174   void swap(RenamePassData &RHS) {
00175     std::swap(BB, RHS.BB);
00176     std::swap(Pred, RHS.Pred);
00177     Values.swap(RHS.Values);
00178   }
00179 };
00180 
00181 /// \brief This assigns and keeps a per-bb relative ordering of load/store
00182 /// instructions in the block that directly load or store an alloca.
00183 ///
00184 /// This functionality is important because it avoids scanning large basic
00185 /// blocks multiple times when promoting many allocas in the same block.
00186 class LargeBlockInfo {
00187   /// \brief For each instruction that we track, keep the index of the
00188   /// instruction.
00189   ///
00190   /// The index starts out as the number of the instruction from the start of
00191   /// the block.
00192   DenseMap<const Instruction *, unsigned> InstNumbers;
00193 
00194 public:
00195 
00196   /// This code only looks at accesses to allocas.
00197   static bool isInterestingInstruction(const Instruction *I) {
00198     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
00199            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
00200   }
00201 
00202   /// Get or calculate the index of the specified instruction.
00203   unsigned getInstructionIndex(const Instruction *I) {
00204     assert(isInterestingInstruction(I) &&
00205            "Not a load/store to/from an alloca?");
00206 
00207     // If we already have this instruction number, return it.
00208     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
00209     if (It != InstNumbers.end())
00210       return It->second;
00211 
00212     // Scan the whole block to get the instruction.  This accumulates
00213     // information for every interesting instruction in the block, in order to
00214     // avoid gratuitus rescans.
00215     const BasicBlock *BB = I->getParent();
00216     unsigned InstNo = 0;
00217     for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
00218          ++BBI)
00219       if (isInterestingInstruction(BBI))
00220         InstNumbers[BBI] = InstNo++;
00221     It = InstNumbers.find(I);
00222 
00223     assert(It != InstNumbers.end() && "Didn't insert instruction?");
00224     return It->second;
00225   }
00226 
00227   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
00228 
00229   void clear() { InstNumbers.clear(); }
00230 };
00231 
00232 struct PromoteMem2Reg {
00233   /// The alloca instructions being promoted.
00234   std::vector<AllocaInst *> Allocas;
00235   DominatorTree &DT;
00236   DIBuilder DIB;
00237 
00238   /// An AliasSetTracker object to update.  If null, don't update it.
00239   AliasSetTracker *AST;
00240 
00241   /// Reverse mapping of Allocas.
00242   DenseMap<AllocaInst *, unsigned> AllocaLookup;
00243 
00244   /// \brief The PhiNodes we're adding.
00245   ///
00246   /// That map is used to simplify some Phi nodes as we iterate over it, so
00247   /// it should have deterministic iterators.  We could use a MapVector, but
00248   /// since we already maintain a map from BasicBlock* to a stable numbering
00249   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
00250   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
00251 
00252   /// For each PHI node, keep track of which entry in Allocas it corresponds
00253   /// to.
00254   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
00255 
00256   /// If we are updating an AliasSetTracker, then for each alloca that is of
00257   /// pointer type, we keep track of what to copyValue to the inserted PHI
00258   /// nodes here.
00259   std::vector<Value *> PointerAllocaValues;
00260 
00261   /// For each alloca, we keep track of the dbg.declare intrinsic that
00262   /// describes it, if any, so that we can convert it to a dbg.value
00263   /// intrinsic if the alloca gets promoted.
00264   SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
00265 
00266   /// The set of basic blocks the renamer has already visited.
00267   ///
00268   SmallPtrSet<BasicBlock *, 16> Visited;
00269 
00270   /// Contains a stable numbering of basic blocks to avoid non-determinstic
00271   /// behavior.
00272   DenseMap<BasicBlock *, unsigned> BBNumbers;
00273 
00274   /// Maps DomTreeNodes to their level in the dominator tree.
00275   DenseMap<DomTreeNode *, unsigned> DomLevels;
00276 
00277   /// Lazily compute the number of predecessors a block has.
00278   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
00279 
00280 public:
00281   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
00282                  AliasSetTracker *AST)
00283       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
00284         DIB(*DT.getRoot()->getParent()->getParent()), AST(AST) {}
00285 
00286   void run();
00287 
00288 private:
00289   void RemoveFromAllocasList(unsigned &AllocaIdx) {
00290     Allocas[AllocaIdx] = Allocas.back();
00291     Allocas.pop_back();
00292     --AllocaIdx;
00293   }
00294 
00295   unsigned getNumPreds(const BasicBlock *BB) {
00296     unsigned &NP = BBNumPreds[BB];
00297     if (NP == 0)
00298       NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
00299     return NP - 1;
00300   }
00301 
00302   void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
00303                                AllocaInfo &Info);
00304   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
00305                            const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
00306                            SmallPtrSet<BasicBlock *, 32> &LiveInBlocks);
00307   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
00308                   RenamePassData::ValVector &IncVals,
00309                   std::vector<RenamePassData> &Worklist);
00310   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
00311 };
00312 
00313 } // end of anonymous namespace
00314 
00315 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
00316   // Knowing that this alloca is promotable, we know that it's safe to kill all
00317   // instructions except for load and store.
00318 
00319   for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
00320     Instruction *I = cast<Instruction>(*UI);
00321     ++UI;
00322     if (isa<LoadInst>(I) || isa<StoreInst>(I))
00323       continue;
00324 
00325     if (!I->getType()->isVoidTy()) {
00326       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
00327       // Follow the use/def chain to erase them now instead of leaving it for
00328       // dead code elimination later.
00329       for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
00330         Instruction *Inst = cast<Instruction>(*UUI);
00331         ++UUI;
00332         Inst->eraseFromParent();
00333       }
00334     }
00335     I->eraseFromParent();
00336   }
00337 }
00338 
00339 /// \brief Rewrite as many loads as possible given a single store.
00340 ///
00341 /// When there is only a single store, we can use the domtree to trivially
00342 /// replace all of the dominated loads with the stored value. Do so, and return
00343 /// true if this has successfully promoted the alloca entirely. If this returns
00344 /// false there were some loads which were not dominated by the single store
00345 /// and thus must be phi-ed with undef. We fall back to the standard alloca
00346 /// promotion algorithm in that case.
00347 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
00348                                      LargeBlockInfo &LBI,
00349                                      DominatorTree &DT,
00350                                      AliasSetTracker *AST) {
00351   StoreInst *OnlyStore = Info.OnlyStore;
00352   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
00353   BasicBlock *StoreBB = OnlyStore->getParent();
00354   int StoreIndex = -1;
00355 
00356   // Clear out UsingBlocks.  We will reconstruct it here if needed.
00357   Info.UsingBlocks.clear();
00358 
00359   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
00360     Instruction *UserInst = cast<Instruction>(*UI++);
00361     if (!isa<LoadInst>(UserInst)) {
00362       assert(UserInst == OnlyStore && "Should only have load/stores");
00363       continue;
00364     }
00365     LoadInst *LI = cast<LoadInst>(UserInst);
00366 
00367     // Okay, if we have a load from the alloca, we want to replace it with the
00368     // only value stored to the alloca.  We can do this if the value is
00369     // dominated by the store.  If not, we use the rest of the mem2reg machinery
00370     // to insert the phi nodes as needed.
00371     if (!StoringGlobalVal) { // Non-instructions are always dominated.
00372       if (LI->getParent() == StoreBB) {
00373         // If we have a use that is in the same block as the store, compare the
00374         // indices of the two instructions to see which one came first.  If the
00375         // load came before the store, we can't handle it.
00376         if (StoreIndex == -1)
00377           StoreIndex = LBI.getInstructionIndex(OnlyStore);
00378 
00379         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
00380           // Can't handle this load, bail out.
00381           Info.UsingBlocks.push_back(StoreBB);
00382           continue;
00383         }
00384 
00385       } else if (LI->getParent() != StoreBB &&
00386                  !DT.dominates(StoreBB, LI->getParent())) {
00387         // If the load and store are in different blocks, use BB dominance to
00388         // check their relationships.  If the store doesn't dom the use, bail
00389         // out.
00390         Info.UsingBlocks.push_back(LI->getParent());
00391         continue;
00392       }
00393     }
00394 
00395     // Otherwise, we *can* safely rewrite this load.
00396     Value *ReplVal = OnlyStore->getOperand(0);
00397     // If the replacement value is the load, this must occur in unreachable
00398     // code.
00399     if (ReplVal == LI)
00400       ReplVal = UndefValue::get(LI->getType());
00401     LI->replaceAllUsesWith(ReplVal);
00402     if (AST && LI->getType()->isPointerTy())
00403       AST->deleteValue(LI);
00404     LI->eraseFromParent();
00405     LBI.deleteValue(LI);
00406   }
00407 
00408   // Finally, after the scan, check to see if the store is all that is left.
00409   if (!Info.UsingBlocks.empty())
00410     return false; // If not, we'll have to fall back for the remainder.
00411 
00412   // Record debuginfo for the store and remove the declaration's
00413   // debuginfo.
00414   if (DbgDeclareInst *DDI = Info.DbgDeclare) {
00415     DIBuilder DIB(*AI->getParent()->getParent()->getParent());
00416     ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
00417     DDI->eraseFromParent();
00418     LBI.deleteValue(DDI);
00419   }
00420   // Remove the (now dead) store and alloca.
00421   Info.OnlyStore->eraseFromParent();
00422   LBI.deleteValue(Info.OnlyStore);
00423 
00424   if (AST)
00425     AST->deleteValue(AI);
00426   AI->eraseFromParent();
00427   LBI.deleteValue(AI);
00428   return true;
00429 }
00430 
00431 /// Many allocas are only used within a single basic block.  If this is the
00432 /// case, avoid traversing the CFG and inserting a lot of potentially useless
00433 /// PHI nodes by just performing a single linear pass over the basic block
00434 /// using the Alloca.
00435 ///
00436 /// If we cannot promote this alloca (because it is read before it is written),
00437 /// return true.  This is necessary in cases where, due to control flow, the
00438 /// alloca is potentially undefined on some control flow paths.  e.g. code like
00439 /// this is potentially correct:
00440 ///
00441 ///   for (...) { if (c) { A = undef; undef = B; } }
00442 ///
00443 /// ... so long as A is not used before undef is set.
00444 static void promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
00445                                      LargeBlockInfo &LBI,
00446                                      AliasSetTracker *AST) {
00447   // The trickiest case to handle is when we have large blocks. Because of this,
00448   // this code is optimized assuming that large blocks happen.  This does not
00449   // significantly pessimize the small block case.  This uses LargeBlockInfo to
00450   // make it efficient to get the index of various operations in the block.
00451 
00452   // Walk the use-def list of the alloca, getting the locations of all stores.
00453   typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
00454   StoresByIndexTy StoresByIndex;
00455 
00456   for (User *U : AI->users())
00457     if (StoreInst *SI = dyn_cast<StoreInst>(U))
00458       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
00459 
00460   // Sort the stores by their index, making it efficient to do a lookup with a
00461   // binary search.
00462   std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
00463 
00464   // Walk all of the loads from this alloca, replacing them with the nearest
00465   // store above them, if any.
00466   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
00467     LoadInst *LI = dyn_cast<LoadInst>(*UI++);
00468     if (!LI)
00469       continue;
00470 
00471     unsigned LoadIdx = LBI.getInstructionIndex(LI);
00472 
00473     // Find the nearest store that has a lower index than this load.
00474     StoresByIndexTy::iterator I =
00475         std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
00476                          std::make_pair(LoadIdx, static_cast<StoreInst *>(0)),
00477                          less_first());
00478 
00479     if (I == StoresByIndex.begin())
00480       // If there is no store before this load, the load takes the undef value.
00481       LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
00482     else
00483       // Otherwise, there was a store before this load, the load takes its value.
00484       LI->replaceAllUsesWith(std::prev(I)->second->getOperand(0));
00485 
00486     if (AST && LI->getType()->isPointerTy())
00487       AST->deleteValue(LI);
00488     LI->eraseFromParent();
00489     LBI.deleteValue(LI);
00490   }
00491 
00492   // Remove the (now dead) stores and alloca.
00493   while (!AI->use_empty()) {
00494     StoreInst *SI = cast<StoreInst>(AI->user_back());
00495     // Record debuginfo for the store before removing it.
00496     if (DbgDeclareInst *DDI = Info.DbgDeclare) {
00497       DIBuilder DIB(*AI->getParent()->getParent()->getParent());
00498       ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
00499     }
00500     SI->eraseFromParent();
00501     LBI.deleteValue(SI);
00502   }
00503 
00504   if (AST)
00505     AST->deleteValue(AI);
00506   AI->eraseFromParent();
00507   LBI.deleteValue(AI);
00508 
00509   // The alloca's debuginfo can be removed as well.
00510   if (DbgDeclareInst *DDI = Info.DbgDeclare) {
00511     DDI->eraseFromParent();
00512     LBI.deleteValue(DDI);
00513   }
00514 
00515   ++NumLocalPromoted;
00516 }
00517 
00518 void PromoteMem2Reg::run() {
00519   Function &F = *DT.getRoot()->getParent();
00520 
00521   if (AST)
00522     PointerAllocaValues.resize(Allocas.size());
00523   AllocaDbgDeclares.resize(Allocas.size());
00524 
00525   AllocaInfo Info;
00526   LargeBlockInfo LBI;
00527 
00528   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
00529     AllocaInst *AI = Allocas[AllocaNum];
00530 
00531     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
00532     assert(AI->getParent()->getParent() == &F &&
00533            "All allocas should be in the same function, which is same as DF!");
00534 
00535     removeLifetimeIntrinsicUsers(AI);
00536 
00537     if (AI->use_empty()) {
00538       // If there are no uses of the alloca, just delete it now.
00539       if (AST)
00540         AST->deleteValue(AI);
00541       AI->eraseFromParent();
00542 
00543       // Remove the alloca from the Allocas list, since it has been processed
00544       RemoveFromAllocasList(AllocaNum);
00545       ++NumDeadAlloca;
00546       continue;
00547     }
00548 
00549     // Calculate the set of read and write-locations for each alloca.  This is
00550     // analogous to finding the 'uses' and 'definitions' of each variable.
00551     Info.AnalyzeAlloca(AI);
00552 
00553     // If there is only a single store to this value, replace any loads of
00554     // it that are directly dominated by the definition with the value stored.
00555     if (Info.DefiningBlocks.size() == 1) {
00556       if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
00557         // The alloca has been processed, move on.
00558         RemoveFromAllocasList(AllocaNum);
00559         ++NumSingleStore;
00560         continue;
00561       }
00562     }
00563 
00564     // If the alloca is only read and written in one basic block, just perform a
00565     // linear sweep over the block to eliminate it.
00566     if (Info.OnlyUsedInOneBlock) {
00567       promoteSingleBlockAlloca(AI, Info, LBI, AST);
00568 
00569       // The alloca has been processed, move on.
00570       RemoveFromAllocasList(AllocaNum);
00571       continue;
00572     }
00573 
00574     // If we haven't computed dominator tree levels, do so now.
00575     if (DomLevels.empty()) {
00576       SmallVector<DomTreeNode *, 32> Worklist;
00577 
00578       DomTreeNode *Root = DT.getRootNode();
00579       DomLevels[Root] = 0;
00580       Worklist.push_back(Root);
00581 
00582       while (!Worklist.empty()) {
00583         DomTreeNode *Node = Worklist.pop_back_val();
00584         unsigned ChildLevel = DomLevels[Node] + 1;
00585         for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
00586              CI != CE; ++CI) {
00587           DomLevels[*CI] = ChildLevel;
00588           Worklist.push_back(*CI);
00589         }
00590       }
00591     }
00592 
00593     // If we haven't computed a numbering for the BB's in the function, do so
00594     // now.
00595     if (BBNumbers.empty()) {
00596       unsigned ID = 0;
00597       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
00598         BBNumbers[I] = ID++;
00599     }
00600 
00601     // If we have an AST to keep updated, remember some pointer value that is
00602     // stored into the alloca.
00603     if (AST)
00604       PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
00605 
00606     // Remember the dbg.declare intrinsic describing this alloca, if any.
00607     if (Info.DbgDeclare)
00608       AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
00609 
00610     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
00611     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
00612 
00613     // At this point, we're committed to promoting the alloca using IDF's, and
00614     // the standard SSA construction algorithm.  Determine which blocks need PHI
00615     // nodes and see if we can optimize out some work by avoiding insertion of
00616     // dead phi nodes.
00617     DetermineInsertionPoint(AI, AllocaNum, Info);
00618   }
00619 
00620   if (Allocas.empty())
00621     return; // All of the allocas must have been trivial!
00622 
00623   LBI.clear();
00624 
00625   // Set the incoming values for the basic block to be null values for all of
00626   // the alloca's.  We do this in case there is a load of a value that has not
00627   // been stored yet.  In this case, it will get this null value.
00628   //
00629   RenamePassData::ValVector Values(Allocas.size());
00630   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
00631     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
00632 
00633   // Walks all basic blocks in the function performing the SSA rename algorithm
00634   // and inserting the phi nodes we marked as necessary
00635   //
00636   std::vector<RenamePassData> RenamePassWorkList;
00637   RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
00638   do {
00639     RenamePassData RPD;
00640     RPD.swap(RenamePassWorkList.back());
00641     RenamePassWorkList.pop_back();
00642     // RenamePass may add new worklist entries.
00643     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
00644   } while (!RenamePassWorkList.empty());
00645 
00646   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
00647   Visited.clear();
00648 
00649   // Remove the allocas themselves from the function.
00650   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
00651     Instruction *A = Allocas[i];
00652 
00653     // If there are any uses of the alloca instructions left, they must be in
00654     // unreachable basic blocks that were not processed by walking the dominator
00655     // tree. Just delete the users now.
00656     if (!A->use_empty())
00657       A->replaceAllUsesWith(UndefValue::get(A->getType()));
00658     if (AST)
00659       AST->deleteValue(A);
00660     A->eraseFromParent();
00661   }
00662 
00663   // Remove alloca's dbg.declare instrinsics from the function.
00664   for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
00665     if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
00666       DDI->eraseFromParent();
00667 
00668   // Loop over all of the PHI nodes and see if there are any that we can get
00669   // rid of because they merge all of the same incoming values.  This can
00670   // happen due to undef values coming into the PHI nodes.  This process is
00671   // iterative, because eliminating one PHI node can cause others to be removed.
00672   bool EliminatedAPHI = true;
00673   while (EliminatedAPHI) {
00674     EliminatedAPHI = false;
00675 
00676     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
00677     // simplify and RAUW them as we go.  If it was not, we could add uses to
00678     // the values we replace with in a non-deterministic order, thus creating
00679     // non-deterministic def->use chains.
00680     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
00681              I = NewPhiNodes.begin(),
00682              E = NewPhiNodes.end();
00683          I != E;) {
00684       PHINode *PN = I->second;
00685 
00686       // If this PHI node merges one value and/or undefs, get the value.
00687       if (Value *V = SimplifyInstruction(PN, 0, 0, &DT)) {
00688         if (AST && PN->getType()->isPointerTy())
00689           AST->deleteValue(PN);
00690         PN->replaceAllUsesWith(V);
00691         PN->eraseFromParent();
00692         NewPhiNodes.erase(I++);
00693         EliminatedAPHI = true;
00694         continue;
00695       }
00696       ++I;
00697     }
00698   }
00699 
00700   // At this point, the renamer has added entries to PHI nodes for all reachable
00701   // code.  Unfortunately, there may be unreachable blocks which the renamer
00702   // hasn't traversed.  If this is the case, the PHI nodes may not
00703   // have incoming values for all predecessors.  Loop over all PHI nodes we have
00704   // created, inserting undef values if they are missing any incoming values.
00705   //
00706   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
00707            I = NewPhiNodes.begin(),
00708            E = NewPhiNodes.end();
00709        I != E; ++I) {
00710     // We want to do this once per basic block.  As such, only process a block
00711     // when we find the PHI that is the first entry in the block.
00712     PHINode *SomePHI = I->second;
00713     BasicBlock *BB = SomePHI->getParent();
00714     if (&BB->front() != SomePHI)
00715       continue;
00716 
00717     // Only do work here if there the PHI nodes are missing incoming values.  We
00718     // know that all PHI nodes that were inserted in a block will have the same
00719     // number of incoming values, so we can just check any of them.
00720     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
00721       continue;
00722 
00723     // Get the preds for BB.
00724     SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
00725 
00726     // Ok, now we know that all of the PHI nodes are missing entries for some
00727     // basic blocks.  Start by sorting the incoming predecessors for efficient
00728     // access.
00729     std::sort(Preds.begin(), Preds.end());
00730 
00731     // Now we loop through all BB's which have entries in SomePHI and remove
00732     // them from the Preds list.
00733     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
00734       // Do a log(n) search of the Preds list for the entry we want.
00735       SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
00736           Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
00737       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
00738              "PHI node has entry for a block which is not a predecessor!");
00739 
00740       // Remove the entry
00741       Preds.erase(EntIt);
00742     }
00743 
00744     // At this point, the blocks left in the preds list must have dummy
00745     // entries inserted into every PHI nodes for the block.  Update all the phi
00746     // nodes in this block that we are inserting (there could be phis before
00747     // mem2reg runs).
00748     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
00749     BasicBlock::iterator BBI = BB->begin();
00750     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
00751            SomePHI->getNumIncomingValues() == NumBadPreds) {
00752       Value *UndefVal = UndefValue::get(SomePHI->getType());
00753       for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
00754         SomePHI->addIncoming(UndefVal, Preds[pred]);
00755     }
00756   }
00757 
00758   NewPhiNodes.clear();
00759 }
00760 
00761 /// \brief Determine which blocks the value is live in.
00762 ///
00763 /// These are blocks which lead to uses.  Knowing this allows us to avoid
00764 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
00765 /// inserted phi nodes would be dead).
00766 void PromoteMem2Reg::ComputeLiveInBlocks(
00767     AllocaInst *AI, AllocaInfo &Info,
00768     const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
00769     SmallPtrSet<BasicBlock *, 32> &LiveInBlocks) {
00770 
00771   // To determine liveness, we must iterate through the predecessors of blocks
00772   // where the def is live.  Blocks are added to the worklist if we need to
00773   // check their predecessors.  Start with all the using blocks.
00774   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
00775                                                     Info.UsingBlocks.end());
00776 
00777   // If any of the using blocks is also a definition block, check to see if the
00778   // definition occurs before or after the use.  If it happens before the use,
00779   // the value isn't really live-in.
00780   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
00781     BasicBlock *BB = LiveInBlockWorklist[i];
00782     if (!DefBlocks.count(BB))
00783       continue;
00784 
00785     // Okay, this is a block that both uses and defines the value.  If the first
00786     // reference to the alloca is a def (store), then we know it isn't live-in.
00787     for (BasicBlock::iterator I = BB->begin();; ++I) {
00788       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00789         if (SI->getOperand(1) != AI)
00790           continue;
00791 
00792         // We found a store to the alloca before a load.  The alloca is not
00793         // actually live-in here.
00794         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
00795         LiveInBlockWorklist.pop_back();
00796         --i, --e;
00797         break;
00798       }
00799 
00800       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00801         if (LI->getOperand(0) != AI)
00802           continue;
00803 
00804         // Okay, we found a load before a store to the alloca.  It is actually
00805         // live into this block.
00806         break;
00807       }
00808     }
00809   }
00810 
00811   // Now that we have a set of blocks where the phi is live-in, recursively add
00812   // their predecessors until we find the full region the value is live.
00813   while (!LiveInBlockWorklist.empty()) {
00814     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
00815 
00816     // The block really is live in here, insert it into the set.  If already in
00817     // the set, then it has already been processed.
00818     if (!LiveInBlocks.insert(BB))
00819       continue;
00820 
00821     // Since the value is live into BB, it is either defined in a predecessor or
00822     // live into it to.  Add the preds to the worklist unless they are a
00823     // defining block.
00824     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00825       BasicBlock *P = *PI;
00826 
00827       // The value is not live into a predecessor if it defines the value.
00828       if (DefBlocks.count(P))
00829         continue;
00830 
00831       // Otherwise it is, add to the worklist.
00832       LiveInBlockWorklist.push_back(P);
00833     }
00834   }
00835 }
00836 
00837 /// At this point, we're committed to promoting the alloca using IDF's, and the
00838 /// standard SSA construction algorithm.  Determine which blocks need phi nodes
00839 /// and see if we can optimize out some work by avoiding insertion of dead phi
00840 /// nodes.
00841 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
00842                                              AllocaInfo &Info) {
00843   // Unique the set of defining blocks for efficient lookup.
00844   SmallPtrSet<BasicBlock *, 32> DefBlocks;
00845   DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
00846 
00847   // Determine which blocks the value is live in.  These are blocks which lead
00848   // to uses.
00849   SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
00850   ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
00851 
00852   // Use a priority queue keyed on dominator tree level so that inserted nodes
00853   // are handled from the bottom of the dominator tree upwards.
00854   typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
00855   typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
00856                               less_second> IDFPriorityQueue;
00857   IDFPriorityQueue PQ;
00858 
00859   for (SmallPtrSet<BasicBlock *, 32>::const_iterator I = DefBlocks.begin(),
00860                                                      E = DefBlocks.end();
00861        I != E; ++I) {
00862     if (DomTreeNode *Node = DT.getNode(*I))
00863       PQ.push(std::make_pair(Node, DomLevels[Node]));
00864   }
00865 
00866   SmallVector<std::pair<unsigned, BasicBlock *>, 32> DFBlocks;
00867   SmallPtrSet<DomTreeNode *, 32> Visited;
00868   SmallVector<DomTreeNode *, 32> Worklist;
00869   while (!PQ.empty()) {
00870     DomTreeNodePair RootPair = PQ.top();
00871     PQ.pop();
00872     DomTreeNode *Root = RootPair.first;
00873     unsigned RootLevel = RootPair.second;
00874 
00875     // Walk all dominator tree children of Root, inspecting their CFG edges with
00876     // targets elsewhere on the dominator tree. Only targets whose level is at
00877     // most Root's level are added to the iterated dominance frontier of the
00878     // definition set.
00879 
00880     Worklist.clear();
00881     Worklist.push_back(Root);
00882 
00883     while (!Worklist.empty()) {
00884       DomTreeNode *Node = Worklist.pop_back_val();
00885       BasicBlock *BB = Node->getBlock();
00886 
00887       for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
00888            ++SI) {
00889         DomTreeNode *SuccNode = DT.getNode(*SI);
00890 
00891         // Quickly skip all CFG edges that are also dominator tree edges instead
00892         // of catching them below.
00893         if (SuccNode->getIDom() == Node)
00894           continue;
00895 
00896         unsigned SuccLevel = DomLevels[SuccNode];
00897         if (SuccLevel > RootLevel)
00898           continue;
00899 
00900         if (!Visited.insert(SuccNode))
00901           continue;
00902 
00903         BasicBlock *SuccBB = SuccNode->getBlock();
00904         if (!LiveInBlocks.count(SuccBB))
00905           continue;
00906 
00907         DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
00908         if (!DefBlocks.count(SuccBB))
00909           PQ.push(std::make_pair(SuccNode, SuccLevel));
00910       }
00911 
00912       for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
00913            ++CI) {
00914         if (!Visited.count(*CI))
00915           Worklist.push_back(*CI);
00916       }
00917     }
00918   }
00919 
00920   if (DFBlocks.size() > 1)
00921     std::sort(DFBlocks.begin(), DFBlocks.end());
00922 
00923   unsigned CurrentVersion = 0;
00924   for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
00925     QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
00926 }
00927 
00928 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
00929 ///
00930 /// Returns true if there wasn't already a phi-node for that variable
00931 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
00932                                   unsigned &Version) {
00933   // Look up the basic-block in question.
00934   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
00935 
00936   // If the BB already has a phi node added for the i'th alloca then we're done!
00937   if (PN)
00938     return false;
00939 
00940   // Create a PhiNode using the dereferenced type... and add the phi-node to the
00941   // BasicBlock.
00942   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
00943                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
00944                        BB->begin());
00945   ++NumPHIInsert;
00946   PhiToAllocaMap[PN] = AllocaNo;
00947 
00948   if (AST && PN->getType()->isPointerTy())
00949     AST->copyValue(PointerAllocaValues[AllocaNo], PN);
00950 
00951   return true;
00952 }
00953 
00954 /// \brief Recursively traverse the CFG of the function, renaming loads and
00955 /// stores to the allocas which we are promoting.
00956 ///
00957 /// IncomingVals indicates what value each Alloca contains on exit from the
00958 /// predecessor block Pred.
00959 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
00960                                 RenamePassData::ValVector &IncomingVals,
00961                                 std::vector<RenamePassData> &Worklist) {
00962 NextIteration:
00963   // If we are inserting any phi nodes into this BB, they will already be in the
00964   // block.
00965   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
00966     // If we have PHI nodes to update, compute the number of edges from Pred to
00967     // BB.
00968     if (PhiToAllocaMap.count(APN)) {
00969       // We want to be able to distinguish between PHI nodes being inserted by
00970       // this invocation of mem2reg from those phi nodes that already existed in
00971       // the IR before mem2reg was run.  We determine that APN is being inserted
00972       // because it is missing incoming edges.  All other PHI nodes being
00973       // inserted by this pass of mem2reg will have the same number of incoming
00974       // operands so far.  Remember this count.
00975       unsigned NewPHINumOperands = APN->getNumOperands();
00976 
00977       unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
00978       assert(NumEdges && "Must be at least one edge from Pred to BB!");
00979 
00980       // Add entries for all the phis.
00981       BasicBlock::iterator PNI = BB->begin();
00982       do {
00983         unsigned AllocaNo = PhiToAllocaMap[APN];
00984 
00985         // Add N incoming values to the PHI node.
00986         for (unsigned i = 0; i != NumEdges; ++i)
00987           APN->addIncoming(IncomingVals[AllocaNo], Pred);
00988 
00989         // The currently active variable for this block is now the PHI.
00990         IncomingVals[AllocaNo] = APN;
00991 
00992         // Get the next phi node.
00993         ++PNI;
00994         APN = dyn_cast<PHINode>(PNI);
00995         if (APN == 0)
00996           break;
00997 
00998         // Verify that it is missing entries.  If not, it is not being inserted
00999         // by this mem2reg invocation so we want to ignore it.
01000       } while (APN->getNumOperands() == NewPHINumOperands);
01001     }
01002   }
01003 
01004   // Don't revisit blocks.
01005   if (!Visited.insert(BB))
01006     return;
01007 
01008   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
01009     Instruction *I = II++; // get the instruction, increment iterator
01010 
01011     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
01012       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
01013       if (!Src)
01014         continue;
01015 
01016       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
01017       if (AI == AllocaLookup.end())
01018         continue;
01019 
01020       Value *V = IncomingVals[AI->second];
01021 
01022       // Anything using the load now uses the current value.
01023       LI->replaceAllUsesWith(V);
01024       if (AST && LI->getType()->isPointerTy())
01025         AST->deleteValue(LI);
01026       BB->getInstList().erase(LI);
01027     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
01028       // Delete this instruction and mark the name as the current holder of the
01029       // value
01030       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
01031       if (!Dest)
01032         continue;
01033 
01034       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
01035       if (ai == AllocaLookup.end())
01036         continue;
01037 
01038       // what value were we writing?
01039       IncomingVals[ai->second] = SI->getOperand(0);
01040       // Record debuginfo for the store before removing it.
01041       if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
01042         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01043       BB->getInstList().erase(SI);
01044     }
01045   }
01046 
01047   // 'Recurse' to our successors.
01048   succ_iterator I = succ_begin(BB), E = succ_end(BB);
01049   if (I == E)
01050     return;
01051 
01052   // Keep track of the successors so we don't visit the same successor twice
01053   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
01054 
01055   // Handle the first successor without using the worklist.
01056   VisitedSuccs.insert(*I);
01057   Pred = BB;
01058   BB = *I;
01059   ++I;
01060 
01061   for (; I != E; ++I)
01062     if (VisitedSuccs.insert(*I))
01063       Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
01064 
01065   goto NextIteration;
01066 }
01067 
01068 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
01069                            AliasSetTracker *AST) {
01070   // If there is nothing to do, bail out...
01071   if (Allocas.empty())
01072     return;
01073 
01074   PromoteMem2Reg(Allocas, DT, AST).run();
01075 }