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) {
48 DominatorTree &DT = getAnalysis<DominatorTree>();
50 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
51 // Only check non-dead blocks. Dead blocks may have strange pointer
52 // cycles that will confuse alias analysis.
53 if (DT.isReachableFromEntry(I))
54 Changed |= runOnBasicBlock(*I);
58 bool runOnBasicBlock(BasicBlock &BB);
59 bool handleFreeWithNonTrivialDependency(const CallInst *F,
61 bool handleEndBlock(BasicBlock &BB);
62 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
63 BasicBlock::iterator &BBI,
64 SmallPtrSet<Value*, 64> &deadPointers);
65 void DeleteDeadInstruction(Instruction *I,
66 SmallPtrSet<Value*, 64> *deadPointers = 0);
69 // getAnalysisUsage - We require post dominance frontiers (aka Control
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<DominatorTree>();
74 AU.addRequired<AliasAnalysis>();
75 AU.addRequired<MemoryDependenceAnalysis>();
76 AU.addPreserved<DominatorTree>();
77 AU.addPreserved<MemoryDependenceAnalysis>();
80 unsigned getPointerSize(Value *V) const;
85 INITIALIZE_PASS(DSE, "dse", "Dead Store Elimination", false, false);
87 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
89 /// doesClobberMemory - Does this instruction clobber (write without reading)
91 static bool doesClobberMemory(Instruction *I) {
92 if (isa<StoreInst>(I))
94 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
95 switch (II->getIntrinsicID()) {
98 case Intrinsic::memset:
99 case Intrinsic::memmove:
100 case Intrinsic::memcpy:
101 case Intrinsic::init_trampoline:
102 case Intrinsic::lifetime_end:
109 /// isElidable - If the value of this instruction and the memory it writes to is
110 /// unused, may we delete this instrtction?
111 static bool isElidable(Instruction *I) {
112 assert(doesClobberMemory(I));
113 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
114 return II->getIntrinsicID() != Intrinsic::lifetime_end;
115 if (StoreInst *SI = dyn_cast<StoreInst>(I))
116 return !SI->isVolatile();
120 /// getPointerOperand - Return the pointer that is being clobbered.
121 static Value *getPointerOperand(Instruction *I) {
122 assert(doesClobberMemory(I));
123 if (StoreInst *SI = dyn_cast<StoreInst>(I))
124 return SI->getPointerOperand();
125 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
126 return MI->getArgOperand(0);
128 IntrinsicInst *II = cast<IntrinsicInst>(I);
129 switch (II->getIntrinsicID()) {
130 default: assert(false && "Unexpected intrinsic!");
131 case Intrinsic::init_trampoline:
132 return II->getArgOperand(0);
133 case Intrinsic::lifetime_end:
134 return II->getArgOperand(1);
138 /// getStoreSize - Return the length in bytes of the write by the clobbering
139 /// instruction. If variable or unknown, returns -1.
140 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
141 assert(doesClobberMemory(I));
142 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
144 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
148 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
149 Len = MI->getLength();
151 IntrinsicInst *II = cast<IntrinsicInst>(I);
152 switch (II->getIntrinsicID()) {
153 default: assert(false && "Unexpected intrinsic!");
154 case Intrinsic::init_trampoline:
156 case Intrinsic::lifetime_end:
157 Len = II->getArgOperand(0);
161 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
162 if (!LenCI->isAllOnesValue())
163 return LenCI->getZExtValue();
167 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
168 /// greater than or equal to the store in I2. This returns false if we don't
171 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
172 const TargetData *TD) {
173 const Type *I1Ty = getPointerOperand(I1)->getType();
174 const Type *I2Ty = getPointerOperand(I2)->getType();
176 // Exactly the same type, must have exactly the same size.
177 if (I1Ty == I2Ty) return true;
179 int I1Size = getStoreSize(I1, TD);
180 int I2Size = getStoreSize(I2, TD);
182 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
185 bool DSE::runOnBasicBlock(BasicBlock &BB) {
186 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
187 TD = getAnalysisIfAvailable<TargetData>();
189 bool MadeChange = false;
191 // Do a top-down walk on the BB.
192 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
193 Instruction *Inst = BBI++;
195 // If we find a store or a free, get its memory dependence.
196 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
199 MemDepResult InstDep = MD.getDependency(Inst);
201 // Ignore non-local stores.
202 // FIXME: cross-block DSE would be fun. :)
203 if (InstDep.isNonLocal()) continue;
205 // Handle frees whose dependencies are non-trivial.
206 if (const CallInst *F = isFreeCall(Inst)) {
207 MadeChange |= handleFreeWithNonTrivialDependency(F, InstDep);
211 // If not a definite must-alias dependency, ignore it.
212 if (!InstDep.isDef())
215 // If this is a store-store dependence, then the previous store is dead so
216 // long as this store is at least as big as it.
217 if (doesClobberMemory(InstDep.getInst())) {
218 Instruction *DepStore = InstDep.getInst();
219 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
220 isElidable(DepStore)) {
221 // Delete the store and now-dead instructions that feed it.
222 DeleteDeadInstruction(DepStore);
226 // DeleteDeadInstruction can delete the current instruction in loop
229 if (BBI != BB.begin())
235 if (!isElidable(Inst))
238 // If we're storing the same value back to a pointer that we just
239 // loaded from, then the store can be removed.
240 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
241 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
242 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
243 SI->getOperand(0) == DepLoad) {
244 // DeleteDeadInstruction can delete the current instruction. Save BBI
245 // in case we need it.
246 WeakVH NextInst(BBI);
248 DeleteDeadInstruction(SI);
250 if (NextInst == 0) // Next instruction deleted.
252 else if (BBI != BB.begin()) // Revisit this instruction if possible.
261 // If this is a lifetime end marker, we can throw away the store.
262 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
263 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
264 // Delete the store and now-dead instructions that feed it.
265 // DeleteDeadInstruction can delete the current instruction. Save BBI
266 // in case we need it.
267 WeakVH NextInst(BBI);
269 DeleteDeadInstruction(Inst);
271 if (NextInst == 0) // Next instruction deleted.
273 else if (BBI != BB.begin()) // Revisit this instruction if possible.
282 // If this block ends in a return, unwind, or unreachable, all allocas are
283 // dead at its end, which means stores to them are also dead.
284 if (BB.getTerminator()->getNumSuccessors() == 0)
285 MadeChange |= handleEndBlock(BB);
290 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
291 /// dependency is a store to a field of that structure.
292 bool DSE::handleFreeWithNonTrivialDependency(const CallInst *F,
294 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
296 Instruction *Dependency = Dep.getInst();
297 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
300 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
302 // Check for aliasing.
303 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
304 AliasAnalysis::MustAlias)
307 // DCE instructions only used to calculate that store
308 DeleteDeadInstruction(Dependency);
313 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
314 /// function end block. Ex:
317 /// store i32 1, i32* %A
319 bool DSE::handleEndBlock(BasicBlock &BB) {
320 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
322 bool MadeChange = false;
324 // Pointers alloca'd in this function are dead in the end block
325 SmallPtrSet<Value*, 64> deadPointers;
327 // Find all of the alloca'd pointers in the entry block.
328 BasicBlock *Entry = BB.getParent()->begin();
329 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
330 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
331 deadPointers.insert(AI);
333 // Treat byval arguments the same, stores to them are dead at the end of the
335 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
336 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
337 if (AI->hasByValAttr())
338 deadPointers.insert(AI);
340 // Scan the basic block backwards
341 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
344 // If we find a store whose pointer is dead.
345 if (doesClobberMemory(BBI)) {
346 if (isElidable(BBI)) {
347 // See through pointer-to-pointer bitcasts
348 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
350 // Alloca'd pointers or byval arguments (which are functionally like
351 // alloca's) are valid candidates for removal.
352 if (deadPointers.count(pointerOperand)) {
353 // DCE instructions only used to calculate that store.
354 Instruction *Dead = BBI;
356 DeleteDeadInstruction(Dead, &deadPointers);
363 // Because a memcpy or memmove is also a load, we can't skip it if we
365 if (!isa<MemTransferInst>(BBI))
369 Value *killPointer = 0;
370 uint64_t killPointerSize = ~0UL;
372 // If we encounter a use of the pointer, it is no longer considered dead
373 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
374 // However, if this load is unused and not volatile, we can go ahead and
375 // remove it, and not have to worry about it making our pointer undead!
376 if (L->use_empty() && !L->isVolatile()) {
378 DeleteDeadInstruction(L, &deadPointers);
384 killPointer = L->getPointerOperand();
385 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
386 killPointer = V->getOperand(0);
387 } else if (isa<MemTransferInst>(BBI) &&
388 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
389 killPointer = cast<MemTransferInst>(BBI)->getSource();
390 killPointerSize = cast<ConstantInt>(
391 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
392 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
393 deadPointers.erase(A);
395 // Dead alloca's can be DCE'd when we reach them
396 if (A->use_empty()) {
398 DeleteDeadInstruction(A, &deadPointers);
404 } else if (CallSite CS = cast<Value>(BBI)) {
405 // If this call does not access memory, it can't
406 // be undeadifying any of our pointers.
407 if (AA.doesNotAccessMemory(CS))
413 // Remove any pointers made undead by the call from the dead set
414 std::vector<Value*> dead;
415 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
416 E = deadPointers.end(); I != E; ++I) {
417 // HACK: if we detect that our AA is imprecise, it's not
418 // worth it to scan the rest of the deadPointers set. Just
419 // assume that the AA will return ModRef for everything, and
420 // go ahead and bail.
421 if (modRef >= 16 && other == 0) {
422 deadPointers.clear();
426 // See if the call site touches it
427 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
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 // See if this pointer could alias it
492 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
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>();
535 Instruction *DeadInst = NowDeadInsts.pop_back_val();
539 // This instruction is dead, zap it, in stages. Start by removing it from
540 // MemDep, which needs to know the operands and needs it to be in the
542 MDA.removeInstruction(DeadInst);
544 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
545 Value *Op = DeadInst->getOperand(op);
546 DeadInst->setOperand(op, 0);
548 // If this operand just became dead, add it to the NowDeadInsts list.
549 if (!Op->use_empty()) continue;
551 if (Instruction *OpI = dyn_cast<Instruction>(Op))
552 if (isInstructionTriviallyDead(OpI))
553 NowDeadInsts.push_back(OpI);
556 DeadInst->eraseFromParent();
558 if (ValueSet) ValueSet->erase(DeadInst);
559 } while (!NowDeadInsts.empty());
562 unsigned DSE::getPointerSize(Value *V) const {
564 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
565 // Get size information for the alloca
566 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
567 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
569 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
570 const PointerType *PT = cast<PointerType>(V->getType());
571 return TD->getTypeAllocSize(PT->getElementType());