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::lifetime_end: return true;
96 /// isElidable - If the memory 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 assert(cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::lifetime_end);
115 return cast<IntrinsicInst>(I)->getOperand(2);
118 /// getStoreSize - Return the length in bytes of the write by the clobbering
119 /// instruction. If variable or unknown, returns -1.
120 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
121 assert(doesClobberMemory(I));
122 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
124 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
128 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
129 Len = MI->getLength();
131 IntrinsicInst *II = cast<IntrinsicInst>(I);
132 assert(II->getIntrinsicID() == Intrinsic::lifetime_end);
133 Len = II->getOperand(0);
135 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
136 if (!LenCI->isAllOnesValue())
137 return LenCI->getZExtValue();
141 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
142 /// greater than or equal to the store in I2. This returns false if we don't
145 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
146 const TargetData *TD) {
147 const Type *I1Ty = getPointerOperand(I1)->getType();
148 const Type *I2Ty = getPointerOperand(I2)->getType();
150 // Exactly the same type, must have exactly the same size.
151 if (I1Ty == I2Ty) return true;
153 int I1Size = getStoreSize(I1, TD);
154 int I2Size = getStoreSize(I2, TD);
156 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
159 bool DSE::runOnBasicBlock(BasicBlock &BB) {
160 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
161 TD = getAnalysisIfAvailable<TargetData>();
163 bool MadeChange = false;
165 // Do a top-down walk on the BB.
166 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
167 Instruction *Inst = BBI++;
169 // If we find a store or a free, get its memory dependence.
170 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
173 MemDepResult InstDep = MD.getDependency(Inst);
175 // Ignore non-local stores.
176 // FIXME: cross-block DSE would be fun. :)
177 if (InstDep.isNonLocal()) continue;
179 // Handle frees whose dependencies are non-trivial.
180 if (isFreeCall(Inst)) {
181 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
185 // If not a definite must-alias dependency, ignore it.
186 if (!InstDep.isDef())
189 // If this is a store-store dependence, then the previous store is dead so
190 // long as this store is at least as big as it.
191 if (doesClobberMemory(InstDep.getInst())) {
192 Instruction *DepStore = InstDep.getInst();
193 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
194 isElidable(DepStore)) {
195 // Delete the store and now-dead instructions that feed it.
196 DeleteDeadInstruction(DepStore);
200 // DeleteDeadInstruction can delete the current instruction in loop
203 if (BBI != BB.begin())
209 if (!isElidable(Inst))
212 // If we're storing the same value back to a pointer that we just
213 // loaded from, then the store can be removed.
214 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
215 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
216 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
217 SI->getOperand(0) == DepLoad) {
218 // DeleteDeadInstruction can delete the current instruction. Save BBI
219 // in case we need it.
220 WeakVH NextInst(BBI);
222 DeleteDeadInstruction(SI);
224 if (NextInst == 0) // Next instruction deleted.
226 else if (BBI != BB.begin()) // Revisit this instruction if possible.
235 // If this is a lifetime end marker, we can throw away the store.
236 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
237 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
238 // Delete the store and now-dead instructions that feed it.
239 // DeleteDeadInstruction can delete the current instruction. Save BBI
240 // in case we need it.
241 WeakVH NextInst(BBI);
243 DeleteDeadInstruction(Inst);
245 if (NextInst == 0) // Next instruction deleted.
247 else if (BBI != BB.begin()) // Revisit this instruction if possible.
256 // If this block ends in a return, unwind, or unreachable, all allocas are
257 // dead at its end, which means stores to them are also dead.
258 if (BB.getTerminator()->getNumSuccessors() == 0)
259 MadeChange |= handleEndBlock(BB);
264 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
265 /// dependency is a store to a field of that structure.
266 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
267 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
269 Instruction *Dependency = Dep.getInst();
270 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
273 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
275 // Check for aliasing.
276 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
277 AliasAnalysis::MustAlias)
280 // DCE instructions only used to calculate that store
281 DeleteDeadInstruction(Dependency);
286 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
287 /// function end block. Ex:
290 /// store i32 1, i32* %A
292 bool DSE::handleEndBlock(BasicBlock &BB) {
293 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
295 bool MadeChange = false;
297 // Pointers alloca'd in this function are dead in the end block
298 SmallPtrSet<Value*, 64> deadPointers;
300 // Find all of the alloca'd pointers in the entry block.
301 BasicBlock *Entry = BB.getParent()->begin();
302 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
303 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
304 deadPointers.insert(AI);
306 // Treat byval arguments the same, stores to them are dead at the end of the
308 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
309 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
310 if (AI->hasByValAttr())
311 deadPointers.insert(AI);
313 // Scan the basic block backwards
314 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
317 // If we find a store whose pointer is dead.
318 if (doesClobberMemory(BBI)) {
319 if (isElidable(BBI)) {
320 // See through pointer-to-pointer bitcasts
321 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
323 // Alloca'd pointers or byval arguments (which are functionally like
324 // alloca's) are valid candidates for removal.
325 if (deadPointers.count(pointerOperand)) {
326 // DCE instructions only used to calculate that store.
327 Instruction *Dead = BBI;
329 DeleteDeadInstruction(Dead, &deadPointers);
336 // Because a memcpy or memmove is also a load, we can't skip it if we
338 if (!isa<MemTransferInst>(BBI))
342 Value* killPointer = 0;
343 uint64_t killPointerSize = ~0UL;
345 // If we encounter a use of the pointer, it is no longer considered dead
346 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
347 // However, if this load is unused and not volatile, we can go ahead and
348 // remove it, and not have to worry about it making our pointer undead!
349 if (L->use_empty() && !L->isVolatile()) {
351 DeleteDeadInstruction(L, &deadPointers);
357 killPointer = L->getPointerOperand();
358 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
359 killPointer = V->getOperand(0);
360 } else if (isa<MemTransferInst>(BBI) &&
361 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
362 killPointer = cast<MemTransferInst>(BBI)->getSource();
363 killPointerSize = cast<ConstantInt>(
364 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
365 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
366 deadPointers.erase(A);
368 // Dead alloca's can be DCE'd when we reach them
369 if (A->use_empty()) {
371 DeleteDeadInstruction(A, &deadPointers);
377 } else if (CallSite::get(BBI).getInstruction() != 0) {
378 // If this call does not access memory, it can't
379 // be undeadifying any of our pointers.
380 CallSite CS = CallSite::get(BBI);
381 if (AA.doesNotAccessMemory(CS))
387 // Remove any pointers made undead by the call from the dead set
388 std::vector<Value*> dead;
389 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
390 E = deadPointers.end(); I != E; ++I) {
391 // HACK: if we detect that our AA is imprecise, it's not
392 // worth it to scan the rest of the deadPointers set. Just
393 // assume that the AA will return ModRef for everything, and
394 // go ahead and bail.
395 if (modRef >= 16 && other == 0) {
396 deadPointers.clear();
400 // Get size information for the alloca
401 unsigned pointerSize = ~0U;
403 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
404 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
405 pointerSize = C->getZExtValue() *
406 TD->getTypeAllocSize(A->getAllocatedType());
408 const PointerType* PT = cast<PointerType>(
409 cast<Argument>(*I)->getType());
410 pointerSize = TD->getTypeAllocSize(PT->getElementType());
414 // See if the call site touches it
415 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
417 if (A == AliasAnalysis::ModRef)
422 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
426 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
428 deadPointers.erase(*I);
431 } else if (isInstructionTriviallyDead(BBI)) {
432 // For any non-memory-affecting non-terminators, DCE them as we reach them
433 Instruction *Inst = BBI;
435 DeleteDeadInstruction(Inst, &deadPointers);
444 killPointer = killPointer->getUnderlyingObject();
446 // Deal with undead pointers
447 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
454 /// RemoveUndeadPointers - check for uses of a pointer that make it
455 /// undead when scanning for dead stores to alloca's.
456 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
457 BasicBlock::iterator &BBI,
458 SmallPtrSet<Value*, 64>& deadPointers) {
459 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
461 // If the kill pointer can be easily reduced to an alloca,
462 // don't bother doing extraneous AA queries.
463 if (deadPointers.count(killPointer)) {
464 deadPointers.erase(killPointer);
468 // A global can't be in the dead pointer set.
469 if (isa<GlobalValue>(killPointer))
472 bool MadeChange = false;
474 SmallVector<Value*, 16> undead;
476 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
477 E = deadPointers.end(); I != E; ++I) {
478 // Get size information for the alloca.
479 unsigned pointerSize = ~0U;
481 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
482 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
483 pointerSize = C->getZExtValue() *
484 TD->getTypeAllocSize(A->getAllocatedType());
486 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
487 pointerSize = TD->getTypeAllocSize(PT->getElementType());
491 // See if this pointer could alias it
492 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
493 killPointer, killPointerSize);
495 // If it must-alias and a store, we can delete it
496 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
497 StoreInst* S = cast<StoreInst>(BBI);
501 DeleteDeadInstruction(S, &deadPointers);
507 // Otherwise, it is undead
508 } else if (A != AliasAnalysis::NoAlias)
509 undead.push_back(*I);
512 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
514 deadPointers.erase(*I);
519 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
520 /// and zero out all the operands of this instruction. If any of them become
521 /// dead, delete them and the computation tree that feeds them.
523 /// If ValueSet is non-null, remove any deleted instructions from it as well.
525 void DSE::DeleteDeadInstruction(Instruction *I,
526 SmallPtrSet<Value*, 64> *ValueSet) {
527 SmallVector<Instruction*, 32> NowDeadInsts;
529 NowDeadInsts.push_back(I);
532 // Before we touch this instruction, remove it from memdep!
533 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
534 while (!NowDeadInsts.empty()) {
535 Instruction *DeadInst = NowDeadInsts.back();
536 NowDeadInsts.pop_back();
540 // This instruction is dead, zap it, in stages. Start by removing it from
541 // MemDep, which needs to know the operands and needs it to be in the
543 MDA.removeInstruction(DeadInst);
545 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
546 Value *Op = DeadInst->getOperand(op);
547 DeadInst->setOperand(op, 0);
549 // If this operand just became dead, add it to the NowDeadInsts list.
550 if (!Op->use_empty()) continue;
552 if (Instruction *OpI = dyn_cast<Instruction>(Op))
553 if (isInstructionTriviallyDead(OpI))
554 NowDeadInsts.push_back(OpI);
557 DeadInst->eraseFromParent();
559 if (ValueSet) ValueSet->erase(DeadInst);