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