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/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/Local.h"
41 #define DEBUG_TYPE "dse"
43 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
44 STATISTIC(NumFastStores, "Number of stores deleted");
45 STATISTIC(NumFastOther , "Number of other instrs removed");
48 struct DSE : public FunctionPass {
50 MemoryDependenceAnalysis *MD;
52 const TargetLibraryInfo *TLI;
54 static char ID; // Pass identification, replacement for typeid
55 DSE() : FunctionPass(ID), AA(nullptr), MD(nullptr), DT(nullptr) {
56 initializeDSEPass(*PassRegistry::getPassRegistry());
59 bool runOnFunction(Function &F) override {
60 if (skipOptnoneFunction(F))
63 AA = &getAnalysis<AliasAnalysis>();
64 MD = &getAnalysis<MemoryDependenceAnalysis>();
65 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
66 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
69 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
70 // Only check non-dead blocks. Dead blocks may have strange pointer
71 // cycles that will confuse alias analysis.
72 if (DT->isReachableFromEntry(I))
73 Changed |= runOnBasicBlock(*I);
75 AA = nullptr; MD = nullptr; DT = nullptr;
79 bool runOnBasicBlock(BasicBlock &BB);
80 bool MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI);
81 bool HandleFree(CallInst *F);
82 bool handleEndBlock(BasicBlock &BB);
83 void RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
84 SmallSetVector<Value *, 16> &DeadStackObjects,
85 const DataLayout &DL);
87 void getAnalysisUsage(AnalysisUsage &AU) const override {
89 AU.addRequired<DominatorTreeWrapperPass>();
90 AU.addRequired<AliasAnalysis>();
91 AU.addRequired<MemoryDependenceAnalysis>();
92 AU.addRequired<TargetLibraryInfoWrapperPass>();
93 AU.addPreserved<AliasAnalysis>();
94 AU.addPreserved<DominatorTreeWrapperPass>();
95 AU.addPreserved<MemoryDependenceAnalysis>();
101 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
102 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
103 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
104 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
105 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
106 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
108 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
110 //===----------------------------------------------------------------------===//
112 //===----------------------------------------------------------------------===//
114 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
115 /// and zero out all the operands of this instruction. If any of them become
116 /// dead, delete them and the computation tree that feeds them.
118 /// If ValueSet is non-null, remove any deleted instructions from it as well.
120 static void DeleteDeadInstruction(Instruction *I,
121 MemoryDependenceAnalysis &MD,
122 const TargetLibraryInfo &TLI,
123 SmallSetVector<Value*, 16> *ValueSet = nullptr) {
124 SmallVector<Instruction*, 32> NowDeadInsts;
126 NowDeadInsts.push_back(I);
129 // Before we touch this instruction, remove it from memdep!
131 Instruction *DeadInst = NowDeadInsts.pop_back_val();
134 // This instruction is dead, zap it, in stages. Start by removing it from
135 // MemDep, which needs to know the operands and needs it to be in the
137 MD.removeInstruction(DeadInst);
139 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
140 Value *Op = DeadInst->getOperand(op);
141 DeadInst->setOperand(op, nullptr);
143 // If this operand just became dead, add it to the NowDeadInsts list.
144 if (!Op->use_empty()) continue;
146 if (Instruction *OpI = dyn_cast<Instruction>(Op))
147 if (isInstructionTriviallyDead(OpI, &TLI))
148 NowDeadInsts.push_back(OpI);
151 DeadInst->eraseFromParent();
153 if (ValueSet) ValueSet->remove(DeadInst);
154 } while (!NowDeadInsts.empty());
158 /// hasMemoryWrite - Does this instruction write some memory? This only returns
159 /// true for things that we can analyze with other helpers below.
160 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo &TLI) {
161 if (isa<StoreInst>(I))
163 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
164 switch (II->getIntrinsicID()) {
167 case Intrinsic::memset:
168 case Intrinsic::memmove:
169 case Intrinsic::memcpy:
170 case Intrinsic::init_trampoline:
171 case Intrinsic::lifetime_end:
175 if (auto CS = CallSite(I)) {
176 if (Function *F = CS.getCalledFunction()) {
177 if (TLI.has(LibFunc::strcpy) &&
178 F->getName() == TLI.getName(LibFunc::strcpy)) {
181 if (TLI.has(LibFunc::strncpy) &&
182 F->getName() == TLI.getName(LibFunc::strncpy)) {
185 if (TLI.has(LibFunc::strcat) &&
186 F->getName() == TLI.getName(LibFunc::strcat)) {
189 if (TLI.has(LibFunc::strncat) &&
190 F->getName() == TLI.getName(LibFunc::strncat)) {
198 /// getLocForWrite - Return a Location stored to by the specified instruction.
199 /// If isRemovable returns true, this function and getLocForRead completely
200 /// describe the memory operations for this instruction.
201 static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
202 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
203 return MemoryLocation::get(SI);
205 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
206 // memcpy/memmove/memset.
207 MemoryLocation Loc = MemoryLocation::getForDest(MI);
211 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
213 return MemoryLocation();
215 switch (II->getIntrinsicID()) {
217 return MemoryLocation(); // Unhandled intrinsic.
218 case Intrinsic::init_trampoline:
219 // FIXME: We don't know the size of the trampoline, so we can't really
221 return MemoryLocation(II->getArgOperand(0));
222 case Intrinsic::lifetime_end: {
223 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
224 return MemoryLocation(II->getArgOperand(1), Len);
229 /// getLocForRead - Return the location read by the specified "hasMemoryWrite"
230 /// instruction if any.
231 static MemoryLocation getLocForRead(Instruction *Inst,
232 const TargetLibraryInfo &TLI) {
233 assert(hasMemoryWrite(Inst, TLI) && "Unknown instruction case");
235 // The only instructions that both read and write are the mem transfer
236 // instructions (memcpy/memmove).
237 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
238 return MemoryLocation::getForSource(MTI);
239 return MemoryLocation();
243 /// isRemovable - If the value of this instruction and the memory it writes to
244 /// is unused, may we delete this instruction?
245 static bool isRemovable(Instruction *I) {
246 // Don't remove volatile/atomic stores.
247 if (StoreInst *SI = dyn_cast<StoreInst>(I))
248 return SI->isUnordered();
250 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
251 switch (II->getIntrinsicID()) {
252 default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
253 case Intrinsic::lifetime_end:
254 // Never remove dead lifetime_end's, e.g. because it is followed by a
257 case Intrinsic::init_trampoline:
258 // Always safe to remove init_trampoline.
261 case Intrinsic::memset:
262 case Intrinsic::memmove:
263 case Intrinsic::memcpy:
264 // Don't remove volatile memory intrinsics.
265 return !cast<MemIntrinsic>(II)->isVolatile();
269 if (auto CS = CallSite(I))
270 return CS.getInstruction()->use_empty();
276 /// isShortenable - Returns true if this instruction can be safely shortened in
278 static bool isShortenable(Instruction *I) {
279 // Don't shorten stores for now
280 if (isa<StoreInst>(I))
283 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
284 switch (II->getIntrinsicID()) {
285 default: return false;
286 case Intrinsic::memset:
287 case Intrinsic::memcpy:
288 // Do shorten memory intrinsics.
293 // Don't shorten libcalls calls for now.
298 /// getStoredPointerOperand - Return the pointer that is being written to.
299 static Value *getStoredPointerOperand(Instruction *I) {
300 if (StoreInst *SI = dyn_cast<StoreInst>(I))
301 return SI->getPointerOperand();
302 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
303 return MI->getDest();
305 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
306 switch (II->getIntrinsicID()) {
307 default: llvm_unreachable("Unexpected intrinsic!");
308 case Intrinsic::init_trampoline:
309 return II->getArgOperand(0);
314 // All the supported functions so far happen to have dest as their first
316 return CS.getArgument(0);
319 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
320 const TargetLibraryInfo &TLI) {
322 if (getObjectSize(V, Size, DL, &TLI))
324 return MemoryLocation::UnknownSize;
336 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location
337 /// completely overwrites a store to the 'Earlier' location.
338 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely
339 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined
340 static OverwriteResult isOverwrite(const MemoryLocation &Later,
341 const MemoryLocation &Earlier,
342 const DataLayout &DL,
343 const TargetLibraryInfo &TLI,
344 int64_t &EarlierOff, int64_t &LaterOff) {
345 const Value *P1 = Earlier.Ptr->stripPointerCasts();
346 const Value *P2 = Later.Ptr->stripPointerCasts();
348 // If the start pointers are the same, we just have to compare sizes to see if
349 // the later store was larger than the earlier store.
351 // If we don't know the sizes of either access, then we can't do a
353 if (Later.Size == MemoryLocation::UnknownSize ||
354 Earlier.Size == MemoryLocation::UnknownSize)
355 return OverwriteUnknown;
357 // Make sure that the Later size is >= the Earlier size.
358 if (Later.Size >= Earlier.Size)
359 return OverwriteComplete;
362 // Otherwise, we have to have size information, and the later store has to be
363 // larger than the earlier one.
364 if (Later.Size == MemoryLocation::UnknownSize ||
365 Earlier.Size == MemoryLocation::UnknownSize)
366 return OverwriteUnknown;
368 // Check to see if the later store is to the entire object (either a global,
369 // an alloca, or a byval/inalloca argument). If so, then it clearly
370 // overwrites any other store to the same object.
371 const Value *UO1 = GetUnderlyingObject(P1, DL),
372 *UO2 = GetUnderlyingObject(P2, DL);
374 // If we can't resolve the same pointers to the same object, then we can't
375 // analyze them at all.
377 return OverwriteUnknown;
379 // If the "Later" store is to a recognizable object, get its size.
380 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
381 if (ObjectSize != MemoryLocation::UnknownSize)
382 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
383 return OverwriteComplete;
385 // Okay, we have stores to two completely different pointers. Try to
386 // decompose the pointer into a "base + constant_offset" form. If the base
387 // pointers are equal, then we can reason about the two stores.
390 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
391 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
393 // If the base pointers still differ, we have two completely different stores.
395 return OverwriteUnknown;
397 // The later store completely overlaps the earlier store if:
399 // 1. Both start at the same offset and the later one's size is greater than
400 // or equal to the earlier one's, or
405 // 2. The earlier store has an offset greater than the later offset, but which
406 // still lies completely within the later store.
409 // |----- later ------|
411 // We have to be careful here as *Off is signed while *.Size is unsigned.
412 if (EarlierOff >= LaterOff &&
413 Later.Size >= Earlier.Size &&
414 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
415 return OverwriteComplete;
417 // The other interesting case is if the later store overwrites the end of
423 // In this case we may want to trim the size of earlier to avoid generating
424 // writes to addresses which will definitely be overwritten later
425 if (LaterOff > EarlierOff &&
426 LaterOff < int64_t(EarlierOff + Earlier.Size) &&
427 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
430 // Otherwise, they don't completely overlap.
431 return OverwriteUnknown;
434 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a
435 /// memory region into an identical pointer) then it doesn't actually make its
436 /// input dead in the traditional sense. Consider this case:
441 /// In this case, the second store to A does not make the first store to A dead.
442 /// The usual situation isn't an explicit A<-A store like this (which can be
443 /// trivially removed) but a case where two pointers may alias.
445 /// This function detects when it is unsafe to remove a dependent instruction
446 /// because the DSE inducing instruction may be a self-read.
447 static bool isPossibleSelfRead(Instruction *Inst,
448 const MemoryLocation &InstStoreLoc,
449 Instruction *DepWrite,
450 const TargetLibraryInfo &TLI,
452 // Self reads can only happen for instructions that read memory. Get the
454 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
455 if (!InstReadLoc.Ptr) return false; // Not a reading instruction.
457 // If the read and written loc obviously don't alias, it isn't a read.
458 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
460 // Okay, 'Inst' may copy over itself. However, we can still remove a the
461 // DepWrite instruction if we can prove that it reads from the same location
462 // as Inst. This handles useful cases like:
465 // Here we don't know if A/B may alias, but we do know that B/B are must
466 // aliases, so removing the first memcpy is safe (assuming it writes <= #
467 // bytes as the second one.
468 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
470 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
473 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
474 // then it can't be considered dead.
479 //===----------------------------------------------------------------------===//
481 //===----------------------------------------------------------------------===//
483 bool DSE::runOnBasicBlock(BasicBlock &BB) {
484 bool MadeChange = false;
486 // Do a top-down walk on the BB.
487 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
488 Instruction *Inst = BBI++;
490 // Handle 'free' calls specially.
491 if (CallInst *F = isFreeCall(Inst, TLI)) {
492 MadeChange |= HandleFree(F);
496 // If we find something that writes memory, get its memory dependence.
497 if (!hasMemoryWrite(Inst, *TLI))
500 // If we're storing the same value back to a pointer that we just
501 // loaded from, then the store can be removed.
502 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
503 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
504 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
506 MemoryIsNotModifiedBetween(DepLoad, SI)) {
508 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n "
509 << "LOAD: " << *DepLoad << "\n STORE: " << *SI << '\n');
511 // DeleteDeadInstruction can delete the current instruction. Save BBI
512 // in case we need it.
513 WeakVH NextInst(BBI);
515 DeleteDeadInstruction(SI, *MD, *TLI);
517 if (!NextInst) // Next instruction deleted.
519 else if (BBI != BB.begin()) // Revisit this instruction if possible.
521 ++NumRedundantStores;
528 MemDepResult InstDep = MD->getDependency(Inst);
530 // Ignore any store where we can't find a local dependence.
531 // FIXME: cross-block DSE would be fun. :)
532 if (!InstDep.isDef() && !InstDep.isClobber())
535 // Figure out what location is being stored to.
536 MemoryLocation Loc = getLocForWrite(Inst, *AA);
538 // If we didn't get a useful location, fail.
542 while (InstDep.isDef() || InstDep.isClobber()) {
543 // Get the memory clobbered by the instruction we depend on. MemDep will
544 // skip any instructions that 'Loc' clearly doesn't interact with. If we
545 // end up depending on a may- or must-aliased load, then we can't optimize
546 // away the store and we bail out. However, if we depend on on something
547 // that overwrites the memory location we *can* potentially optimize it.
549 // Find out what memory location the dependent instruction stores.
550 Instruction *DepWrite = InstDep.getInst();
551 MemoryLocation DepLoc = getLocForWrite(DepWrite, *AA);
552 // If we didn't get a useful location, or if it isn't a size, bail out.
556 // If we find a write that is a) removable (i.e., non-volatile), b) is
557 // completely obliterated by the store to 'Loc', and c) which we know that
558 // 'Inst' doesn't load from, then we can remove it.
559 if (isRemovable(DepWrite) &&
560 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
561 int64_t InstWriteOffset, DepWriteOffset;
562 const DataLayout &DL = BB.getModule()->getDataLayout();
564 isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset);
565 if (OR == OverwriteComplete) {
566 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
567 << *DepWrite << "\n KILLER: " << *Inst << '\n');
569 // Delete the store and now-dead instructions that feed it.
570 DeleteDeadInstruction(DepWrite, *MD, *TLI);
574 // DeleteDeadInstruction can delete the current instruction in loop
577 if (BBI != BB.begin())
580 } else if (OR == OverwriteEnd && isShortenable(DepWrite)) {
581 // TODO: base this on the target vector size so that if the earlier
582 // store was too small to get vector writes anyway then its likely
583 // a good idea to shorten it
584 // Power of 2 vector writes are probably always a bad idea to optimize
585 // as any store/memset/memcpy is likely using vector instructions so
586 // shortening it to not vector size is likely to be slower
587 MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
588 unsigned DepWriteAlign = DepIntrinsic->getAlignment();
589 if (llvm::isPowerOf2_64(InstWriteOffset) ||
590 ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
592 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW END: "
593 << *DepWrite << "\n KILLER (offset "
594 << InstWriteOffset << ", "
595 << DepLoc.Size << ")"
598 Value* DepWriteLength = DepIntrinsic->getLength();
599 Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(),
602 DepIntrinsic->setLength(TrimmedLength);
608 // If this is a may-aliased store that is clobbering the store value, we
609 // can keep searching past it for another must-aliased pointer that stores
610 // to the same location. For example, in:
614 // we can remove the first store to P even though we don't know if P and Q
616 if (DepWrite == &BB.front()) break;
618 // Can't look past this instruction if it might read 'Loc'.
619 if (AA->getModRefInfo(DepWrite, Loc) & MRI_Ref)
622 InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
626 // If this block ends in a return, unwind, or unreachable, all allocas are
627 // dead at its end, which means stores to them are also dead.
628 if (BB.getTerminator()->getNumSuccessors() == 0)
629 MadeChange |= handleEndBlock(BB);
634 /// Returns true if the memory which is accessed by the store instruction is not
635 /// modified between the load and the store instruction.
636 /// Precondition: The store instruction must be dominated by the load
638 bool DSE::MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI) {
639 SmallVector<BasicBlock *, 16> WorkList;
640 SmallPtrSet<BasicBlock *, 8> Visited;
641 BasicBlock::iterator LoadBBI(LI);
643 BasicBlock::iterator StoreBBI(SI);
644 BasicBlock *LoadBB = LI->getParent();
645 BasicBlock *StoreBB = SI->getParent();
646 MemoryLocation StoreLoc = MemoryLocation::get(SI);
648 // Start checking the store-block.
649 WorkList.push_back(StoreBB);
650 bool isFirstBlock = true;
652 // Check all blocks going backward until we reach the load-block.
653 while (!WorkList.empty()) {
654 BasicBlock *B = WorkList.pop_back_val();
656 // Ignore instructions before LI if this is the LoadBB.
657 BasicBlock::iterator BI = (B == LoadBB ? LoadBBI : B->begin());
659 BasicBlock::iterator EI;
661 // Ignore instructions after SI if this is the first visit of StoreBB.
662 assert(B == StoreBB && "first block is not the store block");
664 isFirstBlock = false;
666 // It's not StoreBB or (in case of a loop) the second visit of StoreBB.
667 // In this case we also have to look at instructions after SI.
670 for (; BI != EI; ++BI) {
672 if (I->mayWriteToMemory() && I != SI) {
673 auto Res = AA->getModRefInfo(I, StoreLoc);
674 if (Res != MRI_NoModRef)
679 assert(B != &LoadBB->getParent()->getEntryBlock() &&
680 "Should not hit the entry block because SI must be dominated by LI");
681 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
682 if (!Visited.insert(*PredI).second)
684 WorkList.push_back(*PredI);
691 /// Find all blocks that will unconditionally lead to the block BB and append
693 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
694 BasicBlock *BB, DominatorTree *DT) {
695 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
696 BasicBlock *Pred = *I;
697 if (Pred == BB) continue;
698 TerminatorInst *PredTI = Pred->getTerminator();
699 if (PredTI->getNumSuccessors() != 1)
702 if (DT->isReachableFromEntry(Pred))
703 Blocks.push_back(Pred);
707 /// HandleFree - Handle frees of entire structures whose dependency is a store
708 /// to a field of that structure.
709 bool DSE::HandleFree(CallInst *F) {
710 bool MadeChange = false;
712 MemoryLocation Loc = MemoryLocation(F->getOperand(0));
713 SmallVector<BasicBlock *, 16> Blocks;
714 Blocks.push_back(F->getParent());
715 const DataLayout &DL = F->getModule()->getDataLayout();
717 while (!Blocks.empty()) {
718 BasicBlock *BB = Blocks.pop_back_val();
719 Instruction *InstPt = BB->getTerminator();
720 if (BB == F->getParent()) InstPt = F;
722 MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
723 while (Dep.isDef() || Dep.isClobber()) {
724 Instruction *Dependency = Dep.getInst();
725 if (!hasMemoryWrite(Dependency, *TLI) || !isRemovable(Dependency))
729 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
731 // Check for aliasing.
732 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
735 Instruction *Next = std::next(BasicBlock::iterator(Dependency));
737 // DCE instructions only used to calculate that store
738 DeleteDeadInstruction(Dependency, *MD, *TLI);
742 // Inst's old Dependency is now deleted. Compute the next dependency,
743 // which may also be dead, as in
745 // s[1] = 0; // This has just been deleted.
747 Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
750 if (Dep.isNonLocal())
751 FindUnconditionalPreds(Blocks, BB, DT);
757 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
758 /// function end block. Ex:
761 /// store i32 1, i32* %A
763 bool DSE::handleEndBlock(BasicBlock &BB) {
764 bool MadeChange = false;
766 // Keep track of all of the stack objects that are dead at the end of the
768 SmallSetVector<Value*, 16> DeadStackObjects;
770 // Find all of the alloca'd pointers in the entry block.
771 BasicBlock *Entry = BB.getParent()->begin();
772 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
773 if (isa<AllocaInst>(I))
774 DeadStackObjects.insert(I);
776 // Okay, so these are dead heap objects, but if the pointer never escapes
777 // then it's leaked by this function anyways.
778 else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
779 DeadStackObjects.insert(I);
782 // Treat byval or inalloca arguments the same, stores to them are dead at the
783 // end of the function.
784 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
785 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
786 if (AI->hasByValOrInAllocaAttr())
787 DeadStackObjects.insert(AI);
789 const DataLayout &DL = BB.getModule()->getDataLayout();
791 // becomes false once lifetime intrinsics are observable or useful for stack
793 bool canRemoveLifetimeIntrinsics = true;
795 // Scan the basic block backwards
796 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
800 if (canRemoveLifetimeIntrinsics)
801 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
802 switch (II->getIntrinsicID()) {
804 case Intrinsic::lifetime_start:
805 case Intrinsic::lifetime_end:
806 V = II->getArgOperand(1);
810 if (!V && hasMemoryWrite(BBI, *TLI) && isRemovable(BBI))
811 V = getStoredPointerOperand(BBI);
813 // If we found a store, check to see if it points into a dead stack value.
815 // See through pointer-to-pointer bitcasts
816 SmallVector<Value *, 4> Pointers;
817 GetUnderlyingObjects(V, Pointers, DL);
819 // Stores to stack values are valid candidates for removal.
821 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
822 E = Pointers.end(); I != E; ++I)
823 if (!DeadStackObjects.count(*I)) {
829 Instruction *Dead = BBI++;
831 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
832 << *Dead << "\n Objects: ";
833 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
834 E = Pointers.end(); I != E; ++I) {
836 if (std::next(I) != E)
841 // DCE instructions only used to calculate that store.
842 DeleteDeadInstruction(Dead, *MD, *TLI, &DeadStackObjects);
849 // Remove any dead non-memory-mutating instructions.
850 if (isInstructionTriviallyDead(BBI, TLI)) {
851 Instruction *Inst = BBI++;
852 DeleteDeadInstruction(Inst, *MD, *TLI, &DeadStackObjects);
858 if (isa<AllocaInst>(BBI)) {
859 // Remove allocas from the list of dead stack objects; there can't be
860 // any references before the definition.
861 DeadStackObjects.remove(BBI);
865 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
866 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
867 // We found a lifetime start for a live object, which we could not
868 // remove. So we must stop removing lifetime intrinsics from this block
869 // because they're useful for stack coloring again
870 canRemoveLifetimeIntrinsics = false;
874 if (auto CS = CallSite(BBI)) {
875 // Remove allocation function calls from the list of dead stack objects;
876 // there can't be any references before the definition.
877 if (isAllocLikeFn(BBI, TLI))
878 DeadStackObjects.remove(BBI);
880 // If this call does not access memory, it can't be loading any of our
882 if (AA->doesNotAccessMemory(CS))
885 // If the call might load from any of our allocas, then any store above
887 DeadStackObjects.remove_if([&](Value *I) {
888 // See if the call site touches the value.
889 ModRefInfo A = AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI));
891 return A == MRI_ModRef || A == MRI_Ref;
894 // If all of the allocas were clobbered by the call then we're not going
895 // to find anything else to process.
896 if (DeadStackObjects.empty())
902 MemoryLocation LoadedLoc;
904 // If we encounter a use of the pointer, it is no longer considered dead
905 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
906 if (!L->isUnordered()) // Be conservative with atomic/volatile load
908 LoadedLoc = MemoryLocation::get(L);
909 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
910 LoadedLoc = MemoryLocation::get(V);
911 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
912 LoadedLoc = MemoryLocation::getForSource(MTI);
913 } else if (!BBI->mayReadFromMemory()) {
914 // Instruction doesn't read memory. Note that stores that weren't removed
915 // above will hit this case.
918 // Unknown inst; assume it clobbers everything.
922 // Remove any allocas from the DeadPointer set that are loaded, as this
923 // makes any stores above the access live.
924 RemoveAccessedObjects(LoadedLoc, DeadStackObjects, DL);
926 // If all of the allocas were clobbered by the access then we're not going
927 // to find anything else to process.
928 if (DeadStackObjects.empty())
935 /// RemoveAccessedObjects - Check to see if the specified location may alias any
936 /// of the stack objects in the DeadStackObjects set. If so, they become live
937 /// because the location is being loaded.
938 void DSE::RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
939 SmallSetVector<Value *, 16> &DeadStackObjects,
940 const DataLayout &DL) {
941 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
943 // A constant can't be in the dead pointer set.
944 if (isa<Constant>(UnderlyingPointer))
947 // If the kill pointer can be easily reduced to an alloca, don't bother doing
948 // extraneous AA queries.
949 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
950 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
954 // Remove objects that could alias LoadedLoc.
955 DeadStackObjects.remove_if([&](Value *I) {
956 // See if the loaded location could alias the stack location.
957 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
958 return !AA->isNoAlias(StackLoc, LoadedLoc);