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 = 0) {
121 assert(doesClobberMemory(I));
122 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
124 const PointerType *PTy =
125 cast<PointerType>(SI->getPointerOperand()->getType());
126 return TD->getTypeStoreSize(PTy);
130 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
131 Len = MI->getLength();
133 assert(cast<IntrinsicInst>(I)->getIntrinsicID() ==
134 Intrinsic::lifetime_end);
135 Len = cast<IntrinsicInst>(I)->getOperand(0);
137 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
138 if (!LenCI->isAllOnesValue())
139 return LenCI->getZExtValue();
143 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
144 /// greater than or equal to the store in I2. This returns false if we don't
147 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
148 const TargetData *TD) {
149 const Type *I1Ty = getPointerOperand(I1)->getType();
150 const Type *I2Ty = getPointerOperand(I2)->getType();
152 // Exactly the same type, must have exactly the same size.
153 if (I1Ty == I2Ty) return true;
155 int I1Size = getStoreSize(I1, TD);
156 int I2Size = getStoreSize(I2, TD);
158 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
161 bool DSE::runOnBasicBlock(BasicBlock &BB) {
162 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
163 TD = getAnalysisIfAvailable<TargetData>();
165 bool MadeChange = false;
167 // Do a top-down walk on the BB.
168 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
169 Instruction *Inst = BBI++;
171 // If we find a store or a free, get its memory dependence.
172 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
175 MemDepResult InstDep = MD.getDependency(Inst);
177 // Ignore non-local stores.
178 // FIXME: cross-block DSE would be fun. :)
179 if (InstDep.isNonLocal()) continue;
181 // Handle frees whose dependencies are non-trivial.
182 if (isFreeCall(Inst)) {
183 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
187 // If not a definite must-alias dependency, ignore it.
188 if (!InstDep.isDef())
191 // If this is a store-store dependence, then the previous store is dead so
192 // long as this store is at least as big as it.
193 if (doesClobberMemory(InstDep.getInst())) {
194 Instruction *DepStore = InstDep.getInst();
195 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
196 isElidable(DepStore)){
197 // Delete the store and now-dead instructions that feed it.
198 DeleteDeadInstruction(DepStore);
202 // DeleteDeadInstruction can delete the current instruction in loop
205 if (BBI != BB.begin())
211 if (!isElidable(Inst))
214 // If we're storing the same value back to a pointer that we just
215 // loaded from, then the store can be removed.
216 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
217 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
218 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
219 SI->getOperand(0) == DepLoad) {
220 // DeleteDeadInstruction can delete the current instruction. Save BBI
221 // in case we need it.
222 WeakVH NextInst(BBI);
224 DeleteDeadInstruction(SI);
226 if (NextInst == 0) // Next instruction deleted.
228 else if (BBI != BB.begin()) // Revisit this instruction if possible.
237 // If this is a lifetime end marker, we can throw away the store.
238 if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
239 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
240 // Delete the store and now-dead instructions that feed it.
241 // DeleteDeadInstruction can delete the current instruction. Save BBI
242 // in case we need it.
243 WeakVH NextInst(BBI);
245 DeleteDeadInstruction(Inst);
247 if (NextInst == 0) // Next instruction deleted.
249 else if (BBI != BB.begin()) // Revisit this instruction if possible.
258 // If this block ends in a return, unwind, or unreachable, all allocas are
259 // dead at its end, which means stores to them are also dead.
260 if (BB.getTerminator()->getNumSuccessors() == 0)
261 MadeChange |= handleEndBlock(BB);
266 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
267 /// dependency is a store to a field of that structure.
268 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
269 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
271 Instruction *Dependency = Dep.getInst();
272 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
275 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
277 // Check for aliasing.
278 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
279 AliasAnalysis::MustAlias)
282 // DCE instructions only used to calculate that store
283 DeleteDeadInstruction(Dependency);
288 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
289 /// function end block. Ex:
292 /// store i32 1, i32* %A
294 bool DSE::handleEndBlock(BasicBlock &BB) {
295 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
297 bool MadeChange = false;
299 // Pointers alloca'd in this function are dead in the end block
300 SmallPtrSet<Value*, 64> deadPointers;
302 // Find all of the alloca'd pointers in the entry block.
303 BasicBlock *Entry = BB.getParent()->begin();
304 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
305 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
306 deadPointers.insert(AI);
308 // Treat byval arguments the same, stores to them are dead at the end of the
310 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
311 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
312 if (AI->hasByValAttr())
313 deadPointers.insert(AI);
315 // Scan the basic block backwards
316 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
319 // If we find a store whose pointer is dead.
320 if (doesClobberMemory(BBI)) {
321 if (isElidable(BBI)) {
322 // See through pointer-to-pointer bitcasts
323 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
325 // Alloca'd pointers or byval arguments (which are functionally like
326 // alloca's) are valid candidates for removal.
327 if (deadPointers.count(pointerOperand)) {
328 // DCE instructions only used to calculate that store.
329 Instruction *Dead = BBI;
331 DeleteDeadInstruction(Dead, &deadPointers);
338 // Because a memcpy or memmove is also a load, we can't skip it if we
340 if (!isa<MemTransferInst>(BBI))
344 Value* killPointer = 0;
345 uint64_t killPointerSize = ~0UL;
347 // If we encounter a use of the pointer, it is no longer considered dead
348 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
349 // However, if this load is unused and not volatile, we can go ahead and
350 // remove it, and not have to worry about it making our pointer undead!
351 if (L->use_empty() && !L->isVolatile()) {
353 DeleteDeadInstruction(L, &deadPointers);
359 killPointer = L->getPointerOperand();
360 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
361 killPointer = V->getOperand(0);
362 } else if (isa<MemTransferInst>(BBI) &&
363 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
364 killPointer = cast<MemTransferInst>(BBI)->getSource();
365 killPointerSize = cast<ConstantInt>(
366 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
367 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
368 deadPointers.erase(A);
370 // Dead alloca's can be DCE'd when we reach them
371 if (A->use_empty()) {
373 DeleteDeadInstruction(A, &deadPointers);
379 } else if (CallSite::get(BBI).getInstruction() != 0) {
380 // If this call does not access memory, it can't
381 // be undeadifying any of our pointers.
382 CallSite CS = CallSite::get(BBI);
383 if (AA.doesNotAccessMemory(CS))
389 // Remove any pointers made undead by the call from the dead set
390 std::vector<Value*> dead;
391 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
392 E = deadPointers.end(); I != E; ++I) {
393 // HACK: if we detect that our AA is imprecise, it's not
394 // worth it to scan the rest of the deadPointers set. Just
395 // assume that the AA will return ModRef for everything, and
396 // go ahead and bail.
397 if (modRef >= 16 && other == 0) {
398 deadPointers.clear();
402 // Get size information for the alloca
403 unsigned pointerSize = ~0U;
405 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
406 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
407 pointerSize = C->getZExtValue() *
408 TD->getTypeAllocSize(A->getAllocatedType());
410 const PointerType* PT = cast<PointerType>(
411 cast<Argument>(*I)->getType());
412 pointerSize = TD->getTypeAllocSize(PT->getElementType());
416 // See if the call site touches it
417 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
419 if (A == AliasAnalysis::ModRef)
424 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
428 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
430 deadPointers.erase(*I);
433 } else if (isInstructionTriviallyDead(BBI)) {
434 // For any non-memory-affecting non-terminators, DCE them as we reach them
435 Instruction *Inst = BBI;
437 DeleteDeadInstruction(Inst, &deadPointers);
446 killPointer = killPointer->getUnderlyingObject();
448 // Deal with undead pointers
449 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
456 /// RemoveUndeadPointers - check for uses of a pointer that make it
457 /// undead when scanning for dead stores to alloca's.
458 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
459 BasicBlock::iterator &BBI,
460 SmallPtrSet<Value*, 64>& deadPointers) {
461 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
463 // If the kill pointer can be easily reduced to an alloca,
464 // don't bother doing extraneous AA queries.
465 if (deadPointers.count(killPointer)) {
466 deadPointers.erase(killPointer);
470 // A global can't be in the dead pointer set.
471 if (isa<GlobalValue>(killPointer))
474 bool MadeChange = false;
476 SmallVector<Value*, 16> undead;
478 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
479 E = deadPointers.end(); I != E; ++I) {
480 // Get size information for the alloca.
481 unsigned pointerSize = ~0U;
483 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
484 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
485 pointerSize = C->getZExtValue() *
486 TD->getTypeAllocSize(A->getAllocatedType());
488 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
489 pointerSize = TD->getTypeAllocSize(PT->getElementType());
493 // See if this pointer could alias it
494 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
495 killPointer, killPointerSize);
497 // If it must-alias and a store, we can delete it
498 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
499 StoreInst* S = cast<StoreInst>(BBI);
503 DeleteDeadInstruction(S, &deadPointers);
509 // Otherwise, it is undead
510 } else if (A != AliasAnalysis::NoAlias)
511 undead.push_back(*I);
514 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
516 deadPointers.erase(*I);
521 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
522 /// and zero out all the operands of this instruction. If any of them become
523 /// dead, delete them and the computation tree that feeds them.
525 /// If ValueSet is non-null, remove any deleted instructions from it as well.
527 void DSE::DeleteDeadInstruction(Instruction *I,
528 SmallPtrSet<Value*, 64> *ValueSet) {
529 SmallVector<Instruction*, 32> NowDeadInsts;
531 NowDeadInsts.push_back(I);
534 // Before we touch this instruction, remove it from memdep!
535 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
536 while (!NowDeadInsts.empty()) {
537 Instruction *DeadInst = NowDeadInsts.back();
538 NowDeadInsts.pop_back();
542 // This instruction is dead, zap it, in stages. Start by removing it from
543 // MemDep, which needs to know the operands and needs it to be in the
545 MDA.removeInstruction(DeadInst);
547 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
548 Value *Op = DeadInst->getOperand(op);
549 DeadInst->setOperand(op, 0);
551 // If this operand just became dead, add it to the NowDeadInsts list.
552 if (!Op->use_empty()) continue;
554 if (Instruction *OpI = dyn_cast<Instruction>(Op))
555 if (isInstructionTriviallyDead(OpI))
556 NowDeadInsts.push_back(OpI);
559 DeadInst->eraseFromParent();
561 if (ValueSet) ValueSet->erase(DeadInst);