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) {}
45 virtual bool runOnFunction(Function &F) {
47 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
48 Changed |= runOnBasicBlock(*I);
52 bool runOnBasicBlock(BasicBlock &BB);
53 bool handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep);
54 bool handleEndBlock(BasicBlock &BB);
55 bool RemoveUndeadPointers(Value* Ptr, uint64_t killPointerSize,
56 BasicBlock::iterator& BBI,
57 SmallPtrSet<Value*, 64>& deadPointers);
58 void DeleteDeadInstruction(Instruction *I,
59 SmallPtrSet<Value*, 64> *deadPointers = 0);
62 // getAnalysisUsage - We require post dominance frontiers (aka Control
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<AliasAnalysis>();
68 AU.addRequired<MemoryDependenceAnalysis>();
69 AU.addPreserved<DominatorTree>();
70 AU.addPreserved<AliasAnalysis>();
71 AU.addPreserved<MemoryDependenceAnalysis>();
77 static RegisterPass<DSE> X("dse", "Dead Store Elimination");
79 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
81 /// doesClobberMemory - Does this instruction clobber (write without reading)
83 static bool doesClobberMemory(Instruction *I) {
84 if (isa<StoreInst>(I))
86 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
87 switch (II->getIntrinsicID()) {
88 default: return false;
89 case Intrinsic::memset: case Intrinsic::memmove: case Intrinsic::memcpy:
90 case Intrinsic::init_trampoline: case Intrinsic::lifetime_end: return true;
96 /// isElidable - If the value of this instruction and the memory it writes to is
97 /// unused, may we delete this instrtction?
98 static bool isElidable(Instruction *I) {
99 assert(doesClobberMemory(I));
100 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
101 return II->getIntrinsicID() != Intrinsic::lifetime_end;
102 if (StoreInst *SI = dyn_cast<StoreInst>(I))
103 return !SI->isVolatile();
107 /// getPointerOperand - Return the pointer that is being clobbered.
108 static Value *getPointerOperand(Instruction *I) {
109 assert(doesClobberMemory(I));
110 if (StoreInst *SI = dyn_cast<StoreInst>(I))
111 return SI->getPointerOperand();
112 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
113 return MI->getOperand(1);
114 IntrinsicInst *II = cast<IntrinsicInst>(I);
115 switch (II->getIntrinsicID()) {
117 assert(false && "Unexpected intrinsic!");
118 case Intrinsic::init_trampoline:
119 return II->getOperand(1);
120 case Intrinsic::lifetime_end:
121 return II->getOperand(2);
125 /// getStoreSize - Return the length in bytes of the write by the clobbering
126 /// instruction. If variable or unknown, returns -1.
127 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
128 assert(doesClobberMemory(I));
129 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
131 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
135 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
136 Len = MI->getLength();
138 IntrinsicInst *II = cast<IntrinsicInst>(I);
139 switch (II->getIntrinsicID()) {
141 assert(false && "Unexpected intrinsic!");
142 case Intrinsic::init_trampoline:
144 case Intrinsic::lifetime_end:
145 Len = II->getOperand(1);
148 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
149 if (!LenCI->isAllOnesValue())
150 return LenCI->getZExtValue();
154 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
155 /// greater than or equal to the store in I2. This returns false if we don't
158 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
159 const TargetData *TD) {
160 const Type *I1Ty = getPointerOperand(I1)->getType();
161 const Type *I2Ty = getPointerOperand(I2)->getType();
163 // Exactly the same type, must have exactly the same size.
164 if (I1Ty == I2Ty) return true;
166 int I1Size = getStoreSize(I1, TD);
167 int I2Size = getStoreSize(I2, TD);
169 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
172 bool DSE::runOnBasicBlock(BasicBlock &BB) {
173 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
174 TD = getAnalysisIfAvailable<TargetData>();
176 bool MadeChange = false;
178 // Do a top-down walk on the BB.
179 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
180 Instruction *Inst = BBI++;
182 // If we find a store or a free, get its memory dependence.
183 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
186 MemDepResult InstDep = MD.getDependency(Inst);
188 // Ignore non-local stores.
189 // FIXME: cross-block DSE would be fun. :)
190 if (InstDep.isNonLocal()) continue;
192 // Handle frees whose dependencies are non-trivial.
193 if (isFreeCall(Inst)) {
194 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
198 // If not a definite must-alias dependency, ignore it.
199 if (!InstDep.isDef())
202 // If this is a store-store dependence, then the previous store is dead so
203 // long as this store is at least as big as it.
204 if (doesClobberMemory(InstDep.getInst())) {
205 Instruction *DepStore = InstDep.getInst();
206 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
207 isElidable(DepStore)) {
208 // Delete the store and now-dead instructions that feed it.
209 DeleteDeadInstruction(DepStore);
213 // DeleteDeadInstruction can delete the current instruction in loop
216 if (BBI != BB.begin())
222 if (!isElidable(Inst))
225 // If we're storing the same value back to a pointer that we just
226 // loaded from, then the store can be removed.
227 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
228 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
229 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
230 SI->getOperand(0) == DepLoad) {
231 // DeleteDeadInstruction can delete the current instruction. Save BBI
232 // in case we need it.
233 WeakVH NextInst(BBI);
235 DeleteDeadInstruction(SI);
237 if (NextInst == 0) // Next instruction deleted.
239 else if (BBI != BB.begin()) // Revisit this instruction if possible.
248 // If this is a lifetime end marker, we can throw away the store.
249 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
250 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
251 // Delete the store and now-dead instructions that feed it.
252 // DeleteDeadInstruction can delete the current instruction. Save BBI
253 // in case we need it.
254 WeakVH NextInst(BBI);
256 DeleteDeadInstruction(Inst);
258 if (NextInst == 0) // Next instruction deleted.
260 else if (BBI != BB.begin()) // Revisit this instruction if possible.
269 // If this block ends in a return, unwind, or unreachable, all allocas are
270 // dead at its end, which means stores to them are also dead.
271 if (BB.getTerminator()->getNumSuccessors() == 0)
272 MadeChange |= handleEndBlock(BB);
277 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
278 /// dependency is a store to a field of that structure.
279 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
280 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
282 Instruction *Dependency = Dep.getInst();
283 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
286 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
288 // Check for aliasing.
289 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
290 AliasAnalysis::MustAlias)
293 // DCE instructions only used to calculate that store
294 DeleteDeadInstruction(Dependency);
299 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
300 /// function end block. Ex:
303 /// store i32 1, i32* %A
305 bool DSE::handleEndBlock(BasicBlock &BB) {
306 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
308 bool MadeChange = false;
310 // Pointers alloca'd in this function are dead in the end block
311 SmallPtrSet<Value*, 64> deadPointers;
313 // Find all of the alloca'd pointers in the entry block.
314 BasicBlock *Entry = BB.getParent()->begin();
315 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
316 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
317 deadPointers.insert(AI);
319 // Treat byval arguments the same, stores to them are dead at the end of the
321 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
322 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
323 if (AI->hasByValAttr())
324 deadPointers.insert(AI);
326 // Scan the basic block backwards
327 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
330 // If we find a store whose pointer is dead.
331 if (doesClobberMemory(BBI)) {
332 if (isElidable(BBI)) {
333 // See through pointer-to-pointer bitcasts
334 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
336 // Alloca'd pointers or byval arguments (which are functionally like
337 // alloca's) are valid candidates for removal.
338 if (deadPointers.count(pointerOperand)) {
339 // DCE instructions only used to calculate that store.
340 Instruction *Dead = BBI;
342 DeleteDeadInstruction(Dead, &deadPointers);
349 // Because a memcpy or memmove is also a load, we can't skip it if we
351 if (!isa<MemTransferInst>(BBI))
355 Value* killPointer = 0;
356 uint64_t killPointerSize = ~0UL;
358 // If we encounter a use of the pointer, it is no longer considered dead
359 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
360 // However, if this load is unused and not volatile, we can go ahead and
361 // remove it, and not have to worry about it making our pointer undead!
362 if (L->use_empty() && !L->isVolatile()) {
364 DeleteDeadInstruction(L, &deadPointers);
370 killPointer = L->getPointerOperand();
371 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
372 killPointer = V->getOperand(0);
373 } else if (isa<MemTransferInst>(BBI) &&
374 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
375 killPointer = cast<MemTransferInst>(BBI)->getSource();
376 killPointerSize = cast<ConstantInt>(
377 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
378 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
379 deadPointers.erase(A);
381 // Dead alloca's can be DCE'd when we reach them
382 if (A->use_empty()) {
384 DeleteDeadInstruction(A, &deadPointers);
390 } else if (CallSite::get(BBI).getInstruction() != 0) {
391 // If this call does not access memory, it can't
392 // be undeadifying any of our pointers.
393 CallSite CS = CallSite::get(BBI);
394 if (AA.doesNotAccessMemory(CS))
400 // Remove any pointers made undead by the call from the dead set
401 std::vector<Value*> dead;
402 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
403 E = deadPointers.end(); I != E; ++I) {
404 // HACK: if we detect that our AA is imprecise, it's not
405 // worth it to scan the rest of the deadPointers set. Just
406 // assume that the AA will return ModRef for everything, and
407 // go ahead and bail.
408 if (modRef >= 16 && other == 0) {
409 deadPointers.clear();
413 // Get size information for the alloca
414 unsigned pointerSize = ~0U;
416 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
417 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
418 pointerSize = C->getZExtValue() *
419 TD->getTypeAllocSize(A->getAllocatedType());
421 const PointerType* PT = cast<PointerType>(
422 cast<Argument>(*I)->getType());
423 pointerSize = TD->getTypeAllocSize(PT->getElementType());
427 // See if the call site touches it
428 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
430 if (A == AliasAnalysis::ModRef)
435 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
439 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
441 deadPointers.erase(*I);
444 } else if (isInstructionTriviallyDead(BBI)) {
445 // For any non-memory-affecting non-terminators, DCE them as we reach them
446 Instruction *Inst = BBI;
448 DeleteDeadInstruction(Inst, &deadPointers);
457 killPointer = killPointer->getUnderlyingObject();
459 // Deal with undead pointers
460 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
467 /// RemoveUndeadPointers - check for uses of a pointer that make it
468 /// undead when scanning for dead stores to alloca's.
469 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
470 BasicBlock::iterator &BBI,
471 SmallPtrSet<Value*, 64>& deadPointers) {
472 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
474 // If the kill pointer can be easily reduced to an alloca,
475 // don't bother doing extraneous AA queries.
476 if (deadPointers.count(killPointer)) {
477 deadPointers.erase(killPointer);
481 // A global can't be in the dead pointer set.
482 if (isa<GlobalValue>(killPointer))
485 bool MadeChange = false;
487 SmallVector<Value*, 16> undead;
489 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
490 E = deadPointers.end(); I != E; ++I) {
491 // Get size information for the alloca.
492 unsigned pointerSize = ~0U;
494 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
495 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
496 pointerSize = C->getZExtValue() *
497 TD->getTypeAllocSize(A->getAllocatedType());
499 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
500 pointerSize = TD->getTypeAllocSize(PT->getElementType());
504 // See if this pointer could alias it
505 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
506 killPointer, killPointerSize);
508 // If it must-alias and a store, we can delete it
509 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
510 StoreInst* S = cast<StoreInst>(BBI);
514 DeleteDeadInstruction(S, &deadPointers);
520 // Otherwise, it is undead
521 } else if (A != AliasAnalysis::NoAlias)
522 undead.push_back(*I);
525 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
527 deadPointers.erase(*I);
532 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
533 /// and zero out all the operands of this instruction. If any of them become
534 /// dead, delete them and the computation tree that feeds them.
536 /// If ValueSet is non-null, remove any deleted instructions from it as well.
538 void DSE::DeleteDeadInstruction(Instruction *I,
539 SmallPtrSet<Value*, 64> *ValueSet) {
540 SmallVector<Instruction*, 32> NowDeadInsts;
542 NowDeadInsts.push_back(I);
545 // Before we touch this instruction, remove it from memdep!
546 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
547 while (!NowDeadInsts.empty()) {
548 Instruction *DeadInst = NowDeadInsts.back();
549 NowDeadInsts.pop_back();
553 // This instruction is dead, zap it, in stages. Start by removing it from
554 // MemDep, which needs to know the operands and needs it to be in the
556 MDA.removeInstruction(DeadInst);
558 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
559 Value *Op = DeadInst->getOperand(op);
560 DeadInst->setOperand(op, 0);
562 // If this operand just became dead, add it to the NowDeadInsts list.
563 if (!Op->use_empty()) continue;
565 if (Instruction *OpI = dyn_cast<Instruction>(Op))
566 if (isInstructionTriviallyDead(OpI))
567 NowDeadInsts.push_back(OpI);
570 DeadInst->eraseFromParent();
572 if (ValueSet) ValueSet->erase(DeadInst);