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