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/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Support/Compiler.h"
36 STATISTIC(NumFastStores, "Number of stores deleted");
37 STATISTIC(NumFastOther , "Number of other instrs removed");
40 struct VISIBILITY_HIDDEN DSE : public FunctionPass {
41 static char ID; // Pass identification, replacement for typeid
42 DSE() : FunctionPass(&ID) {}
44 virtual bool runOnFunction(Function &F) {
46 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
47 Changed |= runOnBasicBlock(*I);
51 bool runOnBasicBlock(BasicBlock &BB);
52 bool handleFreeWithNonTrivialDependency(FreeInst* F,
53 Instruction* dependency,
54 SetVector<Instruction*>& possiblyDead);
55 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
56 bool RemoveUndeadPointers(Value* pointer, uint64_t killPointerSize,
57 BasicBlock::iterator& BBI,
58 SmallPtrSet<Value*, 64>& deadPointers,
59 SetVector<Instruction*>& possiblyDead);
60 void DeleteDeadInstructionChains(Instruction *I,
61 SetVector<Instruction*> &DeadInsts);
64 // getAnalysisUsage - We require post dominance frontiers (aka Control
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.addRequired<DominatorTree>();
69 AU.addRequired<TargetData>();
70 AU.addRequired<AliasAnalysis>();
71 AU.addRequired<MemoryDependenceAnalysis>();
72 AU.addPreserved<DominatorTree>();
73 AU.addPreserved<AliasAnalysis>();
74 AU.addPreserved<MemoryDependenceAnalysis>();
80 static RegisterPass<DSE> X("dse", "Dead Store Elimination");
82 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
84 bool DSE::runOnBasicBlock(BasicBlock &BB) {
85 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
86 TargetData &TD = getAnalysis<TargetData>();
88 // Record the last-seen store to this pointer
89 DenseMap<Value*, StoreInst*> lastStore;
90 // Record instructions possibly made dead by deleting a store
91 SetVector<Instruction*> possiblyDead;
93 bool MadeChange = false;
95 // Do a top-down walk on the BB
96 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
98 // If we find a store or a free...
99 if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
103 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
106 pointer = S->getPointerOperand();
108 pointer = cast<FreeInst>(BBI)->getPointerOperand();
111 pointer = pointer->stripPointerCasts();
112 StoreInst*& last = lastStore[pointer];
113 bool deletedStore = false;
115 // ... to a pointer that has been stored to before...
117 Instruction* dep = MD.getDependency(BBI);
119 // ... and no other memory dependencies are between them....
120 while (dep != MemoryDependenceAnalysis::None &&
121 dep != MemoryDependenceAnalysis::NonLocal &&
122 isa<StoreInst>(dep)) {
124 TD.getTypeStoreSize(last->getOperand(0)->getType()) >
125 TD.getTypeStoreSize(BBI->getOperand(0)->getType())) {
126 dep = MD.getDependency(BBI, dep);
131 MD.removeInstruction(last);
133 // DCE instructions only used to calculate that store
134 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
135 possiblyDead.insert(D);
136 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
137 possiblyDead.insert(D);
139 last->eraseFromParent();
148 // Handle frees whose dependencies are non-trivial.
149 if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
151 MadeChange |= handleFreeWithNonTrivialDependency(F,
154 // No known stores after the free
157 StoreInst* S = cast<StoreInst>(BBI);
159 // If we're storing the same value back to a pointer that we just
160 // loaded from, then the store can be removed;
161 if (LoadInst* L = dyn_cast<LoadInst>(S->getOperand(0))) {
162 Instruction* dep = MD.getDependency(S);
163 DominatorTree& DT = getAnalysis<DominatorTree>();
165 if (!S->isVolatile() && S->getParent() == L->getParent() &&
166 S->getPointerOperand() == L->getPointerOperand() &&
167 ( dep == MemoryDependenceAnalysis::None ||
168 dep == MemoryDependenceAnalysis::NonLocal ||
169 DT.dominates(dep, L))) {
170 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
171 possiblyDead.insert(D);
172 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
173 possiblyDead.insert(D);
175 // Avoid iterator invalidation.
178 MD.removeInstruction(S);
179 S->eraseFromParent();
183 // Update our most-recent-store map.
186 // Update our most-recent-store map.
191 // If this block ends in a return, unwind, unreachable, and eventually
192 // tailcall, then all allocas are dead at its end.
193 if (BB.getTerminator()->getNumSuccessors() == 0)
194 MadeChange |= handleEndBlock(BB, possiblyDead);
197 while (!possiblyDead.empty()) {
198 Instruction *I = possiblyDead.back();
199 possiblyDead.pop_back();
200 DeleteDeadInstructionChains(I, possiblyDead);
206 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
207 /// dependency is a store to a field of that structure
208 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
209 SetVector<Instruction*>& possiblyDead) {
210 TargetData &TD = getAnalysis<TargetData>();
211 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
212 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
214 if (dep == MemoryDependenceAnalysis::None ||
215 dep == MemoryDependenceAnalysis::NonLocal)
218 StoreInst* dependency = dyn_cast<StoreInst>(dep);
221 else if (dependency->isVolatile())
224 Value* depPointer = dependency->getPointerOperand();
225 const Type* depType = dependency->getOperand(0)->getType();
226 unsigned depPointerSize = TD.getTypeStoreSize(depType);
228 // Check for aliasing
229 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0U,
230 depPointer, depPointerSize);
232 if (A == AliasAnalysis::MustAlias) {
234 MD.removeInstruction(dependency);
236 // DCE instructions only used to calculate that store
237 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
238 possiblyDead.insert(D);
239 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
240 possiblyDead.insert(D);
242 dependency->eraseFromParent();
250 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
251 /// function end block. Ex:
254 /// store i32 1, i32* %A
256 bool DSE::handleEndBlock(BasicBlock& BB,
257 SetVector<Instruction*>& possiblyDead) {
258 TargetData &TD = getAnalysis<TargetData>();
259 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
260 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
262 bool MadeChange = false;
264 // Pointers alloca'd in this function are dead in the end block
265 SmallPtrSet<Value*, 64> deadPointers;
267 // Find all of the alloca'd pointers in the entry block
268 BasicBlock *Entry = BB.getParent()->begin();
269 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
270 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
271 deadPointers.insert(AI);
272 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
273 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
274 if (AI->hasByValAttr())
275 deadPointers.insert(AI);
277 // Scan the basic block backwards
278 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
281 // If we find a store whose pointer is dead...
282 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
283 if (!S->isVolatile()) {
284 // See through pointer-to-pointer bitcasts
285 Value* pointerOperand = S->getPointerOperand()->getUnderlyingObject();
287 // Alloca'd pointers or byval arguments (which are functionally like
288 // alloca's) are valid candidates for removal.
289 if (deadPointers.count(pointerOperand)) {
291 MD.removeInstruction(S);
293 // DCE instructions only used to calculate that store
294 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
295 possiblyDead.insert(D);
296 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
297 possiblyDead.insert(D);
300 MD.removeInstruction(S);
301 S->eraseFromParent();
309 // We can also remove memcpy's to local variables at the end of a function
310 } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(BBI)) {
311 Value* dest = M->getDest()->getUnderlyingObject();
313 if (deadPointers.count(dest)) {
314 MD.removeInstruction(M);
316 // DCE instructions only used to calculate that memcpy
317 if (Instruction* D = dyn_cast<Instruction>(M->getRawSource()))
318 possiblyDead.insert(D);
319 if (Instruction* D = dyn_cast<Instruction>(M->getLength()))
320 possiblyDead.insert(D);
321 if (Instruction* D = dyn_cast<Instruction>(M->getRawDest()))
322 possiblyDead.insert(D);
325 M->eraseFromParent();
332 // Because a memcpy is also a load, we can't skip it if we didn't remove it
335 Value* killPointer = 0;
336 uint64_t killPointerSize = ~0UL;
338 // If we encounter a use of the pointer, it is no longer considered dead
339 if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
340 // However, if this load is unused and not volatile, we can go ahead and
341 // remove it, and not have to worry about it making our pointer undead!
342 if (L->use_empty() && !L->isVolatile()) {
343 MD.removeInstruction(L);
345 // DCE instructions only used to calculate that load
346 if (Instruction* D = dyn_cast<Instruction>(L->getPointerOperand()))
347 possiblyDead.insert(D);
350 L->eraseFromParent();
353 possiblyDead.remove(L);
358 killPointer = L->getPointerOperand();
359 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
360 killPointer = V->getOperand(0);
361 } else if (isa<MemCpyInst>(BBI) &&
362 isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) {
363 killPointer = cast<MemCpyInst>(BBI)->getSource();
364 killPointerSize = cast<ConstantInt>(
365 cast<MemCpyInst>(BBI)->getLength())->getZExtValue();
366 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
367 deadPointers.erase(A);
369 // Dead alloca's can be DCE'd when we reach them
370 if (A->use_empty()) {
371 MD.removeInstruction(A);
373 // DCE instructions only used to calculate that load
374 if (Instruction* D = dyn_cast<Instruction>(A->getArraySize()))
375 possiblyDead.insert(D);
378 A->eraseFromParent();
381 possiblyDead.remove(A);
385 } else if (CallSite::get(BBI).getInstruction() != 0) {
386 // If this call does not access memory, it can't
387 // be undeadifying any of our pointers.
388 CallSite CS = CallSite::get(BBI);
389 if (AA.doesNotAccessMemory(CS))
395 // Remove any pointers made undead by the call from the dead set
396 std::vector<Value*> dead;
397 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
398 E = deadPointers.end(); I != E; ++I) {
399 // HACK: if we detect that our AA is imprecise, it's not
400 // worth it to scan the rest of the deadPointers set. Just
401 // assume that the AA will return ModRef for everything, and
402 // go ahead and bail.
403 if (modRef >= 16 && other == 0) {
404 deadPointers.clear();
408 // Get size information for the alloca
409 unsigned pointerSize = ~0U;
410 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
411 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
412 pointerSize = C->getZExtValue() * \
413 TD.getABITypeSize(A->getAllocatedType());
415 const PointerType* PT = cast<PointerType>(
416 cast<Argument>(*I)->getType());
417 pointerSize = TD.getABITypeSize(PT->getElementType());
420 // See if the call site touches it
421 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
423 if (A == AliasAnalysis::ModRef)
428 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
432 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
434 deadPointers.erase(*I);
438 // For any non-memory-affecting non-terminators, DCE them as we reach them
439 Instruction *CI = BBI;
440 if (!CI->isTerminator() && CI->use_empty() && !isa<FreeInst>(CI)) {
442 // DCE instructions only used to calculate that load
443 for (Instruction::op_iterator OI = CI->op_begin(), OE = CI->op_end();
445 if (Instruction* D = dyn_cast<Instruction>(OI))
446 possiblyDead.insert(D);
449 CI->eraseFromParent();
452 possiblyDead.remove(CI);
461 killPointer = killPointer->getUnderlyingObject();
463 // Deal with undead pointers
464 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
465 deadPointers, possiblyDead);
471 /// RemoveUndeadPointers - check for uses of a pointer that make it
472 /// undead when scanning for dead stores to alloca's.
473 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
474 BasicBlock::iterator& BBI,
475 SmallPtrSet<Value*, 64>& deadPointers,
476 SetVector<Instruction*>& possiblyDead) {
477 TargetData &TD = getAnalysis<TargetData>();
478 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
479 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
481 // If the kill pointer can be easily reduced to an alloca,
482 // don't bother doing extraneous AA queries
483 if (deadPointers.count(killPointer)) {
484 deadPointers.erase(killPointer);
486 } else if (isa<GlobalValue>(killPointer)) {
487 // A global can't be in the dead pointer set
491 bool MadeChange = false;
493 std::vector<Value*> undead;
495 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
496 E = deadPointers.end(); I != E; ++I) {
497 // Get size information for the alloca
498 unsigned pointerSize = ~0U;
499 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
500 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
501 pointerSize = C->getZExtValue() * \
502 TD.getABITypeSize(A->getAllocatedType());
504 const PointerType* PT = cast<PointerType>(
505 cast<Argument>(*I)->getType());
506 pointerSize = TD.getABITypeSize(PT->getElementType());
509 // See if this pointer could alias it
510 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
511 killPointer, killPointerSize);
513 // If it must-alias and a store, we can delete it
514 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
515 StoreInst* S = cast<StoreInst>(BBI);
518 MD.removeInstruction(S);
520 // DCE instructions only used to calculate that store
521 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
522 possiblyDead.insert(D);
523 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
524 possiblyDead.insert(D);
527 S->eraseFromParent();
533 // Otherwise, it is undead
534 } else if (A != AliasAnalysis::NoAlias)
535 undead.push_back(*I);
538 for (std::vector<Value*>::iterator I = undead.begin(), E = undead.end();
540 deadPointers.erase(*I);
545 /// DeleteDeadInstructionChains - takes an instruction and a setvector of
546 /// dead instructions. If I is dead, it is erased, and its operands are
547 /// checked for deadness. If they are dead, they are added to the dead
549 void DSE::DeleteDeadInstructionChains(Instruction *I,
550 SetVector<Instruction*> &DeadInsts) {
551 // Instruction must be dead.
552 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
554 // Let the memory dependence know
555 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
557 // See if this made any operands dead. We do it this way in case the
558 // instruction uses the same operand twice. We don't want to delete a
559 // value then reference it.
560 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
561 if (I->getOperand(i)->hasOneUse())
562 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
563 DeadInsts.insert(Op); // Attempt to nuke it later.
565 I->setOperand(i, 0); // Drop from the operand list.
568 I->eraseFromParent();