1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a trivial dead store elimination that only considers
11 // basic-block local redundant stores.
13 // FIXME: This should eventually be extended to be a post-dominator tree
14 // traversal. Doing so would be pretty trivial.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/CFG.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
28 #include "llvm/Analysis/PostDominators.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Utils/Local.h"
44 #define DEBUG_TYPE "dse"
46 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
47 STATISTIC(NumFastStores, "Number of stores deleted");
48 STATISTIC(NumCrossBlockStores, "Number of cross block stores deleted");
49 STATISTIC(NumFastOther , "Number of other instrs removed");
52 struct DSE : public FunctionPass {
54 MemoryDependenceAnalysis *MD;
56 PostDominatorTree *PDT;
57 const TargetLibraryInfo *TLI;
58 SmallVector<SmallVector<StoreInst *, 8>, 16> Candidates;
59 SetVector<StoreInst *> DeadStores;
60 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 32>
62 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> BackEdgesMap;
63 static char ID; // Pass identification, replacement for typeid
65 : FunctionPass(ID), AA(nullptr), MD(nullptr), DT(nullptr),
67 initializeDSEPass(*PassRegistry::getPassRegistry());
69 // Return all stores in a given BasicBlock.
70 SmallVector<StoreInst *, 8> getStores(BasicBlock *BB) {
71 SmallVector<StoreInst *, 8> VecStores;
72 for (auto &BI : *BB) {
73 if (StoreInst *SI = dyn_cast<StoreInst>(&BI))
74 VecStores.push_back(SI);
79 // Get dfs in/out on the PDT and populate Candidates store list which
80 // is used to find potential dead stores for a given block
81 void populateCandidateStores(Function &F) {
83 DomTreeNode *DTNode = PDT->getNode(&I);
86 int DFSIn = DTNode->getDFSNumIn();
87 SmallVector<StoreInst *, 8> VecStores = getStores(&I);
88 Candidates[DFSIn] = VecStores;
92 bool runOnFunction(Function &F) override {
93 if (skipOptnoneFunction(F))
96 AA = &getAnalysis<AliasAnalysis>();
97 MD = &getAnalysis<MemoryDependenceAnalysis>();
98 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
99 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
100 PDT = &getAnalysis<PostDominatorTree>();
101 if (PDT->getRootNode()) {
102 int Count = PDT->getRootNode()->getDFSNumOut();
103 SmallVector<StoreInst *, 8> VecStores;
104 Candidates.resize(Count + 1);
105 Candidates.assign(Count + 1, VecStores);
107 // If we have more than 1 block try to populate candidate store.
109 populateCandidateStores(F);
110 FindFunctionBackedges(F, BackEdges);
111 for (auto I : BackEdges)
112 BackEdgesMap.insert(I);
115 bool Changed = false;
116 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
117 // Only check non-dead blocks. Dead blocks may have strange pointer
118 // cycles that will confuse alias analysis.
119 if (DT->isReachableFromEntry(I))
120 Changed |= runOnBasicBlock(*I);
122 AA = nullptr; MD = nullptr; DT = nullptr;
126 bool runOnBasicBlock(BasicBlock &BB);
127 bool MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI);
128 bool HandleFree(CallInst *F);
129 bool handleEndBlock(BasicBlock &BB);
130 void RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
131 SmallSetVector<Value *, 16> &DeadStackObjects,
132 const DataLayout &DL);
133 void handleNonLocalStoreDeletion(StoreInst *SI, BasicBlock::iterator &BBI,
134 BasicBlock &CurBlock);
135 bool isSafeCandidateForDeletion(BasicBlock *SrcBlock, BasicBlock *SinkBlock,
137 void DeleteDeadInstruction(Instruction *I, MemoryDependenceAnalysis &MD,
138 const TargetLibraryInfo &TLI,
139 SmallSetVector<Value *, 16> *ValueSet = nullptr);
140 void getAnalysisUsage(AnalysisUsage &AU) const override {
141 AU.setPreservesCFG();
142 AU.addRequired<DominatorTreeWrapperPass>();
143 AU.addRequired<AliasAnalysis>();
144 AU.addRequired<MemoryDependenceAnalysis>();
145 AU.addRequired<PostDominatorTree>();
146 AU.addRequired<TargetLibraryInfoWrapperPass>();
147 AU.addPreserved<AliasAnalysis>();
148 AU.addPreserved<DominatorTreeWrapperPass>();
149 AU.addPreserved<MemoryDependenceAnalysis>();
150 AU.addPreserved<PostDominatorTree>();
156 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
157 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
158 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
159 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
160 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
161 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
162 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
164 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
166 //===----------------------------------------------------------------------===//
168 //===----------------------------------------------------------------------===//
170 /// hasMemoryWrite - Does this instruction write some memory? This only returns
171 /// true for things that we can analyze with other helpers below.
172 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo &TLI) {
173 if (isa<StoreInst>(I))
175 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
176 switch (II->getIntrinsicID()) {
179 case Intrinsic::memset:
180 case Intrinsic::memmove:
181 case Intrinsic::memcpy:
182 case Intrinsic::init_trampoline:
183 case Intrinsic::lifetime_end:
187 if (auto CS = CallSite(I)) {
188 if (Function *F = CS.getCalledFunction()) {
189 if (TLI.has(LibFunc::strcpy) &&
190 F->getName() == TLI.getName(LibFunc::strcpy)) {
193 if (TLI.has(LibFunc::strncpy) &&
194 F->getName() == TLI.getName(LibFunc::strncpy)) {
197 if (TLI.has(LibFunc::strcat) &&
198 F->getName() == TLI.getName(LibFunc::strcat)) {
201 if (TLI.has(LibFunc::strncat) &&
202 F->getName() == TLI.getName(LibFunc::strncat)) {
210 /// getLocForWrite - Return a Location stored to by the specified instruction.
211 /// If isRemovable returns true, this function and getLocForRead completely
212 /// describe the memory operations for this instruction.
213 static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
214 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
215 return MemoryLocation::get(SI);
217 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
218 // memcpy/memmove/memset.
219 MemoryLocation Loc = MemoryLocation::getForDest(MI);
223 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
225 return MemoryLocation();
227 switch (II->getIntrinsicID()) {
229 return MemoryLocation(); // Unhandled intrinsic.
230 case Intrinsic::init_trampoline:
231 // FIXME: We don't know the size of the trampoline, so we can't really
233 return MemoryLocation(II->getArgOperand(0));
234 case Intrinsic::lifetime_end: {
235 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
236 return MemoryLocation(II->getArgOperand(1), Len);
241 /// getLocForRead - Return the location read by the specified "hasMemoryWrite"
242 /// instruction if any.
243 static MemoryLocation getLocForRead(Instruction *Inst,
244 const TargetLibraryInfo &TLI) {
245 assert(hasMemoryWrite(Inst, TLI) && "Unknown instruction case");
247 // The only instructions that both read and write are the mem transfer
248 // instructions (memcpy/memmove).
249 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
250 return MemoryLocation::getForSource(MTI);
251 return MemoryLocation();
255 /// isRemovable - If the value of this instruction and the memory it writes to
256 /// is unused, may we delete this instruction?
257 static bool isRemovable(Instruction *I) {
258 // Don't remove volatile/atomic stores.
259 if (StoreInst *SI = dyn_cast<StoreInst>(I))
260 return SI->isUnordered();
262 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
263 switch (II->getIntrinsicID()) {
264 default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
265 case Intrinsic::lifetime_end:
266 // Never remove dead lifetime_end's, e.g. because it is followed by a
269 case Intrinsic::init_trampoline:
270 // Always safe to remove init_trampoline.
273 case Intrinsic::memset:
274 case Intrinsic::memmove:
275 case Intrinsic::memcpy:
276 // Don't remove volatile memory intrinsics.
277 return !cast<MemIntrinsic>(II)->isVolatile();
281 if (auto CS = CallSite(I))
282 return CS.getInstruction()->use_empty();
288 /// isShortenable - Returns true if this instruction can be safely shortened in
290 static bool isShortenable(Instruction *I) {
291 // Don't shorten stores for now
292 if (isa<StoreInst>(I))
295 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
296 switch (II->getIntrinsicID()) {
297 default: return false;
298 case Intrinsic::memset:
299 case Intrinsic::memcpy:
300 // Do shorten memory intrinsics.
305 // Don't shorten libcalls calls for now.
310 /// getStoredPointerOperand - Return the pointer that is being written to.
311 static Value *getStoredPointerOperand(Instruction *I) {
312 if (StoreInst *SI = dyn_cast<StoreInst>(I))
313 return SI->getPointerOperand();
314 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
315 return MI->getDest();
317 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
318 switch (II->getIntrinsicID()) {
319 default: llvm_unreachable("Unexpected intrinsic!");
320 case Intrinsic::init_trampoline:
321 return II->getArgOperand(0);
326 // All the supported functions so far happen to have dest as their first
328 return CS.getArgument(0);
331 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
332 const TargetLibraryInfo &TLI) {
334 if (getObjectSize(V, Size, DL, &TLI))
336 return MemoryLocation::UnknownSize;
348 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location
349 /// completely overwrites a store to the 'Earlier' location.
350 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely
351 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined
352 static OverwriteResult isOverwrite(const MemoryLocation &Later,
353 const MemoryLocation &Earlier,
354 const DataLayout &DL,
355 const TargetLibraryInfo &TLI,
356 int64_t &EarlierOff, int64_t &LaterOff) {
357 const Value *P1 = Earlier.Ptr->stripPointerCasts();
358 const Value *P2 = Later.Ptr->stripPointerCasts();
360 // If the start pointers are the same, we just have to compare sizes to see if
361 // the later store was larger than the earlier store.
363 // If we don't know the sizes of either access, then we can't do a
365 if (Later.Size == MemoryLocation::UnknownSize ||
366 Earlier.Size == MemoryLocation::UnknownSize)
367 return OverwriteUnknown;
369 // Make sure that the Later size is >= the Earlier size.
370 if (Later.Size >= Earlier.Size)
371 return OverwriteComplete;
374 // Otherwise, we have to have size information, and the later store has to be
375 // larger than the earlier one.
376 if (Later.Size == MemoryLocation::UnknownSize ||
377 Earlier.Size == MemoryLocation::UnknownSize)
378 return OverwriteUnknown;
380 // Check to see if the later store is to the entire object (either a global,
381 // an alloca, or a byval/inalloca argument). If so, then it clearly
382 // overwrites any other store to the same object.
383 const Value *UO1 = GetUnderlyingObject(P1, DL),
384 *UO2 = GetUnderlyingObject(P2, DL);
386 // If we can't resolve the same pointers to the same object, then we can't
387 // analyze them at all.
389 return OverwriteUnknown;
391 // If the "Later" store is to a recognizable object, get its size.
392 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
393 if (ObjectSize != MemoryLocation::UnknownSize)
394 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
395 return OverwriteComplete;
397 // Okay, we have stores to two completely different pointers. Try to
398 // decompose the pointer into a "base + constant_offset" form. If the base
399 // pointers are equal, then we can reason about the two stores.
402 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
403 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
405 // If the base pointers still differ, we have two completely different stores.
407 return OverwriteUnknown;
409 // The later store completely overlaps the earlier store if:
411 // 1. Both start at the same offset and the later one's size is greater than
412 // or equal to the earlier one's, or
417 // 2. The earlier store has an offset greater than the later offset, but which
418 // still lies completely within the later store.
421 // |----- later ------|
423 // We have to be careful here as *Off is signed while *.Size is unsigned.
424 if (EarlierOff >= LaterOff &&
425 Later.Size >= Earlier.Size &&
426 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
427 return OverwriteComplete;
429 // The other interesting case is if the later store overwrites the end of
435 // In this case we may want to trim the size of earlier to avoid generating
436 // writes to addresses which will definitely be overwritten later
437 if (LaterOff > EarlierOff &&
438 LaterOff < int64_t(EarlierOff + Earlier.Size) &&
439 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
442 // Otherwise, they don't completely overlap.
443 return OverwriteUnknown;
446 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a
447 /// memory region into an identical pointer) then it doesn't actually make its
448 /// input dead in the traditional sense. Consider this case:
453 /// In this case, the second store to A does not make the first store to A dead.
454 /// The usual situation isn't an explicit A<-A store like this (which can be
455 /// trivially removed) but a case where two pointers may alias.
457 /// This function detects when it is unsafe to remove a dependent instruction
458 /// because the DSE inducing instruction may be a self-read.
459 static bool isPossibleSelfRead(Instruction *Inst,
460 const MemoryLocation &InstStoreLoc,
461 Instruction *DepWrite,
462 const TargetLibraryInfo &TLI,
464 // Self reads can only happen for instructions that read memory. Get the
466 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
467 if (!InstReadLoc.Ptr) return false; // Not a reading instruction.
469 // If the read and written loc obviously don't alias, it isn't a read.
470 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
472 // Okay, 'Inst' may copy over itself. However, we can still remove a the
473 // DepWrite instruction if we can prove that it reads from the same location
474 // as Inst. This handles useful cases like:
477 // Here we don't know if A/B may alias, but we do know that B/B are must
478 // aliases, so removing the first memcpy is safe (assuming it writes <= #
479 // bytes as the second one.
480 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
482 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
485 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
486 // then it can't be considered dead.
491 //===----------------------------------------------------------------------===//
493 //===----------------------------------------------------------------------===//
495 bool DSE::runOnBasicBlock(BasicBlock &BB) {
496 bool MadeChange = false;
498 // Do a top-down walk on the BB.
499 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
500 Instruction *Inst = BBI++;
502 // Handle 'free' calls specially.
503 if (CallInst *F = isFreeCall(Inst, TLI)) {
504 MadeChange |= HandleFree(F);
508 // If we find something that writes memory, get its memory dependence.
509 if (!hasMemoryWrite(Inst, *TLI))
512 // If we're storing the same value back to a pointer that we just
513 // loaded from, then the store can be removed.
514 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
515 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
516 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
518 MemoryIsNotModifiedBetween(DepLoad, SI)) {
520 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n "
521 << "LOAD: " << *DepLoad << "\n STORE: " << *SI << '\n');
523 // DeleteDeadInstruction can delete the current instruction. Save BBI
524 // in case we need it.
525 WeakVH NextInst(BBI);
527 DeleteDeadInstruction(SI, *MD, *TLI);
529 if (!NextInst) // Next instruction deleted.
531 else if (BBI != BB.begin()) // Revisit this instruction if possible.
533 ++NumRedundantStores;
540 MemDepResult InstDep = MD->getDependency(Inst);
542 if (!InstDep.isDef() && !InstDep.isClobber() && !InstDep.isNonLocal())
544 if (InstDep.isNonLocal()) {
545 if (!PDT->getRootNode())
547 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
548 handleNonLocalStoreDeletion(SI, BBI, BB);
552 // Figure out what location is being stored to.
553 MemoryLocation Loc = getLocForWrite(Inst, *AA);
555 // If we didn't get a useful location, fail.
559 while (InstDep.isDef() || InstDep.isClobber()) {
560 // Get the memory clobbered by the instruction we depend on. MemDep will
561 // skip any instructions that 'Loc' clearly doesn't interact with. If we
562 // end up depending on a may- or must-aliased load, then we can't optimize
563 // away the store and we bail out. However, if we depend on on something
564 // that overwrites the memory location we *can* potentially optimize it.
566 // Find out what memory location the dependent instruction stores.
567 Instruction *DepWrite = InstDep.getInst();
568 MemoryLocation DepLoc = getLocForWrite(DepWrite, *AA);
569 // If we didn't get a useful location, or if it isn't a size, bail out.
573 // If we find a write that is a) removable (i.e., non-volatile), b) is
574 // completely obliterated by the store to 'Loc', and c) which we know that
575 // 'Inst' doesn't load from, then we can remove it.
576 if (isRemovable(DepWrite) &&
577 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
578 int64_t InstWriteOffset, DepWriteOffset;
579 const DataLayout &DL = BB.getModule()->getDataLayout();
581 isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset);
582 if (OR == OverwriteComplete) {
583 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
584 << *DepWrite << "\n KILLER: " << *Inst << '\n');
586 // Delete the store and now-dead instructions that feed it.
587 DeleteDeadInstruction(DepWrite, *MD, *TLI);
591 // DeleteDeadInstruction can delete the current instruction in loop
594 if (BBI != BB.begin())
597 } else if (OR == OverwriteEnd && isShortenable(DepWrite)) {
598 // TODO: base this on the target vector size so that if the earlier
599 // store was too small to get vector writes anyway then its likely
600 // a good idea to shorten it
601 // Power of 2 vector writes are probably always a bad idea to optimize
602 // as any store/memset/memcpy is likely using vector instructions so
603 // shortening it to not vector size is likely to be slower
604 MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
605 unsigned DepWriteAlign = DepIntrinsic->getAlignment();
606 if (llvm::isPowerOf2_64(InstWriteOffset) ||
607 ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
609 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW END: "
610 << *DepWrite << "\n KILLER (offset "
611 << InstWriteOffset << ", "
612 << DepLoc.Size << ")"
615 Value* DepWriteLength = DepIntrinsic->getLength();
616 Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(),
619 DepIntrinsic->setLength(TrimmedLength);
625 // If this is a may-aliased store that is clobbering the store value, we
626 // can keep searching past it for another must-aliased pointer that stores
627 // to the same location. For example, in:
631 // we can remove the first store to P even though we don't know if P and Q
633 if (DepWrite == &BB.front()) break;
635 // Can't look past this instruction if it might read 'Loc'.
636 if (AA->getModRefInfo(DepWrite, Loc) & MRI_Ref)
639 InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
643 // If this block ends in a return, unwind, or unreachable, all allocas are
644 // dead at its end, which means stores to them are also dead.
645 if (BB.getTerminator()->getNumSuccessors() == 0)
646 MadeChange |= handleEndBlock(BB);
651 /// Returns true if the memory which is accessed by the store instruction is not
652 /// modified between the load and the store instruction.
653 /// Precondition: The store instruction must be dominated by the load
655 bool DSE::MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI) {
656 SmallVector<BasicBlock *, 16> WorkList;
657 SmallPtrSet<BasicBlock *, 8> Visited;
658 BasicBlock::iterator LoadBBI(LI);
660 BasicBlock::iterator StoreBBI(SI);
661 BasicBlock *LoadBB = LI->getParent();
662 BasicBlock *StoreBB = SI->getParent();
663 MemoryLocation StoreLoc = MemoryLocation::get(SI);
665 // Start checking the store-block.
666 WorkList.push_back(StoreBB);
667 bool isFirstBlock = true;
669 // Check all blocks going backward until we reach the load-block.
670 while (!WorkList.empty()) {
671 BasicBlock *B = WorkList.pop_back_val();
673 // Ignore instructions before LI if this is the LoadBB.
674 BasicBlock::iterator BI = (B == LoadBB ? LoadBBI : B->begin());
676 BasicBlock::iterator EI;
678 // Ignore instructions after SI if this is the first visit of StoreBB.
679 assert(B == StoreBB && "first block is not the store block");
681 isFirstBlock = false;
683 // It's not StoreBB or (in case of a loop) the second visit of StoreBB.
684 // In this case we also have to look at instructions after SI.
687 for (; BI != EI; ++BI) {
689 if (I->mayWriteToMemory() && I != SI) {
690 auto Res = AA->getModRefInfo(I, StoreLoc);
691 if (Res != MRI_NoModRef)
696 assert(B != &LoadBB->getParent()->getEntryBlock() &&
697 "Should not hit the entry block because SI must be dominated by LI");
698 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
699 if (!Visited.insert(*PredI).second)
701 WorkList.push_back(*PredI);
708 /// Find all blocks that will unconditionally lead to the block BB and append
710 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
711 BasicBlock *BB, DominatorTree *DT) {
712 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
713 BasicBlock *Pred = *I;
714 if (Pred == BB) continue;
715 TerminatorInst *PredTI = Pred->getTerminator();
716 if (PredTI->getNumSuccessors() != 1)
719 if (DT->isReachableFromEntry(Pred))
720 Blocks.push_back(Pred);
724 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
725 /// and zero out all the operands of this instruction. If any of them become
726 /// dead, delete them and the computation tree that feeds them.
727 /// If ValueSet is non-null, remove any deleted instructions from it as well.
728 void DSE::DeleteDeadInstruction(Instruction *I, MemoryDependenceAnalysis &MD,
729 const TargetLibraryInfo &TLI,
730 SmallSetVector<Value *, 16> *ValueSet) {
731 SmallVector<Instruction *, 32> NowDeadInsts;
733 NowDeadInsts.push_back(I);
736 // Before we touch this instruction, remove it from memdep!
738 Instruction *DeadInst = NowDeadInsts.pop_back_val();
740 if (StoreInst *SI = dyn_cast<StoreInst>(DeadInst))
741 DeadStores.insert(SI);
743 // This instruction is dead, zap it, in stages. Start by removing it from
744 // MemDep, which needs to know the operands and needs it to be in the
746 MD.removeInstruction(DeadInst);
748 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
749 Value *Op = DeadInst->getOperand(op);
750 DeadInst->setOperand(op, nullptr);
752 // If this operand just became dead, add it to the NowDeadInsts list.
753 if (!Op->use_empty())
756 if (Instruction *OpI = dyn_cast<Instruction>(Op))
757 if (isInstructionTriviallyDead(OpI, &TLI))
758 NowDeadInsts.push_back(OpI);
761 DeadInst->eraseFromParent();
764 ValueSet->remove(DeadInst);
765 } while (!NowDeadInsts.empty());
768 /// HandleFree - Handle frees of entire structures whose dependency is a store
769 /// to a field of that structure.
770 bool DSE::HandleFree(CallInst *F) {
771 bool MadeChange = false;
773 MemoryLocation Loc = MemoryLocation(F->getOperand(0));
774 SmallVector<BasicBlock *, 16> Blocks;
775 Blocks.push_back(F->getParent());
776 const DataLayout &DL = F->getModule()->getDataLayout();
778 while (!Blocks.empty()) {
779 BasicBlock *BB = Blocks.pop_back_val();
780 Instruction *InstPt = BB->getTerminator();
781 if (BB == F->getParent()) InstPt = F;
783 MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
784 while (Dep.isDef() || Dep.isClobber()) {
785 Instruction *Dependency = Dep.getInst();
786 if (!hasMemoryWrite(Dependency, *TLI) || !isRemovable(Dependency))
790 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
792 // Check for aliasing.
793 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
796 Instruction *Next = std::next(BasicBlock::iterator(Dependency));
798 // DCE instructions only used to calculate that store
799 DeleteDeadInstruction(Dependency, *MD, *TLI);
803 // Inst's old Dependency is now deleted. Compute the next dependency,
804 // which may also be dead, as in
806 // s[1] = 0; // This has just been deleted.
808 Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
811 if (Dep.isNonLocal())
812 FindUnconditionalPreds(Blocks, BB, DT);
818 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
819 /// function end block. Ex:
822 /// store i32 1, i32* %A
824 bool DSE::handleEndBlock(BasicBlock &BB) {
825 bool MadeChange = false;
827 // Keep track of all of the stack objects that are dead at the end of the
829 SmallSetVector<Value*, 16> DeadStackObjects;
831 // Find all of the alloca'd pointers in the entry block.
832 BasicBlock *Entry = BB.getParent()->begin();
833 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
834 if (isa<AllocaInst>(I))
835 DeadStackObjects.insert(I);
837 // Okay, so these are dead heap objects, but if the pointer never escapes
838 // then it's leaked by this function anyways.
839 else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
840 DeadStackObjects.insert(I);
843 // Treat byval or inalloca arguments the same, stores to them are dead at the
844 // end of the function.
845 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
846 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
847 if (AI->hasByValOrInAllocaAttr())
848 DeadStackObjects.insert(AI);
850 const DataLayout &DL = BB.getModule()->getDataLayout();
852 // Scan the basic block backwards
853 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
856 // If we find a store, check to see if it points into a dead stack value.
857 if (hasMemoryWrite(BBI, *TLI) && isRemovable(BBI)) {
858 // See through pointer-to-pointer bitcasts
859 SmallVector<Value *, 4> Pointers;
860 GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers, DL);
862 // Stores to stack values are valid candidates for removal.
864 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
865 E = Pointers.end(); I != E; ++I)
866 if (!DeadStackObjects.count(*I)) {
872 Instruction *Dead = BBI++;
874 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
875 << *Dead << "\n Objects: ";
876 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
877 E = Pointers.end(); I != E; ++I) {
879 if (std::next(I) != E)
884 // DCE instructions only used to calculate that store.
885 DeleteDeadInstruction(Dead, *MD, *TLI, &DeadStackObjects);
892 // Remove any dead non-memory-mutating instructions.
893 if (isInstructionTriviallyDead(BBI, TLI)) {
894 Instruction *Inst = BBI++;
895 DeleteDeadInstruction(Inst, *MD, *TLI, &DeadStackObjects);
901 if (isa<AllocaInst>(BBI)) {
902 // Remove allocas from the list of dead stack objects; there can't be
903 // any references before the definition.
904 DeadStackObjects.remove(BBI);
908 if (auto CS = CallSite(BBI)) {
909 // Remove allocation function calls from the list of dead stack objects;
910 // there can't be any references before the definition.
911 if (isAllocLikeFn(BBI, TLI))
912 DeadStackObjects.remove(BBI);
914 // If this call does not access memory, it can't be loading any of our
916 if (AA->doesNotAccessMemory(CS))
919 // If the call might load from any of our allocas, then any store above
921 DeadStackObjects.remove_if([&](Value *I) {
922 // See if the call site touches the value.
923 ModRefInfo A = AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI));
925 return A == MRI_ModRef || A == MRI_Ref;
928 // If all of the allocas were clobbered by the call then we're not going
929 // to find anything else to process.
930 if (DeadStackObjects.empty())
936 MemoryLocation LoadedLoc;
938 // If we encounter a use of the pointer, it is no longer considered dead
939 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
940 if (!L->isUnordered()) // Be conservative with atomic/volatile load
942 LoadedLoc = MemoryLocation::get(L);
943 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
944 LoadedLoc = MemoryLocation::get(V);
945 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
946 LoadedLoc = MemoryLocation::getForSource(MTI);
947 } else if (!BBI->mayReadFromMemory()) {
948 // Instruction doesn't read memory. Note that stores that weren't removed
949 // above will hit this case.
952 // Unknown inst; assume it clobbers everything.
956 // Remove any allocas from the DeadPointer set that are loaded, as this
957 // makes any stores above the access live.
958 RemoveAccessedObjects(LoadedLoc, DeadStackObjects, DL);
960 // If all of the allocas were clobbered by the access then we're not going
961 // to find anything else to process.
962 if (DeadStackObjects.empty())
969 /// RemoveAccessedObjects - Check to see if the specified location may alias any
970 /// of the stack objects in the DeadStackObjects set. If so, they become live
971 /// because the location is being loaded.
972 void DSE::RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
973 SmallSetVector<Value *, 16> &DeadStackObjects,
974 const DataLayout &DL) {
975 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
977 // A constant can't be in the dead pointer set.
978 if (isa<Constant>(UnderlyingPointer))
981 // If the kill pointer can be easily reduced to an alloca, don't bother doing
982 // extraneous AA queries.
983 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
984 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
988 // Remove objects that could alias LoadedLoc.
989 DeadStackObjects.remove_if([&](Value *I) {
990 // See if the loaded location could alias the stack location.
991 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
992 return !AA->isNoAlias(StackLoc, LoadedLoc);
996 /// isSafeCandidateForDeletion- Check all paths from the SrcBlock till
997 /// SinkBlock to see if Store 'SI' is safe to be remove.
998 /// Returns true if the candidate store SI is safe to delete
999 /// else returns false.
1000 bool DSE::isSafeCandidateForDeletion(BasicBlock *SrcBlock,
1001 BasicBlock *SinkBlock, StoreInst *SI) {
1002 SmallVector<BasicBlock *, 16> WorkList;
1003 SmallPtrSet<BasicBlock *, 8> Visited;
1004 BasicBlock::iterator BBI(SI);
1006 // Check from the store till end of block and make sure we have no references
1007 // to memory stored by this Store Instruction.
1008 for (auto BI = ++BBI, BE = SrcBlock->end(); BI != BE; ++BI) {
1009 Instruction *I = BI;
1010 StoreInst *CSI = dyn_cast<StoreInst>(I);
1013 AA->alias(MemoryLocation::get(SI), MemoryLocation::get(CSI));
1017 ModRefInfo Res = AA->getModRefInfo(I, MemoryLocation::get(SI));
1018 if (Res != MRI_NoModRef)
1023 // Add successors of the block to stack and start DFS.
1024 for (succ_iterator I = succ_begin(SrcBlock), E = succ_end(SrcBlock); I != E;
1026 if (!Visited.insert(*I).second)
1028 // A path with backedge may not be safe. Conservatively mark
1029 // this store unsafe.
1030 if (BackEdgesMap.count(std::make_pair(SrcBlock, *I)))
1032 WorkList.push_back(*I);
1035 while (!WorkList.empty()) {
1036 BasicBlock *B = WorkList.pop_back_val();
1037 auto BI = B->begin();
1039 for (; BI != BE; ++BI) {
1040 Instruction *I = BI;
1041 StoreInst *CSI = dyn_cast<StoreInst>(I);
1044 AA->alias(MemoryLocation::get(SI), MemoryLocation::get(CSI));
1048 ModRefInfo Res = AA->getModRefInfo(I, MemoryLocation::get(SI));
1049 if (Res != MRI_NoModRef)
1054 // If we reached the sink node or we found a block which has a stores that
1055 // overwrites the candidate block we need not look at their successors.
1056 if (B == SinkBlock || BI != BE)
1059 for (succ_iterator I = succ_begin(B), E = succ_end(B); I != E; ++I) {
1060 if (!Visited.insert(*I).second)
1062 // A path with backedge may not be safe.Conservatively mark
1063 // this store unsafe.
1064 if (BackEdgesMap.count(std::make_pair(B, *I)))
1066 WorkList.push_back(*I);
1073 /// handleNonLocalStoreDeletion - Handle non local dead store elimination.
1074 /// This works by finding candidate stores using PDT and then running DFS
1075 /// from candidate store block checking all paths to make sure the store is
1077 void DSE::handleNonLocalStoreDeletion(StoreInst *SI, BasicBlock::iterator &BBI,
1078 BasicBlock &CurBlock) {
1079 BasicBlock *BB = SI->getParent();
1080 Value *Pointer = SI->getPointerOperand();
1081 DomTreeNode *DTNode = PDT->getNode(BB);
1085 int DFSNumIn = DTNode->getDFSNumIn();
1086 int DFSNumOut = DTNode->getDFSNumOut();
1087 for (int i = DFSNumIn + 1; i < DFSNumOut; ++i) {
1088 for (auto &I : Candidates[i]) {
1089 StoreInst *CandidateSI = I;
1090 if (DeadStores.count(CandidateSI))
1092 Value *MemPtr = CandidateSI->getPointerOperand();
1095 if (Pointer->getType() != MemPtr->getType())
1098 AA->alias(MemoryLocation::get(SI), MemoryLocation::get(CandidateSI));
1101 if (isSafeCandidateForDeletion(CandidateSI->getParent(), BB,
1103 DeleteDeadInstruction(CandidateSI, *MD, *TLI);
1104 ++NumCrossBlockStores;
1105 // DeleteDeadInstruction can delete the current instruction in loop
1106 // cases, reset BBI.
1108 if (BBI != CurBlock.begin())