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/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Transforms/Utils/Local.h"
35 STATISTIC(NumFastStores, "Number of stores deleted");
36 STATISTIC(NumFastOther , "Number of other instrs removed");
39 struct DSE : public FunctionPass {
42 static char ID; // Pass identification, replacement for typeid
43 DSE() : FunctionPass(ID) {
44 initializeDSEPass(*PassRegistry::getPassRegistry());
47 virtual bool runOnFunction(Function &F) {
50 DominatorTree &DT = getAnalysis<DominatorTree>();
52 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
53 // Only check non-dead blocks. Dead blocks may have strange pointer
54 // cycles that will confuse alias analysis.
55 if (DT.isReachableFromEntry(I))
56 Changed |= runOnBasicBlock(*I);
60 bool runOnBasicBlock(BasicBlock &BB);
61 bool HandleFree(CallInst *F);
62 bool handleEndBlock(BasicBlock &BB);
63 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
64 BasicBlock::iterator &BBI,
65 SmallPtrSet<Value*, 64> &deadPointers);
66 void DeleteDeadInstruction(Instruction *I,
67 SmallPtrSet<Value*, 64> *deadPointers = 0);
70 // getAnalysisUsage - We require post dominance frontiers (aka Control
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<DominatorTree>();
75 AU.addRequired<AliasAnalysis>();
76 AU.addRequired<MemoryDependenceAnalysis>();
77 AU.addPreserved<DominatorTree>();
78 AU.addPreserved<MemoryDependenceAnalysis>();
81 uint64_t getPointerSize(Value *V) const;
86 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
87 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
88 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
89 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
92 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
94 /// hasMemoryWrite - Does this instruction write some memory? This only returns
95 /// true for things that we can analyze with other helpers below.
96 static bool hasMemoryWrite(Instruction *I) {
97 if (isa<StoreInst>(I))
99 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
100 switch (II->getIntrinsicID()) {
103 case Intrinsic::memset:
104 case Intrinsic::memmove:
105 case Intrinsic::memcpy:
106 case Intrinsic::init_trampoline:
107 case Intrinsic::lifetime_end:
114 /// getLocForWrite - Return a Location stored to by the specified instruction.
115 static AliasAnalysis::Location
116 getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
117 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
118 return AA.getLocation(SI);
120 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
121 // memcpy/memmove/memset.
122 AliasAnalysis::Location Loc = AA.getLocationForDest(MI);
123 // If we don't have target data around, an unknown size in Location means
124 // that we should use the size of the pointee type. This isn't valid for
125 // memset/memcpy, which writes more than an i8.
126 if (Loc.Size == AliasAnalysis::UnknownSize && AA.getTargetData() == 0)
127 return AliasAnalysis::Location();
131 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
132 if (II == 0) return AliasAnalysis::Location();
134 switch (II->getIntrinsicID()) {
135 default: return AliasAnalysis::Location(); // Unhandled intrinsic.
136 case Intrinsic::init_trampoline:
137 // If we don't have target data around, an unknown size in Location means
138 // that we should use the size of the pointee type. This isn't valid for
139 // init.trampoline, which writes more than an i8.
140 if (AA.getTargetData() == 0) return AliasAnalysis::Location();
142 // FIXME: We don't know the size of the trampoline, so we can't really
144 return AliasAnalysis::Location(II->getArgOperand(0));
145 case Intrinsic::lifetime_end: {
146 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
147 return AliasAnalysis::Location(II->getArgOperand(1), Len);
152 /// isRemovable - If the value of this instruction and the memory it writes to
153 /// is unused, may we delete this instruction?
154 static bool isRemovable(Instruction *I) {
155 // Don't remove volatile stores.
156 if (StoreInst *SI = dyn_cast<StoreInst>(I))
157 return !SI->isVolatile();
159 IntrinsicInst *II = cast<IntrinsicInst>(I);
160 switch (II->getIntrinsicID()) {
161 default: assert(0 && "doesn't pass 'hasMemoryWrite' predicate");
162 case Intrinsic::lifetime_end:
163 // Never remove dead lifetime_end's, e.g. because it is followed by a
166 case Intrinsic::init_trampoline:
167 // Always safe to remove init_trampoline.
170 case Intrinsic::memset:
171 case Intrinsic::memmove:
172 case Intrinsic::memcpy:
173 // Don't remove volatile memory intrinsics.
174 return !cast<MemIntrinsic>(II)->isVolatile();
178 /// getPointerOperand - Return the pointer that is being written to.
179 static Value *getPointerOperand(Instruction *I) {
180 assert(hasMemoryWrite(I));
181 if (StoreInst *SI = dyn_cast<StoreInst>(I))
182 return SI->getPointerOperand();
183 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
184 return MI->getArgOperand(0);
186 IntrinsicInst *II = cast<IntrinsicInst>(I);
187 switch (II->getIntrinsicID()) {
188 default: assert(false && "Unexpected intrinsic!");
189 case Intrinsic::init_trampoline:
190 return II->getArgOperand(0);
191 case Intrinsic::lifetime_end:
192 return II->getArgOperand(1);
196 /// isCompleteOverwrite - Return true if a store to the 'Later' location
197 /// completely overwrites a store to the 'Earlier' location.
198 static bool isCompleteOverwrite(const AliasAnalysis::Location &Later,
199 const AliasAnalysis::Location &Earlier,
200 AliasAnalysis &AA, const TargetData *TD) {
201 const Value *P1 = Later.Ptr->stripPointerCasts();
202 const Value *P2 = Earlier.Ptr->stripPointerCasts();
204 // Make sure that the start pointers are the same.
208 // If we have no TargetData information around, then the size of the store is
209 // inferrable from the pointee type. If they are the same type, then we know
210 // that the store is safe.
212 return Later.Ptr->getType() == Earlier.Ptr->getType();
215 // Make sure that the Later size is >= the Earlier size.
216 if (Later.Size < Earlier.Size)
222 bool DSE::runOnBasicBlock(BasicBlock &BB) {
223 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
224 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
225 TD = getAnalysisIfAvailable<TargetData>();
227 bool MadeChange = false;
229 // Do a top-down walk on the BB.
230 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
231 Instruction *Inst = BBI++;
233 // Handle 'free' calls specially.
234 if (CallInst *F = isFreeCall(Inst)) {
235 MadeChange |= HandleFree(F);
239 // If we find something that writes memory, get its memory dependence.
240 if (!hasMemoryWrite(Inst))
243 MemDepResult InstDep = MD.getDependency(Inst);
245 // Ignore non-local store liveness.
246 // FIXME: cross-block DSE would be fun. :)
247 if (InstDep.isNonLocal() ||
248 // Ignore self dependence, which happens in the entry block of the
250 InstDep.getInst() == Inst)
253 // If we're storing the same value back to a pointer that we just
254 // loaded from, then the store can be removed.
255 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
256 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
257 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
258 SI->getOperand(0) == DepLoad && !SI->isVolatile()) {
259 // DeleteDeadInstruction can delete the current instruction. Save BBI
260 // in case we need it.
261 WeakVH NextInst(BBI);
263 DeleteDeadInstruction(SI);
265 if (NextInst == 0) // Next instruction deleted.
267 else if (BBI != BB.begin()) // Revisit this instruction if possible.
276 // Figure out what location is being stored to.
277 AliasAnalysis::Location Loc = getLocForWrite(Inst, AA);
279 // If we didn't get a useful location, fail.
283 while (!InstDep.isNonLocal()) {
284 // Get the memory clobbered by the instruction we depend on. MemDep will
285 // skip any instructions that 'Loc' clearly doesn't interact with. If we
286 // end up depending on a may- or must-aliased load, then we can't optimize
287 // away the store and we bail out. However, if we depend on on something
288 // that overwrites the memory location we *can* potentially optimize it.
290 // Find out what memory location the dependant instruction stores.
291 Instruction *DepWrite = InstDep.getInst();
292 AliasAnalysis::Location DepLoc = getLocForWrite(DepWrite, AA);
293 // If we didn't get a useful location, or if it isn't a size, bail out.
297 // If we find a removable write that is completely obliterated by the
298 // store to 'Loc' then we can remove it.
299 if (isRemovable(DepWrite) && isCompleteOverwrite(Loc, DepLoc, AA, TD)) {
300 // Delete the store and now-dead instructions that feed it.
301 DeleteDeadInstruction(DepWrite);
305 // DeleteDeadInstruction can delete the current instruction in loop
308 if (BBI != BB.begin())
313 // If this is a may-aliased store that is clobbering the store value, we
314 // can keep searching past it for another must-aliased pointer that stores
315 // to the same location. For example, in:
319 // we can remove the first store to P even though we don't know if P and Q
321 if (DepWrite == &BB.front()) break;
323 // Can't look past this instruction if it might read 'Loc'.
324 if (AA.getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
327 InstDep = MD.getPointerDependencyFrom(Loc, false, DepWrite, &BB);
331 // If this block ends in a return, unwind, or unreachable, all allocas are
332 // dead at its end, which means stores to them are also dead.
333 if (BB.getTerminator()->getNumSuccessors() == 0)
334 MadeChange |= handleEndBlock(BB);
339 /// HandleFree - Handle frees of entire structures whose dependency is a store
340 /// to a field of that structure.
341 bool DSE::HandleFree(CallInst *F) {
342 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
343 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
345 MemDepResult Dep = MD.getDependency(F);
347 if (Dep.isNonLocal()) return false;
349 Instruction *Dependency = Dep.getInst();
350 if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
353 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
355 // Check for aliasing.
356 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
357 AliasAnalysis::MustAlias)
360 // DCE instructions only used to calculate that store
361 DeleteDeadInstruction(Dependency);
364 // Inst's old Dependency is now deleted. Compute the next dependency,
365 // which may also be dead, as in
367 // s[1] = 0; // This has just been deleted.
369 Dep = MD.getDependency(F);
370 } while (!Dep.isNonLocal());
375 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
376 /// function end block. Ex:
379 /// store i32 1, i32* %A
381 bool DSE::handleEndBlock(BasicBlock &BB) {
382 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
384 bool MadeChange = false;
386 // Pointers alloca'd in this function are dead in the end block
387 SmallPtrSet<Value*, 64> deadPointers;
389 // Find all of the alloca'd pointers in the entry block.
390 BasicBlock *Entry = BB.getParent()->begin();
391 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
392 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
393 deadPointers.insert(AI);
395 // Treat byval arguments the same, stores to them are dead at the end of the
397 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
398 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
399 if (AI->hasByValAttr())
400 deadPointers.insert(AI);
402 // Scan the basic block backwards
403 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
406 // If we find a store whose pointer is dead.
407 if (hasMemoryWrite(BBI)) {
408 if (isRemovable(BBI)) {
409 // See through pointer-to-pointer bitcasts
410 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
412 // Alloca'd pointers or byval arguments (which are functionally like
413 // alloca's) are valid candidates for removal.
414 if (deadPointers.count(pointerOperand)) {
415 // DCE instructions only used to calculate that store.
416 Instruction *Dead = BBI;
418 DeleteDeadInstruction(Dead, &deadPointers);
425 // Because a memcpy or memmove is also a load, we can't skip it if we
427 if (!isa<MemTransferInst>(BBI))
431 Value *killPointer = 0;
432 uint64_t killPointerSize = AliasAnalysis::UnknownSize;
434 // If we encounter a use of the pointer, it is no longer considered dead
435 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
436 // However, if this load is unused and not volatile, we can go ahead and
437 // remove it, and not have to worry about it making our pointer undead!
438 if (L->use_empty() && !L->isVolatile()) {
440 DeleteDeadInstruction(L, &deadPointers);
446 killPointer = L->getPointerOperand();
447 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
448 killPointer = V->getOperand(0);
449 } else if (isa<MemTransferInst>(BBI) &&
450 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
451 killPointer = cast<MemTransferInst>(BBI)->getSource();
452 killPointerSize = cast<ConstantInt>(
453 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
454 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
455 deadPointers.erase(A);
457 // Dead alloca's can be DCE'd when we reach them
458 if (A->use_empty()) {
460 DeleteDeadInstruction(A, &deadPointers);
466 } else if (CallSite CS = cast<Value>(BBI)) {
467 // If this call does not access memory, it can't
468 // be undeadifying any of our pointers.
469 if (AA.doesNotAccessMemory(CS))
475 // Remove any pointers made undead by the call from the dead set
476 std::vector<Value*> dead;
477 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
478 E = deadPointers.end(); I != E; ++I) {
479 // HACK: if we detect that our AA is imprecise, it's not
480 // worth it to scan the rest of the deadPointers set. Just
481 // assume that the AA will return ModRef for everything, and
482 // go ahead and bail.
483 if (modRef >= 16 && other == 0) {
484 deadPointers.clear();
488 // See if the call site touches it
489 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
492 if (A == AliasAnalysis::ModRef)
497 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
501 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
503 deadPointers.erase(*I);
506 } else if (isInstructionTriviallyDead(BBI)) {
507 // For any non-memory-affecting non-terminators, DCE them as we reach them
508 Instruction *Inst = BBI;
510 DeleteDeadInstruction(Inst, &deadPointers);
519 killPointer = killPointer->getUnderlyingObject();
521 // Deal with undead pointers
522 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
529 /// RemoveUndeadPointers - check for uses of a pointer that make it
530 /// undead when scanning for dead stores to alloca's.
531 bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
532 BasicBlock::iterator &BBI,
533 SmallPtrSet<Value*, 64> &deadPointers) {
534 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
536 // If the kill pointer can be easily reduced to an alloca,
537 // don't bother doing extraneous AA queries.
538 if (deadPointers.count(killPointer)) {
539 deadPointers.erase(killPointer);
543 // A global can't be in the dead pointer set.
544 if (isa<GlobalValue>(killPointer))
547 bool MadeChange = false;
549 SmallVector<Value*, 16> undead;
551 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
552 E = deadPointers.end(); I != E; ++I) {
553 // See if this pointer could alias it
554 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
555 killPointer, killPointerSize);
557 // If it must-alias and a store, we can delete it
558 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
559 StoreInst *S = cast<StoreInst>(BBI);
563 DeleteDeadInstruction(S, &deadPointers);
569 // Otherwise, it is undead
570 } else if (A != AliasAnalysis::NoAlias)
571 undead.push_back(*I);
574 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
576 deadPointers.erase(*I);
581 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
582 /// and zero out all the operands of this instruction. If any of them become
583 /// dead, delete them and the computation tree that feeds them.
585 /// If ValueSet is non-null, remove any deleted instructions from it as well.
587 void DSE::DeleteDeadInstruction(Instruction *I,
588 SmallPtrSet<Value*, 64> *ValueSet) {
589 SmallVector<Instruction*, 32> NowDeadInsts;
591 NowDeadInsts.push_back(I);
594 // Before we touch this instruction, remove it from memdep!
595 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
597 Instruction *DeadInst = NowDeadInsts.pop_back_val();
601 // This instruction is dead, zap it, in stages. Start by removing it from
602 // MemDep, which needs to know the operands and needs it to be in the
604 MDA.removeInstruction(DeadInst);
606 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
607 Value *Op = DeadInst->getOperand(op);
608 DeadInst->setOperand(op, 0);
610 // If this operand just became dead, add it to the NowDeadInsts list.
611 if (!Op->use_empty()) continue;
613 if (Instruction *OpI = dyn_cast<Instruction>(Op))
614 if (isInstructionTriviallyDead(OpI))
615 NowDeadInsts.push_back(OpI);
618 DeadInst->eraseFromParent();
620 if (ValueSet) ValueSet->erase(DeadInst);
621 } while (!NowDeadInsts.empty());
624 uint64_t DSE::getPointerSize(Value *V) const {
626 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
627 // Get size information for the alloca
628 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
629 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
631 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
632 const PointerType *PT = cast<PointerType>(V->getType());
633 return TD->getTypeAllocSize(PT->getElementType());
636 return AliasAnalysis::UnknownSize;