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 bool DSE::runOnBasicBlock(BasicBlock &BB) {
82 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
83 TD = getAnalysisIfAvailable<TargetData>();
85 bool MadeChange = false;
87 // Do a top-down walk on the BB.
88 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
89 Instruction *Inst = BBI++;
91 // If we find a store or a free, get its memory dependence.
92 if (!isa<StoreInst>(Inst) && !isFreeCall(Inst))
95 // Don't molest volatile stores or do queries that will return "clobber".
96 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
100 MemDepResult InstDep = MD.getDependency(Inst);
102 // Ignore non-local stores.
103 // FIXME: cross-block DSE would be fun. :)
104 if (InstDep.isNonLocal()) continue;
106 // Handle frees whose dependencies are non-trivial.
107 if (isFreeCall(Inst)) {
108 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
112 StoreInst *SI = cast<StoreInst>(Inst);
114 // If not a definite must-alias dependency, ignore it.
115 if (!InstDep.isDef())
118 // If this is a store-store dependence, then the previous store is dead so
119 // long as this store is at least as big as it.
120 if (StoreInst *DepStore = dyn_cast<StoreInst>(InstDep.getInst()))
122 TD->getTypeStoreSize(DepStore->getOperand(0)->getType()) <=
123 TD->getTypeStoreSize(SI->getOperand(0)->getType())) {
124 // Delete the store and now-dead instructions that feed it.
125 DeleteDeadInstruction(DepStore);
129 // DeleteDeadInstruction can delete the current instruction in loop
132 if (BBI != BB.begin())
137 // If we're storing the same value back to a pointer that we just
138 // loaded from, then the store can be removed.
139 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
140 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
141 SI->getOperand(0) == DepLoad) {
142 // DeleteDeadInstruction can delete the current instruction. Save BBI
143 // in case we need it.
144 WeakVH NextInst(BBI);
146 DeleteDeadInstruction(SI);
148 if (NextInst == 0) // Next instruction deleted.
150 else if (BBI != BB.begin()) // Revisit this instruction if possible.
159 // If this block ends in a return, unwind, or unreachable, all allocas are
160 // dead at its end, which means stores to them are also dead.
161 if (BB.getTerminator()->getNumSuccessors() == 0)
162 MadeChange |= handleEndBlock(BB);
167 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
168 /// dependency is a store to a field of that structure.
169 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
170 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
172 StoreInst *Dependency = dyn_cast_or_null<StoreInst>(Dep.getInst());
173 if (!Dependency || Dependency->isVolatile())
176 Value *DepPointer = Dependency->getPointerOperand()->getUnderlyingObject();
178 // Check for aliasing.
179 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
180 AliasAnalysis::MustAlias)
183 // DCE instructions only used to calculate that store
184 DeleteDeadInstruction(Dependency);
189 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
190 /// function end block. Ex:
193 /// store i32 1, i32* %A
195 bool DSE::handleEndBlock(BasicBlock &BB) {
196 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
198 bool MadeChange = false;
200 // Pointers alloca'd in this function are dead in the end block
201 SmallPtrSet<Value*, 64> deadPointers;
203 // Find all of the alloca'd pointers in the entry block.
204 BasicBlock *Entry = BB.getParent()->begin();
205 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
206 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
207 deadPointers.insert(AI);
209 // Treat byval arguments the same, stores to them are dead at the end of the
211 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
212 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
213 if (AI->hasByValAttr())
214 deadPointers.insert(AI);
216 // Scan the basic block backwards
217 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
220 // If we find a store whose pointer is dead.
221 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
222 if (!S->isVolatile()) {
223 // See through pointer-to-pointer bitcasts
224 Value* pointerOperand = S->getPointerOperand()->getUnderlyingObject();
226 // Alloca'd pointers or byval arguments (which are functionally like
227 // alloca's) are valid candidates for removal.
228 if (deadPointers.count(pointerOperand)) {
229 // DCE instructions only used to calculate that store.
231 DeleteDeadInstruction(S, &deadPointers);
240 // We can also remove memcpy's to local variables at the end of a function.
241 if (MemCpyInst *M = dyn_cast<MemCpyInst>(BBI)) {
242 Value *dest = M->getDest()->getUnderlyingObject();
244 if (deadPointers.count(dest)) {
246 DeleteDeadInstruction(M, &deadPointers);
252 // Because a memcpy is also a load, we can't skip it if we didn't remove
256 Value* killPointer = 0;
257 uint64_t killPointerSize = ~0UL;
259 // If we encounter a use of the pointer, it is no longer considered dead
260 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
261 // However, if this load is unused and not volatile, we can go ahead and
262 // remove it, and not have to worry about it making our pointer undead!
263 if (L->use_empty() && !L->isVolatile()) {
265 DeleteDeadInstruction(L, &deadPointers);
271 killPointer = L->getPointerOperand();
272 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
273 killPointer = V->getOperand(0);
274 } else if (isa<MemCpyInst>(BBI) &&
275 isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) {
276 killPointer = cast<MemCpyInst>(BBI)->getSource();
277 killPointerSize = cast<ConstantInt>(
278 cast<MemCpyInst>(BBI)->getLength())->getZExtValue();
279 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
280 deadPointers.erase(A);
282 // Dead alloca's can be DCE'd when we reach them
283 if (A->use_empty()) {
285 DeleteDeadInstruction(A, &deadPointers);
291 } else if (CallSite::get(BBI).getInstruction() != 0) {
292 // If this call does not access memory, it can't
293 // be undeadifying any of our pointers.
294 CallSite CS = CallSite::get(BBI);
295 if (AA.doesNotAccessMemory(CS))
301 // Remove any pointers made undead by the call from the dead set
302 std::vector<Value*> dead;
303 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
304 E = deadPointers.end(); I != E; ++I) {
305 // HACK: if we detect that our AA is imprecise, it's not
306 // worth it to scan the rest of the deadPointers set. Just
307 // assume that the AA will return ModRef for everything, and
308 // go ahead and bail.
309 if (modRef >= 16 && other == 0) {
310 deadPointers.clear();
314 // Get size information for the alloca
315 unsigned pointerSize = ~0U;
317 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
318 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
319 pointerSize = C->getZExtValue() *
320 TD->getTypeAllocSize(A->getAllocatedType());
322 const PointerType* PT = cast<PointerType>(
323 cast<Argument>(*I)->getType());
324 pointerSize = TD->getTypeAllocSize(PT->getElementType());
328 // See if the call site touches it
329 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
331 if (A == AliasAnalysis::ModRef)
336 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
340 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
342 deadPointers.erase(*I);
345 } else if (isInstructionTriviallyDead(BBI)) {
346 // For any non-memory-affecting non-terminators, DCE them as we reach them
347 Instruction *Inst = BBI;
349 DeleteDeadInstruction(Inst, &deadPointers);
358 killPointer = killPointer->getUnderlyingObject();
360 // Deal with undead pointers
361 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
368 /// RemoveUndeadPointers - check for uses of a pointer that make it
369 /// undead when scanning for dead stores to alloca's.
370 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
371 BasicBlock::iterator &BBI,
372 SmallPtrSet<Value*, 64>& deadPointers) {
373 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
375 // If the kill pointer can be easily reduced to an alloca,
376 // don't bother doing extraneous AA queries.
377 if (deadPointers.count(killPointer)) {
378 deadPointers.erase(killPointer);
382 // A global can't be in the dead pointer set.
383 if (isa<GlobalValue>(killPointer))
386 bool MadeChange = false;
388 SmallVector<Value*, 16> undead;
390 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
391 E = deadPointers.end(); I != E; ++I) {
392 // Get size information for the alloca.
393 unsigned pointerSize = ~0U;
395 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
396 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
397 pointerSize = C->getZExtValue() *
398 TD->getTypeAllocSize(A->getAllocatedType());
400 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
401 pointerSize = TD->getTypeAllocSize(PT->getElementType());
405 // See if this pointer could alias it
406 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
407 killPointer, killPointerSize);
409 // If it must-alias and a store, we can delete it
410 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
411 StoreInst* S = cast<StoreInst>(BBI);
415 DeleteDeadInstruction(S, &deadPointers);
421 // Otherwise, it is undead
422 } else if (A != AliasAnalysis::NoAlias)
423 undead.push_back(*I);
426 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
428 deadPointers.erase(*I);
433 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
434 /// and zero out all the operands of this instruction. If any of them become
435 /// dead, delete them and the computation tree that feeds them.
437 /// If ValueSet is non-null, remove any deleted instructions from it as well.
439 void DSE::DeleteDeadInstruction(Instruction *I,
440 SmallPtrSet<Value*, 64> *ValueSet) {
441 SmallVector<Instruction*, 32> NowDeadInsts;
443 NowDeadInsts.push_back(I);
446 // Before we touch this instruction, remove it from memdep!
447 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
448 while (!NowDeadInsts.empty()) {
449 Instruction *DeadInst = NowDeadInsts.back();
450 NowDeadInsts.pop_back();
454 // This instruction is dead, zap it, in stages. Start by removing it from
455 // MemDep, which needs to know the operands and needs it to be in the
457 MDA.removeInstruction(DeadInst);
459 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
460 Value *Op = DeadInst->getOperand(op);
461 DeadInst->setOperand(op, 0);
463 // If this operand just became dead, add it to the NowDeadInsts list.
464 if (!Op->use_empty()) continue;
466 if (Instruction *OpI = dyn_cast<Instruction>(Op))
467 if (isInstructionTriviallyDead(OpI))
468 NowDeadInsts.push_back(OpI);
471 DeadInst->eraseFromParent();
473 if (ValueSet) ValueSet->erase(DeadInst);