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