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