LLVM  mainline
DeadStoreElimination.cpp
Go to the documentation of this file.
00001 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
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 implements a trivial dead store elimination that only considers
00011 // basic-block local redundant stores.
00012 //
00013 // FIXME: This should eventually be extended to be a post-dominator tree
00014 // traversal.  Doing so would be pretty trivial.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/Transforms/Scalar.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SetVector.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/AliasAnalysis.h"
00023 #include "llvm/Analysis/CaptureTracking.h"
00024 #include "llvm/Analysis/MemoryBuiltins.h"
00025 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00026 #include "llvm/Analysis/TargetLibraryInfo.h"
00027 #include "llvm/Analysis/ValueTracking.h"
00028 #include "llvm/IR/Constants.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/Dominators.h"
00031 #include "llvm/IR/Function.h"
00032 #include "llvm/IR/GlobalVariable.h"
00033 #include "llvm/IR/Instructions.h"
00034 #include "llvm/IR/IntrinsicInst.h"
00035 #include "llvm/Pass.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 #include "llvm/Transforms/Utils/Local.h"
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "dse"
00042 
00043 STATISTIC(NumFastStores, "Number of stores deleted");
00044 STATISTIC(NumFastOther , "Number of other instrs removed");
00045 
00046 namespace {
00047   struct DSE : public FunctionPass {
00048     AliasAnalysis *AA;
00049     MemoryDependenceAnalysis *MD;
00050     DominatorTree *DT;
00051     const TargetLibraryInfo *TLI;
00052 
00053     static char ID; // Pass identification, replacement for typeid
00054     DSE() : FunctionPass(ID), AA(nullptr), MD(nullptr), DT(nullptr) {
00055       initializeDSEPass(*PassRegistry::getPassRegistry());
00056     }
00057 
00058     bool runOnFunction(Function &F) override {
00059       if (skipOptnoneFunction(F))
00060         return false;
00061 
00062       AA = &getAnalysis<AliasAnalysis>();
00063       MD = &getAnalysis<MemoryDependenceAnalysis>();
00064       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00065       TLI = AA->getTargetLibraryInfo();
00066 
00067       bool Changed = false;
00068       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
00069         // Only check non-dead blocks.  Dead blocks may have strange pointer
00070         // cycles that will confuse alias analysis.
00071         if (DT->isReachableFromEntry(I))
00072           Changed |= runOnBasicBlock(*I);
00073 
00074       AA = nullptr; MD = nullptr; DT = nullptr;
00075       return Changed;
00076     }
00077 
00078     bool runOnBasicBlock(BasicBlock &BB);
00079     bool HandleFree(CallInst *F);
00080     bool handleEndBlock(BasicBlock &BB);
00081     void RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
00082                                SmallSetVector<Value *, 16> &DeadStackObjects,
00083                                const DataLayout &DL);
00084 
00085     void getAnalysisUsage(AnalysisUsage &AU) const override {
00086       AU.setPreservesCFG();
00087       AU.addRequired<DominatorTreeWrapperPass>();
00088       AU.addRequired<AliasAnalysis>();
00089       AU.addRequired<MemoryDependenceAnalysis>();
00090       AU.addPreserved<AliasAnalysis>();
00091       AU.addPreserved<DominatorTreeWrapperPass>();
00092       AU.addPreserved<MemoryDependenceAnalysis>();
00093     }
00094   };
00095 }
00096 
00097 char DSE::ID = 0;
00098 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
00099 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00100 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00101 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00102 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
00103 
00104 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
00105 
00106 //===----------------------------------------------------------------------===//
00107 // Helper functions
00108 //===----------------------------------------------------------------------===//
00109 
00110 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
00111 /// and zero out all the operands of this instruction.  If any of them become
00112 /// dead, delete them and the computation tree that feeds them.
00113 ///
00114 /// If ValueSet is non-null, remove any deleted instructions from it as well.
00115 ///
00116 static void DeleteDeadInstruction(Instruction *I,
00117                                MemoryDependenceAnalysis &MD,
00118                                const TargetLibraryInfo *TLI,
00119                                SmallSetVector<Value*, 16> *ValueSet = nullptr) {
00120   SmallVector<Instruction*, 32> NowDeadInsts;
00121 
00122   NowDeadInsts.push_back(I);
00123   --NumFastOther;
00124 
00125   // Before we touch this instruction, remove it from memdep!
00126   do {
00127     Instruction *DeadInst = NowDeadInsts.pop_back_val();
00128     ++NumFastOther;
00129 
00130     // This instruction is dead, zap it, in stages.  Start by removing it from
00131     // MemDep, which needs to know the operands and needs it to be in the
00132     // function.
00133     MD.removeInstruction(DeadInst);
00134 
00135     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
00136       Value *Op = DeadInst->getOperand(op);
00137       DeadInst->setOperand(op, nullptr);
00138 
00139       // If this operand just became dead, add it to the NowDeadInsts list.
00140       if (!Op->use_empty()) continue;
00141 
00142       if (Instruction *OpI = dyn_cast<Instruction>(Op))
00143         if (isInstructionTriviallyDead(OpI, TLI))
00144           NowDeadInsts.push_back(OpI);
00145     }
00146 
00147     DeadInst->eraseFromParent();
00148 
00149     if (ValueSet) ValueSet->remove(DeadInst);
00150   } while (!NowDeadInsts.empty());
00151 }
00152 
00153 
00154 /// hasMemoryWrite - Does this instruction write some memory?  This only returns
00155 /// true for things that we can analyze with other helpers below.
00156 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo *TLI) {
00157   if (isa<StoreInst>(I))
00158     return true;
00159   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00160     switch (II->getIntrinsicID()) {
00161     default:
00162       return false;
00163     case Intrinsic::memset:
00164     case Intrinsic::memmove:
00165     case Intrinsic::memcpy:
00166     case Intrinsic::init_trampoline:
00167     case Intrinsic::lifetime_end:
00168       return true;
00169     }
00170   }
00171   if (auto CS = CallSite(I)) {
00172     if (Function *F = CS.getCalledFunction()) {
00173       if (TLI && TLI->has(LibFunc::strcpy) &&
00174           F->getName() == TLI->getName(LibFunc::strcpy)) {
00175         return true;
00176       }
00177       if (TLI && TLI->has(LibFunc::strncpy) &&
00178           F->getName() == TLI->getName(LibFunc::strncpy)) {
00179         return true;
00180       }
00181       if (TLI && TLI->has(LibFunc::strcat) &&
00182           F->getName() == TLI->getName(LibFunc::strcat)) {
00183         return true;
00184       }
00185       if (TLI && TLI->has(LibFunc::strncat) &&
00186           F->getName() == TLI->getName(LibFunc::strncat)) {
00187         return true;
00188       }
00189     }
00190   }
00191   return false;
00192 }
00193 
00194 /// getLocForWrite - Return a Location stored to by the specified instruction.
00195 /// If isRemovable returns true, this function and getLocForRead completely
00196 /// describe the memory operations for this instruction.
00197 static AliasAnalysis::Location
00198 getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
00199   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00200     return AA.getLocation(SI);
00201 
00202   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
00203     // memcpy/memmove/memset.
00204     AliasAnalysis::Location Loc = AA.getLocationForDest(MI);
00205     return Loc;
00206   }
00207 
00208   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
00209   if (!II) return AliasAnalysis::Location();
00210 
00211   switch (II->getIntrinsicID()) {
00212   default: return AliasAnalysis::Location(); // Unhandled intrinsic.
00213   case Intrinsic::init_trampoline:
00214     // FIXME: We don't know the size of the trampoline, so we can't really
00215     // handle it here.
00216     return AliasAnalysis::Location(II->getArgOperand(0));
00217   case Intrinsic::lifetime_end: {
00218     uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
00219     return AliasAnalysis::Location(II->getArgOperand(1), Len);
00220   }
00221   }
00222 }
00223 
00224 /// getLocForRead - Return the location read by the specified "hasMemoryWrite"
00225 /// instruction if any.
00226 static AliasAnalysis::Location
00227 getLocForRead(Instruction *Inst, AliasAnalysis &AA) {
00228   assert(hasMemoryWrite(Inst, AA.getTargetLibraryInfo()) &&
00229          "Unknown instruction case");
00230 
00231   // The only instructions that both read and write are the mem transfer
00232   // instructions (memcpy/memmove).
00233   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
00234     return AA.getLocationForSource(MTI);
00235   return AliasAnalysis::Location();
00236 }
00237 
00238 
00239 /// isRemovable - If the value of this instruction and the memory it writes to
00240 /// is unused, may we delete this instruction?
00241 static bool isRemovable(Instruction *I) {
00242   // Don't remove volatile/atomic stores.
00243   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00244     return SI->isUnordered();
00245 
00246   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00247     switch (II->getIntrinsicID()) {
00248     default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
00249     case Intrinsic::lifetime_end:
00250       // Never remove dead lifetime_end's, e.g. because it is followed by a
00251       // free.
00252       return false;
00253     case Intrinsic::init_trampoline:
00254       // Always safe to remove init_trampoline.
00255       return true;
00256 
00257     case Intrinsic::memset:
00258     case Intrinsic::memmove:
00259     case Intrinsic::memcpy:
00260       // Don't remove volatile memory intrinsics.
00261       return !cast<MemIntrinsic>(II)->isVolatile();
00262     }
00263   }
00264 
00265   if (auto CS = CallSite(I))
00266     return CS.getInstruction()->use_empty();
00267 
00268   return false;
00269 }
00270 
00271 
00272 /// isShortenable - Returns true if this instruction can be safely shortened in
00273 /// length.
00274 static bool isShortenable(Instruction *I) {
00275   // Don't shorten stores for now
00276   if (isa<StoreInst>(I))
00277     return false;
00278 
00279   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00280     switch (II->getIntrinsicID()) {
00281       default: return false;
00282       case Intrinsic::memset:
00283       case Intrinsic::memcpy:
00284         // Do shorten memory intrinsics.
00285         return true;
00286     }
00287   }
00288 
00289   // Don't shorten libcalls calls for now.
00290 
00291   return false;
00292 }
00293 
00294 /// getStoredPointerOperand - Return the pointer that is being written to.
00295 static Value *getStoredPointerOperand(Instruction *I) {
00296   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00297     return SI->getPointerOperand();
00298   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
00299     return MI->getDest();
00300 
00301   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00302     switch (II->getIntrinsicID()) {
00303     default: llvm_unreachable("Unexpected intrinsic!");
00304     case Intrinsic::init_trampoline:
00305       return II->getArgOperand(0);
00306     }
00307   }
00308 
00309   CallSite CS(I);
00310   // All the supported functions so far happen to have dest as their first
00311   // argument.
00312   return CS.getArgument(0);
00313 }
00314 
00315 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
00316                                const TargetLibraryInfo *TLI) {
00317   uint64_t Size;
00318   if (getObjectSize(V, Size, DL, TLI))
00319     return Size;
00320   return AliasAnalysis::UnknownSize;
00321 }
00322 
00323 namespace {
00324   enum OverwriteResult
00325   {
00326     OverwriteComplete,
00327     OverwriteEnd,
00328     OverwriteUnknown
00329   };
00330 }
00331 
00332 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location
00333 /// completely overwrites a store to the 'Earlier' location.
00334 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely
00335 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined
00336 static OverwriteResult isOverwrite(const AliasAnalysis::Location &Later,
00337                                    const AliasAnalysis::Location &Earlier,
00338                                    const DataLayout &DL,
00339                                    const TargetLibraryInfo *TLI,
00340                                    int64_t &EarlierOff, int64_t &LaterOff) {
00341   const Value *P1 = Earlier.Ptr->stripPointerCasts();
00342   const Value *P2 = Later.Ptr->stripPointerCasts();
00343 
00344   // If the start pointers are the same, we just have to compare sizes to see if
00345   // the later store was larger than the earlier store.
00346   if (P1 == P2) {
00347     // If we don't know the sizes of either access, then we can't do a
00348     // comparison.
00349     if (Later.Size == AliasAnalysis::UnknownSize ||
00350         Earlier.Size == AliasAnalysis::UnknownSize)
00351       return OverwriteUnknown;
00352 
00353     // Make sure that the Later size is >= the Earlier size.
00354     if (Later.Size >= Earlier.Size)
00355       return OverwriteComplete;
00356   }
00357 
00358   // Otherwise, we have to have size information, and the later store has to be
00359   // larger than the earlier one.
00360   if (Later.Size == AliasAnalysis::UnknownSize ||
00361       Earlier.Size == AliasAnalysis::UnknownSize)
00362     return OverwriteUnknown;
00363 
00364   // Check to see if the later store is to the entire object (either a global,
00365   // an alloca, or a byval/inalloca argument).  If so, then it clearly
00366   // overwrites any other store to the same object.
00367   const Value *UO1 = GetUnderlyingObject(P1, DL),
00368               *UO2 = GetUnderlyingObject(P2, DL);
00369 
00370   // If we can't resolve the same pointers to the same object, then we can't
00371   // analyze them at all.
00372   if (UO1 != UO2)
00373     return OverwriteUnknown;
00374 
00375   // If the "Later" store is to a recognizable object, get its size.
00376   uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
00377   if (ObjectSize != AliasAnalysis::UnknownSize)
00378     if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
00379       return OverwriteComplete;
00380 
00381   // Okay, we have stores to two completely different pointers.  Try to
00382   // decompose the pointer into a "base + constant_offset" form.  If the base
00383   // pointers are equal, then we can reason about the two stores.
00384   EarlierOff = 0;
00385   LaterOff = 0;
00386   const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
00387   const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
00388 
00389   // If the base pointers still differ, we have two completely different stores.
00390   if (BP1 != BP2)
00391     return OverwriteUnknown;
00392 
00393   // The later store completely overlaps the earlier store if:
00394   //
00395   // 1. Both start at the same offset and the later one's size is greater than
00396   //    or equal to the earlier one's, or
00397   //
00398   //      |--earlier--|
00399   //      |--   later   --|
00400   //
00401   // 2. The earlier store has an offset greater than the later offset, but which
00402   //    still lies completely within the later store.
00403   //
00404   //        |--earlier--|
00405   //    |-----  later  ------|
00406   //
00407   // We have to be careful here as *Off is signed while *.Size is unsigned.
00408   if (EarlierOff >= LaterOff &&
00409       Later.Size >= Earlier.Size &&
00410       uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
00411     return OverwriteComplete;
00412 
00413   // The other interesting case is if the later store overwrites the end of
00414   // the earlier store
00415   //
00416   //      |--earlier--|
00417   //                |--   later   --|
00418   //
00419   // In this case we may want to trim the size of earlier to avoid generating
00420   // writes to addresses which will definitely be overwritten later
00421   if (LaterOff > EarlierOff &&
00422       LaterOff < int64_t(EarlierOff + Earlier.Size) &&
00423       int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
00424     return OverwriteEnd;
00425 
00426   // Otherwise, they don't completely overlap.
00427   return OverwriteUnknown;
00428 }
00429 
00430 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a
00431 /// memory region into an identical pointer) then it doesn't actually make its
00432 /// input dead in the traditional sense.  Consider this case:
00433 ///
00434 ///   memcpy(A <- B)
00435 ///   memcpy(A <- A)
00436 ///
00437 /// In this case, the second store to A does not make the first store to A dead.
00438 /// The usual situation isn't an explicit A<-A store like this (which can be
00439 /// trivially removed) but a case where two pointers may alias.
00440 ///
00441 /// This function detects when it is unsafe to remove a dependent instruction
00442 /// because the DSE inducing instruction may be a self-read.
00443 static bool isPossibleSelfRead(Instruction *Inst,
00444                                const AliasAnalysis::Location &InstStoreLoc,
00445                                Instruction *DepWrite, AliasAnalysis &AA) {
00446   // Self reads can only happen for instructions that read memory.  Get the
00447   // location read.
00448   AliasAnalysis::Location InstReadLoc = getLocForRead(Inst, AA);
00449   if (!InstReadLoc.Ptr) return false;  // Not a reading instruction.
00450 
00451   // If the read and written loc obviously don't alias, it isn't a read.
00452   if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
00453 
00454   // Okay, 'Inst' may copy over itself.  However, we can still remove a the
00455   // DepWrite instruction if we can prove that it reads from the same location
00456   // as Inst.  This handles useful cases like:
00457   //   memcpy(A <- B)
00458   //   memcpy(A <- B)
00459   // Here we don't know if A/B may alias, but we do know that B/B are must
00460   // aliases, so removing the first memcpy is safe (assuming it writes <= #
00461   // bytes as the second one.
00462   AliasAnalysis::Location DepReadLoc = getLocForRead(DepWrite, AA);
00463 
00464   if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
00465     return false;
00466 
00467   // If DepWrite doesn't read memory or if we can't prove it is a must alias,
00468   // then it can't be considered dead.
00469   return true;
00470 }
00471 
00472 
00473 //===----------------------------------------------------------------------===//
00474 // DSE Pass
00475 //===----------------------------------------------------------------------===//
00476 
00477 bool DSE::runOnBasicBlock(BasicBlock &BB) {
00478   bool MadeChange = false;
00479 
00480   // Do a top-down walk on the BB.
00481   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
00482     Instruction *Inst = BBI++;
00483 
00484     // Handle 'free' calls specially.
00485     if (CallInst *F = isFreeCall(Inst, TLI)) {
00486       MadeChange |= HandleFree(F);
00487       continue;
00488     }
00489 
00490     // If we find something that writes memory, get its memory dependence.
00491     if (!hasMemoryWrite(Inst, TLI))
00492       continue;
00493 
00494     MemDepResult InstDep = MD->getDependency(Inst);
00495 
00496     // Ignore any store where we can't find a local dependence.
00497     // FIXME: cross-block DSE would be fun. :)
00498     if (!InstDep.isDef() && !InstDep.isClobber())
00499       continue;
00500 
00501     // If we're storing the same value back to a pointer that we just
00502     // loaded from, then the store can be removed.
00503     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00504       if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
00505         if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
00506             SI->getOperand(0) == DepLoad && isRemovable(SI)) {
00507           DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n  "
00508                        << "LOAD: " << *DepLoad << "\n  STORE: " << *SI << '\n');
00509 
00510           // DeleteDeadInstruction can delete the current instruction.  Save BBI
00511           // in case we need it.
00512           WeakVH NextInst(BBI);
00513 
00514           DeleteDeadInstruction(SI, *MD, TLI);
00515 
00516           if (!NextInst)  // Next instruction deleted.
00517             BBI = BB.begin();
00518           else if (BBI != BB.begin())  // Revisit this instruction if possible.
00519             --BBI;
00520           ++NumFastStores;
00521           MadeChange = true;
00522           continue;
00523         }
00524       }
00525     }
00526 
00527     // Figure out what location is being stored to.
00528     AliasAnalysis::Location Loc = getLocForWrite(Inst, *AA);
00529 
00530     // If we didn't get a useful location, fail.
00531     if (!Loc.Ptr)
00532       continue;
00533 
00534     while (InstDep.isDef() || InstDep.isClobber()) {
00535       // Get the memory clobbered by the instruction we depend on.  MemDep will
00536       // skip any instructions that 'Loc' clearly doesn't interact with.  If we
00537       // end up depending on a may- or must-aliased load, then we can't optimize
00538       // away the store and we bail out.  However, if we depend on on something
00539       // that overwrites the memory location we *can* potentially optimize it.
00540       //
00541       // Find out what memory location the dependent instruction stores.
00542       Instruction *DepWrite = InstDep.getInst();
00543       AliasAnalysis::Location DepLoc = getLocForWrite(DepWrite, *AA);
00544       // If we didn't get a useful location, or if it isn't a size, bail out.
00545       if (!DepLoc.Ptr)
00546         break;
00547 
00548       // If we find a write that is a) removable (i.e., non-volatile), b) is
00549       // completely obliterated by the store to 'Loc', and c) which we know that
00550       // 'Inst' doesn't load from, then we can remove it.
00551       if (isRemovable(DepWrite) &&
00552           !isPossibleSelfRead(Inst, Loc, DepWrite, *AA)) {
00553         int64_t InstWriteOffset, DepWriteOffset;
00554         const DataLayout &DL = BB.getModule()->getDataLayout();
00555         OverwriteResult OR =
00556             isOverwrite(Loc, DepLoc, DL, AA->getTargetLibraryInfo(),
00557                         DepWriteOffset, InstWriteOffset);
00558         if (OR == OverwriteComplete) {
00559           DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: "
00560                 << *DepWrite << "\n  KILLER: " << *Inst << '\n');
00561 
00562           // Delete the store and now-dead instructions that feed it.
00563           DeleteDeadInstruction(DepWrite, *MD, TLI);
00564           ++NumFastStores;
00565           MadeChange = true;
00566 
00567           // DeleteDeadInstruction can delete the current instruction in loop
00568           // cases, reset BBI.
00569           BBI = Inst;
00570           if (BBI != BB.begin())
00571             --BBI;
00572           break;
00573         } else if (OR == OverwriteEnd && isShortenable(DepWrite)) {
00574           // TODO: base this on the target vector size so that if the earlier
00575           // store was too small to get vector writes anyway then its likely
00576           // a good idea to shorten it
00577           // Power of 2 vector writes are probably always a bad idea to optimize
00578           // as any store/memset/memcpy is likely using vector instructions so
00579           // shortening it to not vector size is likely to be slower
00580           MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
00581           unsigned DepWriteAlign = DepIntrinsic->getAlignment();
00582           if (llvm::isPowerOf2_64(InstWriteOffset) ||
00583               ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
00584 
00585             DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW END: "
00586                   << *DepWrite << "\n  KILLER (offset "
00587                   << InstWriteOffset << ", "
00588                   << DepLoc.Size << ")"
00589                   << *Inst << '\n');
00590 
00591             Value* DepWriteLength = DepIntrinsic->getLength();
00592             Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(),
00593                                                     InstWriteOffset -
00594                                                     DepWriteOffset);
00595             DepIntrinsic->setLength(TrimmedLength);
00596             MadeChange = true;
00597           }
00598         }
00599       }
00600 
00601       // If this is a may-aliased store that is clobbering the store value, we
00602       // can keep searching past it for another must-aliased pointer that stores
00603       // to the same location.  For example, in:
00604       //   store -> P
00605       //   store -> Q
00606       //   store -> P
00607       // we can remove the first store to P even though we don't know if P and Q
00608       // alias.
00609       if (DepWrite == &BB.front()) break;
00610 
00611       // Can't look past this instruction if it might read 'Loc'.
00612       if (AA->getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
00613         break;
00614 
00615       InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
00616     }
00617   }
00618 
00619   // If this block ends in a return, unwind, or unreachable, all allocas are
00620   // dead at its end, which means stores to them are also dead.
00621   if (BB.getTerminator()->getNumSuccessors() == 0)
00622     MadeChange |= handleEndBlock(BB);
00623 
00624   return MadeChange;
00625 }
00626 
00627 /// Find all blocks that will unconditionally lead to the block BB and append
00628 /// them to F.
00629 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
00630                                    BasicBlock *BB, DominatorTree *DT) {
00631   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
00632     BasicBlock *Pred = *I;
00633     if (Pred == BB) continue;
00634     TerminatorInst *PredTI = Pred->getTerminator();
00635     if (PredTI->getNumSuccessors() != 1)
00636       continue;
00637 
00638     if (DT->isReachableFromEntry(Pred))
00639       Blocks.push_back(Pred);
00640   }
00641 }
00642 
00643 /// HandleFree - Handle frees of entire structures whose dependency is a store
00644 /// to a field of that structure.
00645 bool DSE::HandleFree(CallInst *F) {
00646   bool MadeChange = false;
00647 
00648   AliasAnalysis::Location Loc = AliasAnalysis::Location(F->getOperand(0));
00649   SmallVector<BasicBlock *, 16> Blocks;
00650   Blocks.push_back(F->getParent());
00651   const DataLayout &DL = F->getModule()->getDataLayout();
00652 
00653   while (!Blocks.empty()) {
00654     BasicBlock *BB = Blocks.pop_back_val();
00655     Instruction *InstPt = BB->getTerminator();
00656     if (BB == F->getParent()) InstPt = F;
00657 
00658     MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
00659     while (Dep.isDef() || Dep.isClobber()) {
00660       Instruction *Dependency = Dep.getInst();
00661       if (!hasMemoryWrite(Dependency, TLI) || !isRemovable(Dependency))
00662         break;
00663 
00664       Value *DepPointer =
00665           GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
00666 
00667       // Check for aliasing.
00668       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
00669         break;
00670 
00671       Instruction *Next = std::next(BasicBlock::iterator(Dependency));
00672 
00673       // DCE instructions only used to calculate that store
00674       DeleteDeadInstruction(Dependency, *MD, TLI);
00675       ++NumFastStores;
00676       MadeChange = true;
00677 
00678       // Inst's old Dependency is now deleted. Compute the next dependency,
00679       // which may also be dead, as in
00680       //    s[0] = 0;
00681       //    s[1] = 0; // This has just been deleted.
00682       //    free(s);
00683       Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
00684     }
00685 
00686     if (Dep.isNonLocal())
00687       FindUnconditionalPreds(Blocks, BB, DT);
00688   }
00689 
00690   return MadeChange;
00691 }
00692 
00693 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
00694 /// function end block.  Ex:
00695 /// %A = alloca i32
00696 /// ...
00697 /// store i32 1, i32* %A
00698 /// ret void
00699 bool DSE::handleEndBlock(BasicBlock &BB) {
00700   bool MadeChange = false;
00701 
00702   // Keep track of all of the stack objects that are dead at the end of the
00703   // function.
00704   SmallSetVector<Value*, 16> DeadStackObjects;
00705 
00706   // Find all of the alloca'd pointers in the entry block.
00707   BasicBlock *Entry = BB.getParent()->begin();
00708   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
00709     if (isa<AllocaInst>(I))
00710       DeadStackObjects.insert(I);
00711 
00712     // Okay, so these are dead heap objects, but if the pointer never escapes
00713     // then it's leaked by this function anyways.
00714     else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
00715       DeadStackObjects.insert(I);
00716   }
00717 
00718   // Treat byval or inalloca arguments the same, stores to them are dead at the
00719   // end of the function.
00720   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
00721        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
00722     if (AI->hasByValOrInAllocaAttr())
00723       DeadStackObjects.insert(AI);
00724 
00725   const DataLayout &DL = BB.getModule()->getDataLayout();
00726 
00727   // Scan the basic block backwards
00728   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
00729     --BBI;
00730 
00731     // If we find a store, check to see if it points into a dead stack value.
00732     if (hasMemoryWrite(BBI, TLI) && isRemovable(BBI)) {
00733       // See through pointer-to-pointer bitcasts
00734       SmallVector<Value *, 4> Pointers;
00735       GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers, DL);
00736 
00737       // Stores to stack values are valid candidates for removal.
00738       bool AllDead = true;
00739       for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
00740            E = Pointers.end(); I != E; ++I)
00741         if (!DeadStackObjects.count(*I)) {
00742           AllDead = false;
00743           break;
00744         }
00745 
00746       if (AllDead) {
00747         Instruction *Dead = BBI++;
00748 
00749         DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
00750                      << *Dead << "\n  Objects: ";
00751               for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
00752                    E = Pointers.end(); I != E; ++I) {
00753                 dbgs() << **I;
00754                 if (std::next(I) != E)
00755                   dbgs() << ", ";
00756               }
00757               dbgs() << '\n');
00758 
00759         // DCE instructions only used to calculate that store.
00760         DeleteDeadInstruction(Dead, *MD, TLI, &DeadStackObjects);
00761         ++NumFastStores;
00762         MadeChange = true;
00763         continue;
00764       }
00765     }
00766 
00767     // Remove any dead non-memory-mutating instructions.
00768     if (isInstructionTriviallyDead(BBI, TLI)) {
00769       Instruction *Inst = BBI++;
00770       DeleteDeadInstruction(Inst, *MD, TLI, &DeadStackObjects);
00771       ++NumFastOther;
00772       MadeChange = true;
00773       continue;
00774     }
00775 
00776     if (isa<AllocaInst>(BBI)) {
00777       // Remove allocas from the list of dead stack objects; there can't be
00778       // any references before the definition.
00779       DeadStackObjects.remove(BBI);
00780       continue;
00781     }
00782 
00783     if (auto CS = CallSite(BBI)) {
00784       // Remove allocation function calls from the list of dead stack objects; 
00785       // there can't be any references before the definition.
00786       if (isAllocLikeFn(BBI, TLI))
00787         DeadStackObjects.remove(BBI);
00788 
00789       // If this call does not access memory, it can't be loading any of our
00790       // pointers.
00791       if (AA->doesNotAccessMemory(CS))
00792         continue;
00793 
00794       // If the call might load from any of our allocas, then any store above
00795       // the call is live.
00796       DeadStackObjects.remove_if([&](Value *I) {
00797         // See if the call site touches the value.
00798         AliasAnalysis::ModRefResult A = AA->getModRefInfo(
00799             CS, I, getPointerSize(I, DL, AA->getTargetLibraryInfo()));
00800 
00801         return A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref;
00802       });
00803 
00804       // If all of the allocas were clobbered by the call then we're not going
00805       // to find anything else to process.
00806       if (DeadStackObjects.empty())
00807         break;
00808 
00809       continue;
00810     }
00811 
00812     AliasAnalysis::Location LoadedLoc;
00813 
00814     // If we encounter a use of the pointer, it is no longer considered dead
00815     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
00816       if (!L->isUnordered()) // Be conservative with atomic/volatile load
00817         break;
00818       LoadedLoc = AA->getLocation(L);
00819     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
00820       LoadedLoc = AA->getLocation(V);
00821     } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
00822       LoadedLoc = AA->getLocationForSource(MTI);
00823     } else if (!BBI->mayReadFromMemory()) {
00824       // Instruction doesn't read memory.  Note that stores that weren't removed
00825       // above will hit this case.
00826       continue;
00827     } else {
00828       // Unknown inst; assume it clobbers everything.
00829       break;
00830     }
00831 
00832     // Remove any allocas from the DeadPointer set that are loaded, as this
00833     // makes any stores above the access live.
00834     RemoveAccessedObjects(LoadedLoc, DeadStackObjects, DL);
00835 
00836     // If all of the allocas were clobbered by the access then we're not going
00837     // to find anything else to process.
00838     if (DeadStackObjects.empty())
00839       break;
00840   }
00841 
00842   return MadeChange;
00843 }
00844 
00845 /// RemoveAccessedObjects - Check to see if the specified location may alias any
00846 /// of the stack objects in the DeadStackObjects set.  If so, they become live
00847 /// because the location is being loaded.
00848 void DSE::RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
00849                                 SmallSetVector<Value *, 16> &DeadStackObjects,
00850                                 const DataLayout &DL) {
00851   const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
00852 
00853   // A constant can't be in the dead pointer set.
00854   if (isa<Constant>(UnderlyingPointer))
00855     return;
00856 
00857   // If the kill pointer can be easily reduced to an alloca, don't bother doing
00858   // extraneous AA queries.
00859   if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
00860     DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
00861     return;
00862   }
00863 
00864   // Remove objects that could alias LoadedLoc.
00865   DeadStackObjects.remove_if([&](Value *I) {
00866     // See if the loaded location could alias the stack location.
00867     AliasAnalysis::Location StackLoc(
00868         I, getPointerSize(I, DL, AA->getTargetLibraryInfo()));
00869     return !AA->isNoAlias(StackLoc, LoadedLoc);
00870   });
00871 }