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 handleFreeWithNonTrivialDependency(const CallInst *F,
63 bool handleEndBlock(BasicBlock &BB);
64 bool RemoveUndeadPointers(Value *Ptr, unsigned killPointerSize,
65 BasicBlock::iterator &BBI,
66 SmallPtrSet<Value*, 64> &deadPointers);
67 void DeleteDeadInstruction(Instruction *I,
68 SmallPtrSet<Value*, 64> *deadPointers = 0);
71 // getAnalysisUsage - We require post dominance frontiers (aka Control
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<DominatorTree>();
76 AU.addRequired<AliasAnalysis>();
77 AU.addRequired<MemoryDependenceAnalysis>();
78 AU.addPreserved<DominatorTree>();
79 AU.addPreserved<MemoryDependenceAnalysis>();
82 unsigned getPointerSize(Value *V) const;
87 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
88 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
89 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
90 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
91 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
93 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
95 /// doesClobberMemory - Does this instruction clobber (write without reading)
97 static bool doesClobberMemory(Instruction *I) {
98 if (isa<StoreInst>(I))
100 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
101 switch (II->getIntrinsicID()) {
104 case Intrinsic::memset:
105 case Intrinsic::memmove:
106 case Intrinsic::memcpy:
107 case Intrinsic::init_trampoline:
108 case Intrinsic::lifetime_end:
115 /// isElidable - If the value of this instruction and the memory it writes to is
116 /// unused, may we delete this instrtction?
117 static bool isElidable(Instruction *I) {
118 assert(doesClobberMemory(I));
119 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
120 return II->getIntrinsicID() != Intrinsic::lifetime_end;
121 if (StoreInst *SI = dyn_cast<StoreInst>(I))
122 return !SI->isVolatile();
126 /// getPointerOperand - Return the pointer that is being clobbered.
127 static Value *getPointerOperand(Instruction *I) {
128 assert(doesClobberMemory(I));
129 if (StoreInst *SI = dyn_cast<StoreInst>(I))
130 return SI->getPointerOperand();
131 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
132 return MI->getArgOperand(0);
134 IntrinsicInst *II = cast<IntrinsicInst>(I);
135 switch (II->getIntrinsicID()) {
136 default: assert(false && "Unexpected intrinsic!");
137 case Intrinsic::init_trampoline:
138 return II->getArgOperand(0);
139 case Intrinsic::lifetime_end:
140 return II->getArgOperand(1);
144 /// getStoreSize - Return the length in bytes of the write by the clobbering
145 /// instruction. If variable or unknown, returns -1.
146 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
147 assert(doesClobberMemory(I));
148 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
150 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
154 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
155 Len = MI->getLength();
157 IntrinsicInst *II = cast<IntrinsicInst>(I);
158 switch (II->getIntrinsicID()) {
159 default: assert(false && "Unexpected intrinsic!");
160 case Intrinsic::init_trampoline:
162 case Intrinsic::lifetime_end:
163 Len = II->getArgOperand(0);
167 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
168 if (!LenCI->isAllOnesValue())
169 return LenCI->getZExtValue();
173 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
174 /// greater than or equal to the store in I2. This returns false if we don't
177 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
178 const TargetData *TD) {
179 const Type *I1Ty = getPointerOperand(I1)->getType();
180 const Type *I2Ty = getPointerOperand(I2)->getType();
182 // Exactly the same type, must have exactly the same size.
183 if (I1Ty == I2Ty) return true;
185 int I1Size = getStoreSize(I1, TD);
186 int I2Size = getStoreSize(I2, TD);
188 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
191 bool DSE::runOnBasicBlock(BasicBlock &BB) {
192 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
193 TD = getAnalysisIfAvailable<TargetData>();
195 bool MadeChange = false;
197 // Do a top-down walk on the BB.
198 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
199 Instruction *Inst = BBI++;
201 // If we find a store or a free, get its memory dependence.
202 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
205 MemDepResult InstDep = MD.getDependency(Inst);
207 // Ignore non-local stores.
208 // FIXME: cross-block DSE would be fun. :)
209 if (InstDep.isNonLocal()) continue;
211 // Handle frees whose dependencies are non-trivial.
212 if (const CallInst *F = isFreeCall(Inst)) {
213 MadeChange |= handleFreeWithNonTrivialDependency(F, InstDep);
217 // If not a definite must-alias dependency, ignore it.
218 if (!InstDep.isDef())
221 // If this is a store-store dependence, then the previous store is dead so
222 // long as this store is at least as big as it.
223 if (doesClobberMemory(InstDep.getInst())) {
224 Instruction *DepStore = InstDep.getInst();
225 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
226 isElidable(DepStore)) {
227 // Delete the store and now-dead instructions that feed it.
228 DeleteDeadInstruction(DepStore);
232 // DeleteDeadInstruction can delete the current instruction in loop
235 if (BBI != BB.begin())
241 if (!isElidable(Inst))
244 // If we're storing the same value back to a pointer that we just
245 // loaded from, then the store can be removed.
246 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
247 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
248 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
249 SI->getOperand(0) == DepLoad) {
250 // DeleteDeadInstruction can delete the current instruction. Save BBI
251 // in case we need it.
252 WeakVH NextInst(BBI);
254 DeleteDeadInstruction(SI);
256 if (NextInst == 0) // Next instruction deleted.
258 else if (BBI != BB.begin()) // Revisit this instruction if possible.
267 // If this is a lifetime end marker, we can throw away the store.
268 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
269 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
270 // Delete the store and now-dead instructions that feed it.
271 // DeleteDeadInstruction can delete the current instruction. Save BBI
272 // in case we need it.
273 WeakVH NextInst(BBI);
275 DeleteDeadInstruction(Inst);
277 if (NextInst == 0) // Next instruction deleted.
279 else if (BBI != BB.begin()) // Revisit this instruction if possible.
288 // If this block ends in a return, unwind, or unreachable, all allocas are
289 // dead at its end, which means stores to them are also dead.
290 if (BB.getTerminator()->getNumSuccessors() == 0)
291 MadeChange |= handleEndBlock(BB);
296 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
297 /// dependency is a store to a field of that structure.
298 bool DSE::handleFreeWithNonTrivialDependency(const CallInst *F,
300 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
302 Instruction *Dependency = Dep.getInst();
303 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
306 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
308 // Check for aliasing.
309 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
310 AliasAnalysis::MustAlias)
313 // DCE instructions only used to calculate that store
314 DeleteDeadInstruction(Dependency);
319 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
320 /// function end block. Ex:
323 /// store i32 1, i32* %A
325 bool DSE::handleEndBlock(BasicBlock &BB) {
326 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
328 bool MadeChange = false;
330 // Pointers alloca'd in this function are dead in the end block
331 SmallPtrSet<Value*, 64> deadPointers;
333 // Find all of the alloca'd pointers in the entry block.
334 BasicBlock *Entry = BB.getParent()->begin();
335 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
336 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
337 deadPointers.insert(AI);
339 // Treat byval arguments the same, stores to them are dead at the end of the
341 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
342 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
343 if (AI->hasByValAttr())
344 deadPointers.insert(AI);
346 // Scan the basic block backwards
347 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
350 // If we find a store whose pointer is dead.
351 if (doesClobberMemory(BBI)) {
352 if (isElidable(BBI)) {
353 // See through pointer-to-pointer bitcasts
354 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
356 // Alloca'd pointers or byval arguments (which are functionally like
357 // alloca's) are valid candidates for removal.
358 if (deadPointers.count(pointerOperand)) {
359 // DCE instructions only used to calculate that store.
360 Instruction *Dead = BBI;
362 DeleteDeadInstruction(Dead, &deadPointers);
369 // Because a memcpy or memmove is also a load, we can't skip it if we
371 if (!isa<MemTransferInst>(BBI))
375 Value *killPointer = 0;
376 unsigned killPointerSize = AliasAnalysis::UnknownSize;
378 // If we encounter a use of the pointer, it is no longer considered dead
379 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
380 // However, if this load is unused and not volatile, we can go ahead and
381 // remove it, and not have to worry about it making our pointer undead!
382 if (L->use_empty() && !L->isVolatile()) {
384 DeleteDeadInstruction(L, &deadPointers);
390 killPointer = L->getPointerOperand();
391 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
392 killPointer = V->getOperand(0);
393 } else if (isa<MemTransferInst>(BBI) &&
394 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
395 killPointer = cast<MemTransferInst>(BBI)->getSource();
396 killPointerSize = cast<ConstantInt>(
397 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
398 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
399 deadPointers.erase(A);
401 // Dead alloca's can be DCE'd when we reach them
402 if (A->use_empty()) {
404 DeleteDeadInstruction(A, &deadPointers);
410 } else if (CallSite CS = cast<Value>(BBI)) {
411 // If this call does not access memory, it can't
412 // be undeadifying any of our pointers.
413 if (AA.doesNotAccessMemory(CS))
419 // Remove any pointers made undead by the call from the dead set
420 std::vector<Value*> dead;
421 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
422 E = deadPointers.end(); I != E; ++I) {
423 // HACK: if we detect that our AA is imprecise, it's not
424 // worth it to scan the rest of the deadPointers set. Just
425 // assume that the AA will return ModRef for everything, and
426 // go ahead and bail.
427 if (modRef >= 16 && other == 0) {
428 deadPointers.clear();
432 // See if the call site touches it
433 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
436 if (A == AliasAnalysis::ModRef)
441 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
445 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
447 deadPointers.erase(*I);
450 } else if (isInstructionTriviallyDead(BBI)) {
451 // For any non-memory-affecting non-terminators, DCE them as we reach them
452 Instruction *Inst = BBI;
454 DeleteDeadInstruction(Inst, &deadPointers);
463 killPointer = killPointer->getUnderlyingObject();
465 // Deal with undead pointers
466 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
473 /// RemoveUndeadPointers - check for uses of a pointer that make it
474 /// undead when scanning for dead stores to alloca's.
475 bool DSE::RemoveUndeadPointers(Value *killPointer, unsigned killPointerSize,
476 BasicBlock::iterator &BBI,
477 SmallPtrSet<Value*, 64> &deadPointers) {
478 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
480 // If the kill pointer can be easily reduced to an alloca,
481 // don't bother doing extraneous AA queries.
482 if (deadPointers.count(killPointer)) {
483 deadPointers.erase(killPointer);
487 // A global can't be in the dead pointer set.
488 if (isa<GlobalValue>(killPointer))
491 bool MadeChange = false;
493 SmallVector<Value*, 16> undead;
495 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
496 E = deadPointers.end(); I != E; ++I) {
497 // See if this pointer could alias it
498 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
499 killPointer, killPointerSize);
501 // If it must-alias and a store, we can delete it
502 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
503 StoreInst *S = cast<StoreInst>(BBI);
507 DeleteDeadInstruction(S, &deadPointers);
513 // Otherwise, it is undead
514 } else if (A != AliasAnalysis::NoAlias)
515 undead.push_back(*I);
518 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
520 deadPointers.erase(*I);
525 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
526 /// and zero out all the operands of this instruction. If any of them become
527 /// dead, delete them and the computation tree that feeds them.
529 /// If ValueSet is non-null, remove any deleted instructions from it as well.
531 void DSE::DeleteDeadInstruction(Instruction *I,
532 SmallPtrSet<Value*, 64> *ValueSet) {
533 SmallVector<Instruction*, 32> NowDeadInsts;
535 NowDeadInsts.push_back(I);
538 // Before we touch this instruction, remove it from memdep!
539 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
541 Instruction *DeadInst = NowDeadInsts.pop_back_val();
545 // This instruction is dead, zap it, in stages. Start by removing it from
546 // MemDep, which needs to know the operands and needs it to be in the
548 MDA.removeInstruction(DeadInst);
550 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
551 Value *Op = DeadInst->getOperand(op);
552 DeadInst->setOperand(op, 0);
554 // If this operand just became dead, add it to the NowDeadInsts list.
555 if (!Op->use_empty()) continue;
557 if (Instruction *OpI = dyn_cast<Instruction>(Op))
558 if (isInstructionTriviallyDead(OpI))
559 NowDeadInsts.push_back(OpI);
562 DeadInst->eraseFromParent();
564 if (ValueSet) ValueSet->erase(DeadInst);
565 } while (!NowDeadInsts.empty());
568 unsigned DSE::getPointerSize(Value *V) const {
570 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
571 // Get size information for the alloca
572 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
573 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
575 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
576 const PointerType *PT = cast<PointerType>(V->getType());
577 return TD->getTypeAllocSize(PT->getElementType());
580 return AliasAnalysis::UnknownSize;