1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source 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/Pass.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Support/Compiler.h"
34 STATISTIC(NumFastStores, "Number of stores deleted");
35 STATISTIC(NumFastOther , "Number of other instrs removed");
38 struct VISIBILITY_HIDDEN DSE : public FunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 DSE() : FunctionPass((intptr_t)&ID) {}
42 virtual bool runOnFunction(Function &F) {
44 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
45 Changed |= runOnBasicBlock(*I);
49 bool runOnBasicBlock(BasicBlock &BB);
50 bool handleFreeWithNonTrivialDependency(FreeInst* F,
51 Instruction* dependency,
52 SetVector<Instruction*>& possiblyDead);
53 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
54 bool RemoveUndeadPointers(Value* pointer,
55 BasicBlock::iterator& BBI,
56 SmallPtrSet<AllocaInst*, 64>& deadPointers,
57 SetVector<Instruction*>& possiblyDead);
58 void DeleteDeadInstructionChains(Instruction *I,
59 SetVector<Instruction*> &DeadInsts);
61 /// Find the base pointer that a pointer came from
62 /// Because this is used to find pointers that originate
63 /// from allocas, it is safe to ignore GEP indices, since
64 /// either the store will be in the alloca, and thus dead,
65 /// or beyond the end of the alloca, and thus undefined.
66 void TranslatePointerBitCasts(Value*& v) {
67 assert(isa<PointerType>(v->getType()) &&
68 "Translating a non-pointer type?");
70 if (BitCastInst* C = dyn_cast<BitCastInst>(v))
72 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
79 // getAnalysisUsage - We require post dominance frontiers (aka Control
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequired<TargetData>();
84 AU.addRequired<AliasAnalysis>();
85 AU.addRequired<MemoryDependenceAnalysis>();
86 AU.addPreserved<AliasAnalysis>();
87 AU.addPreserved<MemoryDependenceAnalysis>();
91 RegisterPass<DSE> X("dse", "Dead Store Elimination");
94 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
96 bool DSE::runOnBasicBlock(BasicBlock &BB) {
97 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
99 // Record the last-seen store to this pointer
100 DenseMap<Value*, StoreInst*> lastStore;
101 // Record instructions possibly made dead by deleting a store
102 SetVector<Instruction*> possiblyDead;
104 bool MadeChange = false;
106 // Do a top-down walk on the BB
107 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
109 // If we find a store or a free...
110 if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
114 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
115 if (!S->isVolatile())
116 pointer = S->getPointerOperand();
120 pointer = cast<FreeInst>(BBI)->getPointerOperand();
122 StoreInst*& last = lastStore[pointer];
123 bool deletedStore = false;
125 // ... to a pointer that has been stored to before...
127 Instruction* dep = MD.getDependency(BBI);
129 // ... and no other memory dependencies are between them....
130 while (dep != MemoryDependenceAnalysis::None &&
131 dep != MemoryDependenceAnalysis::NonLocal &&
132 isa<StoreInst>(dep)) {
134 dep = MD.getDependency(BBI, dep);
139 MD.removeInstruction(last);
141 // DCE instructions only used to calculate that store
142 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
143 possiblyDead.insert(D);
144 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
145 possiblyDead.insert(D);
147 last->eraseFromParent();
156 // Handle frees whose dependencies are non-trivial.
157 if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
159 MadeChange |= handleFreeWithNonTrivialDependency(F,
162 // No known stores after the free
165 // Update our most-recent-store map.
166 last = cast<StoreInst>(BBI);
170 // If this block ends in a return, unwind, unreachable, and eventually
171 // tailcall, then all allocas are dead at its end.
172 if (BB.getTerminator()->getNumSuccessors() == 0)
173 MadeChange |= handleEndBlock(BB, possiblyDead);
176 while (!possiblyDead.empty()) {
177 Instruction *I = possiblyDead.back();
178 possiblyDead.pop_back();
179 DeleteDeadInstructionChains(I, possiblyDead);
185 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
186 /// dependency is a store to a field of that structure
187 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
188 SetVector<Instruction*>& possiblyDead) {
189 TargetData &TD = getAnalysis<TargetData>();
190 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
191 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
193 if (dep == MemoryDependenceAnalysis::None ||
194 dep == MemoryDependenceAnalysis::NonLocal)
197 StoreInst* dependency = dyn_cast<StoreInst>(dep);
200 else if (dependency->isVolatile())
203 Value* depPointer = dependency->getPointerOperand();
204 const Type* depType = dependency->getOperand(0)->getType();
205 unsigned depPointerSize = TD.getTypeSize(depType);
207 // Check for aliasing
208 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
209 depPointer, depPointerSize);
211 if (A == AliasAnalysis::MustAlias) {
213 MD.removeInstruction(dependency);
215 // DCE instructions only used to calculate that store
216 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
217 possiblyDead.insert(D);
218 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
219 possiblyDead.insert(D);
221 dependency->eraseFromParent();
229 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
230 /// function end block. Ex:
233 /// store i32 1, i32* %A
235 bool DSE::handleEndBlock(BasicBlock& BB,
236 SetVector<Instruction*>& possiblyDead) {
237 TargetData &TD = getAnalysis<TargetData>();
238 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
239 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
241 bool MadeChange = false;
243 // Pointers alloca'd in this function are dead in the end block
244 SmallPtrSet<AllocaInst*, 64> deadPointers;
246 // Find all of the alloca'd pointers in the entry block
247 BasicBlock *Entry = BB.getParent()->begin();
248 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
249 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
250 deadPointers.insert(AI);
252 // Scan the basic block backwards
253 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
256 if (deadPointers.empty())
259 // If we find a store whose pointer is dead...
260 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
261 if (!S->isVolatile()) {
262 Value* pointerOperand = S->getPointerOperand();
263 // See through pointer-to-pointer bitcasts
264 TranslatePointerBitCasts(pointerOperand);
266 if (deadPointers.count(pointerOperand)){
268 MD.removeInstruction(S);
270 // DCE instructions only used to calculate that store
271 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
272 possiblyDead.insert(D);
273 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
274 possiblyDead.insert(D);
277 S->eraseFromParent();
286 Value* killPointer = 0;
288 // If we encounter a use of the pointer, it is no longer considered dead
289 if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
290 killPointer = L->getPointerOperand();
291 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
292 killPointer = V->getOperand(0);
293 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
294 deadPointers.erase(A);
296 } else if (CallSite::get(BBI).getInstruction() != 0) {
297 // If this call does not access memory, it can't
298 // be undeadifying any of our pointers.
299 CallSite CS = CallSite::get(BBI);
300 if (CS.getCalledFunction() &&
301 AA.doesNotAccessMemory(CS.getCalledFunction()))
307 // Remove any pointers made undead by the call from the dead set
308 std::vector<Instruction*> dead;
309 for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
310 E = deadPointers.end(); I != E; ++I) {
311 // HACK: if we detect that our AA is imprecise, it's not
312 // worth it to scan the rest of the deadPointers set. Just
313 // assume that the AA will return ModRef for everything, and
314 // go ahead and bail.
315 if (modRef >= 16 && other == 0) {
316 deadPointers.clear();
320 // Get size information for the alloca
321 unsigned pointerSize = ~0UL;
322 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
323 pointerSize = C->getZExtValue() * \
324 TD.getTypeSize((*I)->getAllocatedType());
326 // See if the call site touches it
327 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
329 if (A == AliasAnalysis::ModRef)
334 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
338 for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
340 deadPointers.erase(*I);
348 TranslatePointerBitCasts(killPointer);
350 // Deal with undead pointers
351 MadeChange |= RemoveUndeadPointers(killPointer, BBI,
352 deadPointers, possiblyDead);
358 /// RemoveUndeadPointers - check for uses of a pointer that make it
359 /// undead when scanning for dead stores to alloca's.
360 bool DSE::RemoveUndeadPointers(Value* killPointer,
361 BasicBlock::iterator& BBI,
362 SmallPtrSet<AllocaInst*, 64>& deadPointers,
363 SetVector<Instruction*>& possiblyDead) {
364 TargetData &TD = getAnalysis<TargetData>();
365 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
366 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
368 // If the kill pointer can be easily reduced to an alloca,
369 // don't bother doing extraneous AA queries
370 if (AllocaInst* A = dyn_cast<AllocaInst>(killPointer)) {
371 if (deadPointers.count(A))
372 deadPointers.erase(A);
374 } else if (isa<GlobalValue>(killPointer)) {
375 // A global can't be in the dead pointer set
379 bool MadeChange = false;
381 std::vector<Instruction*> undead;
383 for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
384 E = deadPointers.end(); I != E; ++I) {
385 // Get size information for the alloca
386 unsigned pointerSize = ~0UL;
387 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
388 pointerSize = C->getZExtValue() * \
389 TD.getTypeSize((*I)->getAllocatedType());
391 // See if this pointer could alias it
392 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
395 // If it must-alias and a store, we can delete it
396 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
397 StoreInst* S = cast<StoreInst>(BBI);
400 MD.removeInstruction(S);
402 // DCE instructions only used to calculate that store
403 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
404 possiblyDead.insert(D);
405 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
406 possiblyDead.insert(D);
409 S->eraseFromParent();
415 // Otherwise, it is undead
416 } else if (A != AliasAnalysis::NoAlias)
417 undead.push_back(*I);
420 for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
422 deadPointers.erase(*I);
427 /// DeleteDeadInstructionChains - takes an instruction and a setvector of
428 /// dead instructions. If I is dead, it is erased, and its operands are
429 /// checked for deadness. If they are dead, they are added to the dead
431 void DSE::DeleteDeadInstructionChains(Instruction *I,
432 SetVector<Instruction*> &DeadInsts) {
433 // Instruction must be dead.
434 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
436 // Let the memory dependence know
437 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
439 // See if this made any operands dead. We do it this way in case the
440 // instruction uses the same operand twice. We don't want to delete a
441 // value then reference it.
442 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
443 if (I->getOperand(i)->hasOneUse())
444 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
445 DeadInsts.insert(Op); // Attempt to nuke it later.
447 I->setOperand(i, 0); // Drop from the operand list.
450 I->eraseFromParent();