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 #define DEBUG_TYPE "dse"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
40 STATISTIC(NumFastStores, "Number of stores deleted");
41 STATISTIC(NumFastOther , "Number of other instrs removed");
44 struct DSE : public FunctionPass {
46 MemoryDependenceAnalysis *MD;
48 const TargetLibraryInfo *TLI;
50 static char ID; // Pass identification, replacement for typeid
51 DSE() : FunctionPass(ID), AA(0), MD(0), DT(0) {
52 initializeDSEPass(*PassRegistry::getPassRegistry());
55 virtual bool runOnFunction(Function &F) {
56 AA = &getAnalysis<AliasAnalysis>();
57 MD = &getAnalysis<MemoryDependenceAnalysis>();
58 DT = &getAnalysis<DominatorTree>();
59 TLI = AA->getTargetLibraryInfo();
62 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
63 // Only check non-dead blocks. Dead blocks may have strange pointer
64 // cycles that will confuse alias analysis.
65 if (DT->isReachableFromEntry(I))
66 Changed |= runOnBasicBlock(*I);
68 AA = 0; MD = 0; DT = 0;
72 bool runOnBasicBlock(BasicBlock &BB);
73 bool HandleFree(CallInst *F);
74 bool handleEndBlock(BasicBlock &BB);
75 void RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
76 SmallSetVector<Value*, 16> &DeadStackObjects);
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80 AU.addRequired<DominatorTree>();
81 AU.addRequired<AliasAnalysis>();
82 AU.addRequired<MemoryDependenceAnalysis>();
83 AU.addPreserved<AliasAnalysis>();
84 AU.addPreserved<DominatorTree>();
85 AU.addPreserved<MemoryDependenceAnalysis>();
91 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
92 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
93 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
94 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
95 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
97 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
99 //===----------------------------------------------------------------------===//
101 //===----------------------------------------------------------------------===//
103 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
104 /// and zero out all the operands of this instruction. If any of them become
105 /// dead, delete them and the computation tree that feeds them.
107 /// If ValueSet is non-null, remove any deleted instructions from it as well.
109 static void DeleteDeadInstruction(Instruction *I,
110 MemoryDependenceAnalysis &MD,
111 const TargetLibraryInfo *TLI,
112 SmallSetVector<Value*, 16> *ValueSet = 0) {
113 SmallVector<Instruction*, 32> NowDeadInsts;
115 NowDeadInsts.push_back(I);
118 // Before we touch this instruction, remove it from memdep!
120 Instruction *DeadInst = NowDeadInsts.pop_back_val();
123 // This instruction is dead, zap it, in stages. Start by removing it from
124 // MemDep, which needs to know the operands and needs it to be in the
126 MD.removeInstruction(DeadInst);
128 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
129 Value *Op = DeadInst->getOperand(op);
130 DeadInst->setOperand(op, 0);
132 // If this operand just became dead, add it to the NowDeadInsts list.
133 if (!Op->use_empty()) continue;
135 if (Instruction *OpI = dyn_cast<Instruction>(Op))
136 if (isInstructionTriviallyDead(OpI, TLI))
137 NowDeadInsts.push_back(OpI);
140 DeadInst->eraseFromParent();
142 if (ValueSet) ValueSet->remove(DeadInst);
143 } while (!NowDeadInsts.empty());
147 /// hasMemoryWrite - Does this instruction write some memory? This only returns
148 /// true for things that we can analyze with other helpers below.
149 static bool hasMemoryWrite(Instruction *I) {
150 if (isa<StoreInst>(I))
152 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
153 switch (II->getIntrinsicID()) {
156 case Intrinsic::memset:
157 case Intrinsic::memmove:
158 case Intrinsic::memcpy:
159 case Intrinsic::init_trampoline:
160 case Intrinsic::lifetime_end:
167 /// getLocForWrite - Return a Location stored to by the specified instruction.
168 /// If isRemovable returns true, this function and getLocForRead completely
169 /// describe the memory operations for this instruction.
170 static AliasAnalysis::Location
171 getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
172 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
173 return AA.getLocation(SI);
175 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
176 // memcpy/memmove/memset.
177 AliasAnalysis::Location Loc = AA.getLocationForDest(MI);
178 // If we don't have target data around, an unknown size in Location means
179 // that we should use the size of the pointee type. This isn't valid for
180 // memset/memcpy, which writes more than an i8.
181 if (Loc.Size == AliasAnalysis::UnknownSize && AA.getTargetData() == 0)
182 return AliasAnalysis::Location();
186 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
187 if (II == 0) return AliasAnalysis::Location();
189 switch (II->getIntrinsicID()) {
190 default: return AliasAnalysis::Location(); // Unhandled intrinsic.
191 case Intrinsic::init_trampoline:
192 // If we don't have target data around, an unknown size in Location means
193 // that we should use the size of the pointee type. This isn't valid for
194 // init.trampoline, which writes more than an i8.
195 if (AA.getTargetData() == 0) return AliasAnalysis::Location();
197 // FIXME: We don't know the size of the trampoline, so we can't really
199 return AliasAnalysis::Location(II->getArgOperand(0));
200 case Intrinsic::lifetime_end: {
201 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
202 return AliasAnalysis::Location(II->getArgOperand(1), Len);
207 /// getLocForRead - Return the location read by the specified "hasMemoryWrite"
208 /// instruction if any.
209 static AliasAnalysis::Location
210 getLocForRead(Instruction *Inst, AliasAnalysis &AA) {
211 assert(hasMemoryWrite(Inst) && "Unknown instruction case");
213 // The only instructions that both read and write are the mem transfer
214 // instructions (memcpy/memmove).
215 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
216 return AA.getLocationForSource(MTI);
217 return AliasAnalysis::Location();
221 /// isRemovable - If the value of this instruction and the memory it writes to
222 /// is unused, may we delete this instruction?
223 static bool isRemovable(Instruction *I) {
224 // Don't remove volatile/atomic stores.
225 if (StoreInst *SI = dyn_cast<StoreInst>(I))
226 return SI->isUnordered();
228 IntrinsicInst *II = cast<IntrinsicInst>(I);
229 switch (II->getIntrinsicID()) {
230 default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
231 case Intrinsic::lifetime_end:
232 // Never remove dead lifetime_end's, e.g. because it is followed by a
235 case Intrinsic::init_trampoline:
236 // Always safe to remove init_trampoline.
239 case Intrinsic::memset:
240 case Intrinsic::memmove:
241 case Intrinsic::memcpy:
242 // Don't remove volatile memory intrinsics.
243 return !cast<MemIntrinsic>(II)->isVolatile();
248 /// isShortenable - Returns true if this instruction can be safely shortened in
250 static bool isShortenable(Instruction *I) {
251 // Don't shorten stores for now
252 if (isa<StoreInst>(I))
255 IntrinsicInst *II = cast<IntrinsicInst>(I);
256 switch (II->getIntrinsicID()) {
257 default: return false;
258 case Intrinsic::memset:
259 case Intrinsic::memcpy:
260 // Do shorten memory intrinsics.
265 /// getStoredPointerOperand - Return the pointer that is being written to.
266 static Value *getStoredPointerOperand(Instruction *I) {
267 if (StoreInst *SI = dyn_cast<StoreInst>(I))
268 return SI->getPointerOperand();
269 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
270 return MI->getDest();
272 IntrinsicInst *II = cast<IntrinsicInst>(I);
273 switch (II->getIntrinsicID()) {
274 default: llvm_unreachable("Unexpected intrinsic!");
275 case Intrinsic::init_trampoline:
276 return II->getArgOperand(0);
280 static uint64_t getPointerSize(const Value *V, AliasAnalysis &AA) {
282 if (getObjectSize(V, Size, AA.getTargetData(), AA.getTargetLibraryInfo()))
284 return AliasAnalysis::UnknownSize;
296 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location
297 /// completely overwrites a store to the 'Earlier' location.
298 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely
299 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined
300 static OverwriteResult isOverwrite(const AliasAnalysis::Location &Later,
301 const AliasAnalysis::Location &Earlier,
305 const Value *P1 = Earlier.Ptr->stripPointerCasts();
306 const Value *P2 = Later.Ptr->stripPointerCasts();
308 // If the start pointers are the same, we just have to compare sizes to see if
309 // the later store was larger than the earlier store.
311 // If we don't know the sizes of either access, then we can't do a
313 if (Later.Size == AliasAnalysis::UnknownSize ||
314 Earlier.Size == AliasAnalysis::UnknownSize) {
315 // If we have no TargetData information around, then the size of the store
316 // is inferrable from the pointee type. If they are the same type, then
317 // we know that the store is safe.
318 if (AA.getTargetData() == 0 &&
319 Later.Ptr->getType() == Earlier.Ptr->getType())
320 return OverwriteComplete;
322 return OverwriteUnknown;
325 // Make sure that the Later size is >= the Earlier size.
326 if (Later.Size >= Earlier.Size)
327 return OverwriteComplete;
330 // Otherwise, we have to have size information, and the later store has to be
331 // larger than the earlier one.
332 if (Later.Size == AliasAnalysis::UnknownSize ||
333 Earlier.Size == AliasAnalysis::UnknownSize ||
334 AA.getTargetData() == 0)
335 return OverwriteUnknown;
337 // Check to see if the later store is to the entire object (either a global,
338 // an alloca, or a byval argument). If so, then it clearly overwrites any
339 // other store to the same object.
340 const TargetData &TD = *AA.getTargetData();
342 const Value *UO1 = GetUnderlyingObject(P1, &TD),
343 *UO2 = GetUnderlyingObject(P2, &TD);
345 // If we can't resolve the same pointers to the same object, then we can't
346 // analyze them at all.
348 return OverwriteUnknown;
350 // If the "Later" store is to a recognizable object, get its size.
351 uint64_t ObjectSize = getPointerSize(UO2, AA);
352 if (ObjectSize != AliasAnalysis::UnknownSize)
353 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
354 return OverwriteComplete;
356 // Okay, we have stores to two completely different pointers. Try to
357 // decompose the pointer into a "base + constant_offset" form. If the base
358 // pointers are equal, then we can reason about the two stores.
361 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, TD);
362 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, TD);
364 // If the base pointers still differ, we have two completely different stores.
366 return OverwriteUnknown;
368 // The later store completely overlaps the earlier store if:
370 // 1. Both start at the same offset and the later one's size is greater than
371 // or equal to the earlier one's, or
376 // 2. The earlier store has an offset greater than the later offset, but which
377 // still lies completely within the later store.
380 // |----- later ------|
382 // We have to be careful here as *Off is signed while *.Size is unsigned.
383 if (EarlierOff >= LaterOff &&
384 Later.Size >= Earlier.Size &&
385 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
386 return OverwriteComplete;
388 // The other interesting case is if the later store overwrites the end of
394 // In this case we may want to trim the size of earlier to avoid generating
395 // writes to addresses which will definitely be overwritten later
396 if (LaterOff > EarlierOff &&
397 LaterOff < int64_t(EarlierOff + Earlier.Size) &&
398 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
401 // Otherwise, they don't completely overlap.
402 return OverwriteUnknown;
405 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a
406 /// memory region into an identical pointer) then it doesn't actually make its
407 /// input dead in the traditional sense. Consider this case:
412 /// In this case, the second store to A does not make the first store to A dead.
413 /// The usual situation isn't an explicit A<-A store like this (which can be
414 /// trivially removed) but a case where two pointers may alias.
416 /// This function detects when it is unsafe to remove a dependent instruction
417 /// because the DSE inducing instruction may be a self-read.
418 static bool isPossibleSelfRead(Instruction *Inst,
419 const AliasAnalysis::Location &InstStoreLoc,
420 Instruction *DepWrite, AliasAnalysis &AA) {
421 // Self reads can only happen for instructions that read memory. Get the
423 AliasAnalysis::Location InstReadLoc = getLocForRead(Inst, AA);
424 if (InstReadLoc.Ptr == 0) return false; // Not a reading instruction.
426 // If the read and written loc obviously don't alias, it isn't a read.
427 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
429 // Okay, 'Inst' may copy over itself. However, we can still remove a the
430 // DepWrite instruction if we can prove that it reads from the same location
431 // as Inst. This handles useful cases like:
434 // Here we don't know if A/B may alias, but we do know that B/B are must
435 // aliases, so removing the first memcpy is safe (assuming it writes <= #
436 // bytes as the second one.
437 AliasAnalysis::Location DepReadLoc = getLocForRead(DepWrite, AA);
439 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
442 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
443 // then it can't be considered dead.
448 //===----------------------------------------------------------------------===//
450 //===----------------------------------------------------------------------===//
452 bool DSE::runOnBasicBlock(BasicBlock &BB) {
453 bool MadeChange = false;
455 // Do a top-down walk on the BB.
456 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
457 Instruction *Inst = BBI++;
459 // Handle 'free' calls specially.
460 if (CallInst *F = isFreeCall(Inst, TLI)) {
461 MadeChange |= HandleFree(F);
465 // If we find something that writes memory, get its memory dependence.
466 if (!hasMemoryWrite(Inst))
469 MemDepResult InstDep = MD->getDependency(Inst);
471 // Ignore any store where we can't find a local dependence.
472 // FIXME: cross-block DSE would be fun. :)
473 if (!InstDep.isDef() && !InstDep.isClobber())
476 // If we're storing the same value back to a pointer that we just
477 // loaded from, then the store can be removed.
478 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
479 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
480 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
481 SI->getOperand(0) == DepLoad && isRemovable(SI)) {
482 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n "
483 << "LOAD: " << *DepLoad << "\n STORE: " << *SI << '\n');
485 // DeleteDeadInstruction can delete the current instruction. Save BBI
486 // in case we need it.
487 WeakVH NextInst(BBI);
489 DeleteDeadInstruction(SI, *MD, TLI);
491 if (NextInst == 0) // Next instruction deleted.
493 else if (BBI != BB.begin()) // Revisit this instruction if possible.
502 // Figure out what location is being stored to.
503 AliasAnalysis::Location Loc = getLocForWrite(Inst, *AA);
505 // If we didn't get a useful location, fail.
509 while (InstDep.isDef() || InstDep.isClobber()) {
510 // Get the memory clobbered by the instruction we depend on. MemDep will
511 // skip any instructions that 'Loc' clearly doesn't interact with. If we
512 // end up depending on a may- or must-aliased load, then we can't optimize
513 // away the store and we bail out. However, if we depend on on something
514 // that overwrites the memory location we *can* potentially optimize it.
516 // Find out what memory location the dependent instruction stores.
517 Instruction *DepWrite = InstDep.getInst();
518 AliasAnalysis::Location DepLoc = getLocForWrite(DepWrite, *AA);
519 // If we didn't get a useful location, or if it isn't a size, bail out.
523 // If we find a write that is a) removable (i.e., non-volatile), b) is
524 // completely obliterated by the store to 'Loc', and c) which we know that
525 // 'Inst' doesn't load from, then we can remove it.
526 if (isRemovable(DepWrite) &&
527 !isPossibleSelfRead(Inst, Loc, DepWrite, *AA)) {
528 int64_t InstWriteOffset, DepWriteOffset;
529 OverwriteResult OR = isOverwrite(Loc, DepLoc, *AA,
530 DepWriteOffset, InstWriteOffset);
531 if (OR == OverwriteComplete) {
532 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
533 << *DepWrite << "\n KILLER: " << *Inst << '\n');
535 // Delete the store and now-dead instructions that feed it.
536 DeleteDeadInstruction(DepWrite, *MD, TLI);
540 // DeleteDeadInstruction can delete the current instruction in loop
543 if (BBI != BB.begin())
546 } else if (OR == OverwriteEnd && isShortenable(DepWrite)) {
547 // TODO: base this on the target vector size so that if the earlier
548 // store was too small to get vector writes anyway then its likely
549 // a good idea to shorten it
550 // Power of 2 vector writes are probably always a bad idea to optimize
551 // as any store/memset/memcpy is likely using vector instructions so
552 // shortening it to not vector size is likely to be slower
553 MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
554 unsigned DepWriteAlign = DepIntrinsic->getAlignment();
555 if (llvm::isPowerOf2_64(InstWriteOffset) ||
556 ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
558 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW END: "
559 << *DepWrite << "\n KILLER (offset "
560 << InstWriteOffset << ", "
561 << DepLoc.Size << ")"
564 Value* DepWriteLength = DepIntrinsic->getLength();
565 Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(),
568 DepIntrinsic->setLength(TrimmedLength);
574 // If this is a may-aliased store that is clobbering the store value, we
575 // can keep searching past it for another must-aliased pointer that stores
576 // to the same location. For example, in:
580 // we can remove the first store to P even though we don't know if P and Q
582 if (DepWrite == &BB.front()) break;
584 // Can't look past this instruction if it might read 'Loc'.
585 if (AA->getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
588 InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
592 // If this block ends in a return, unwind, or unreachable, all allocas are
593 // dead at its end, which means stores to them are also dead.
594 if (BB.getTerminator()->getNumSuccessors() == 0)
595 MadeChange |= handleEndBlock(BB);
600 /// Find all blocks that will unconditionally lead to the block BB and append
602 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
603 BasicBlock *BB, DominatorTree *DT) {
604 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
605 BasicBlock *Pred = *I;
606 if (Pred == BB) continue;
607 TerminatorInst *PredTI = Pred->getTerminator();
608 if (PredTI->getNumSuccessors() != 1)
611 if (DT->isReachableFromEntry(Pred))
612 Blocks.push_back(Pred);
616 /// HandleFree - Handle frees of entire structures whose dependency is a store
617 /// to a field of that structure.
618 bool DSE::HandleFree(CallInst *F) {
619 bool MadeChange = false;
621 AliasAnalysis::Location Loc = AliasAnalysis::Location(F->getOperand(0));
622 SmallVector<BasicBlock *, 16> Blocks;
623 Blocks.push_back(F->getParent());
625 while (!Blocks.empty()) {
626 BasicBlock *BB = Blocks.pop_back_val();
627 Instruction *InstPt = BB->getTerminator();
628 if (BB == F->getParent()) InstPt = F;
630 MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
631 while (Dep.isDef() || Dep.isClobber()) {
632 Instruction *Dependency = Dep.getInst();
633 if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
637 GetUnderlyingObject(getStoredPointerOperand(Dependency));
639 // Check for aliasing.
640 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
643 Instruction *Next = llvm::next(BasicBlock::iterator(Dependency));
645 // DCE instructions only used to calculate that store
646 DeleteDeadInstruction(Dependency, *MD, TLI);
650 // Inst's old Dependency is now deleted. Compute the next dependency,
651 // which may also be dead, as in
653 // s[1] = 0; // This has just been deleted.
655 Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
658 if (Dep.isNonLocal())
659 FindUnconditionalPreds(Blocks, BB, DT);
665 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
666 /// function end block. Ex:
669 /// store i32 1, i32* %A
671 bool DSE::handleEndBlock(BasicBlock &BB) {
672 bool MadeChange = false;
674 // Keep track of all of the stack objects that are dead at the end of the
676 SmallSetVector<Value*, 16> DeadStackObjects;
678 // Find all of the alloca'd pointers in the entry block.
679 BasicBlock *Entry = BB.getParent()->begin();
680 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
681 if (isa<AllocaInst>(I))
682 DeadStackObjects.insert(I);
684 // Okay, so these are dead heap objects, but if the pointer never escapes
685 // then it's leaked by this function anyways.
686 else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
687 DeadStackObjects.insert(I);
690 // Treat byval arguments the same, stores to them are dead at the end of the
692 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
693 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
694 if (AI->hasByValAttr())
695 DeadStackObjects.insert(AI);
697 // Scan the basic block backwards
698 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
701 // If we find a store, check to see if it points into a dead stack value.
702 if (hasMemoryWrite(BBI) && isRemovable(BBI)) {
703 // See through pointer-to-pointer bitcasts
704 SmallVector<Value *, 4> Pointers;
705 GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers);
707 // Stores to stack values are valid candidates for removal.
709 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
710 E = Pointers.end(); I != E; ++I)
711 if (!DeadStackObjects.count(*I)) {
717 Instruction *Dead = BBI++;
719 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
720 << *Dead << "\n Objects: ";
721 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
722 E = Pointers.end(); I != E; ++I) {
724 if (llvm::next(I) != E)
729 // DCE instructions only used to calculate that store.
730 DeleteDeadInstruction(Dead, *MD, TLI, &DeadStackObjects);
737 // Remove any dead non-memory-mutating instructions.
738 if (isInstructionTriviallyDead(BBI, TLI)) {
739 Instruction *Inst = BBI++;
740 DeleteDeadInstruction(Inst, *MD, TLI, &DeadStackObjects);
746 if (isa<AllocaInst>(BBI)) {
747 // Remove allocas from the list of dead stack objects; there can't be
748 // any references before the definition.
749 DeadStackObjects.remove(BBI);
753 if (CallSite CS = cast<Value>(BBI)) {
754 // Remove allocation function calls from the list of dead stack objects;
755 // there can't be any references before the definition.
756 if (isAllocLikeFn(BBI, TLI))
757 DeadStackObjects.remove(BBI);
759 // If this call does not access memory, it can't be loading any of our
761 if (AA->doesNotAccessMemory(CS))
764 // If the call might load from any of our allocas, then any store above
766 SmallVector<Value*, 8> LiveAllocas;
767 for (SmallSetVector<Value*, 16>::iterator I = DeadStackObjects.begin(),
768 E = DeadStackObjects.end(); I != E; ++I) {
769 // See if the call site touches it.
770 AliasAnalysis::ModRefResult A =
771 AA->getModRefInfo(CS, *I, getPointerSize(*I, *AA));
773 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
774 LiveAllocas.push_back(*I);
777 // If all of the allocas were clobbered by the call then we're not going
778 // to find anything else to process.
779 if (DeadStackObjects.size() == LiveAllocas.size())
782 for (SmallVector<Value*, 8>::iterator I = LiveAllocas.begin(),
783 E = LiveAllocas.end(); I != E; ++I)
784 DeadStackObjects.remove(*I);
789 AliasAnalysis::Location LoadedLoc;
791 // If we encounter a use of the pointer, it is no longer considered dead
792 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
793 if (!L->isUnordered()) // Be conservative with atomic/volatile load
795 LoadedLoc = AA->getLocation(L);
796 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
797 LoadedLoc = AA->getLocation(V);
798 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
799 LoadedLoc = AA->getLocationForSource(MTI);
800 } else if (!BBI->mayReadFromMemory()) {
801 // Instruction doesn't read memory. Note that stores that weren't removed
802 // above will hit this case.
805 // Unknown inst; assume it clobbers everything.
809 // Remove any allocas from the DeadPointer set that are loaded, as this
810 // makes any stores above the access live.
811 RemoveAccessedObjects(LoadedLoc, DeadStackObjects);
813 // If all of the allocas were clobbered by the access then we're not going
814 // to find anything else to process.
815 if (DeadStackObjects.empty())
822 /// RemoveAccessedObjects - Check to see if the specified location may alias any
823 /// of the stack objects in the DeadStackObjects set. If so, they become live
824 /// because the location is being loaded.
825 void DSE::RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
826 SmallSetVector<Value*, 16> &DeadStackObjects) {
827 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr);
829 // A constant can't be in the dead pointer set.
830 if (isa<Constant>(UnderlyingPointer))
833 // If the kill pointer can be easily reduced to an alloca, don't bother doing
834 // extraneous AA queries.
835 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
836 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
840 SmallVector<Value*, 16> NowLive;
841 for (SmallSetVector<Value*, 16>::iterator I = DeadStackObjects.begin(),
842 E = DeadStackObjects.end(); I != E; ++I) {
843 // See if the loaded location could alias the stack location.
844 AliasAnalysis::Location StackLoc(*I, getPointerSize(*I, *AA));
845 if (!AA->isNoAlias(StackLoc, LoadedLoc))
846 NowLive.push_back(*I);
849 for (SmallVector<Value*, 16>::iterator I = NowLive.begin(), E = NowLive.end();
851 DeadStackObjects.remove(*I);