f55d8b2accbb59598b7bd9e25c13724fd4897de2
[oota-llvm.git] / lib / Transforms / Scalar / DeadStoreElimination.cpp
1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a trivial dead store elimination that only considers
11 // basic-block local redundant stores.
12 //
13 // FIXME: This should eventually be extended to be a post-dominator tree
14 // traversal.  Doing so would be pretty trivial.
15 //
16 //===----------------------------------------------------------------------===//
17
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/MallocHelper.h"
30 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 using namespace llvm;
34
35 STATISTIC(NumFastStores, "Number of stores deleted");
36 STATISTIC(NumFastOther , "Number of other instrs removed");
37
38 namespace {
39   struct DSE : public FunctionPass {
40     TargetData *TD;
41
42     static char ID; // Pass identification, replacement for typeid
43     DSE() : FunctionPass(&ID) {}
44
45     virtual bool runOnFunction(Function &F) {
46       bool Changed = false;
47       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
48         Changed |= runOnBasicBlock(*I);
49       return Changed;
50     }
51     
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);
60     
61
62     // getAnalysisUsage - We require post dominance frontiers (aka Control
63     // Dependence Graph)
64     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.setPreservesCFG();
66       AU.addRequired<DominatorTree>();
67       AU.addRequired<AliasAnalysis>();
68       AU.addRequired<MemoryDependenceAnalysis>();
69       AU.addPreserved<DominatorTree>();
70       AU.addPreserved<AliasAnalysis>();
71       AU.addPreserved<MemoryDependenceAnalysis>();
72     }
73   };
74 }
75
76 char DSE::ID = 0;
77 static RegisterPass<DSE> X("dse", "Dead Store Elimination");
78
79 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
80
81 bool DSE::runOnBasicBlock(BasicBlock &BB) {
82   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
83   TD = getAnalysisIfAvailable<TargetData>();
84
85   bool MadeChange = false;
86   
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++;
90     
91     // If we find a store or a free, get its memory dependence.
92     if (!isa<StoreInst>(Inst) && !isa<FreeInst>(Inst) && !isFreeCall(Inst))
93       continue;
94     
95     // Don't molest volatile stores or do queries that will return "clobber".
96     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
97       if (SI->isVolatile())
98         continue;
99
100     MemDepResult InstDep = MD.getDependency(Inst);
101     
102     // Ignore non-local stores.
103     // FIXME: cross-block DSE would be fun. :)
104     if (InstDep.isNonLocal()) continue;
105   
106     // Handle frees whose dependencies are non-trivial.
107     if (isa<FreeInst>(Inst) || isFreeCall(Inst)) {
108       MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
109       continue;
110     }
111     
112     StoreInst *SI = cast<StoreInst>(Inst);
113     
114     // If not a definite must-alias dependency, ignore it.
115     if (!InstDep.isDef())
116       continue;
117     
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()))
121       if (TD &&
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);
126         NumFastStores++;
127         MadeChange = true;
128
129         // DeleteDeadInstruction can delete the current instruction in loop
130         // cases, reset BBI.
131         BBI = Inst;
132         if (BBI != BB.begin())
133           --BBI;
134         continue;
135       }
136     
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);
145         
146         DeleteDeadInstruction(SI);
147         
148         if (NextInst == 0)  // Next instruction deleted.
149           BBI = BB.begin();
150         else if (BBI != BB.begin())  // Revisit this instruction if possible.
151           --BBI;
152         NumFastStores++;
153         MadeChange = true;
154         continue;
155       }
156     }
157   }
158   
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);
163   
164   return MadeChange;
165 }
166
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>();
171   
172   StoreInst *Dependency = dyn_cast_or_null<StoreInst>(Dep.getInst());
173   if (!Dependency || Dependency->isVolatile())
174     return false;
175   
176   Value *DepPointer = Dependency->getPointerOperand()->getUnderlyingObject();
177
178   // Check for aliasing.
179   Value* FreeVal = isa<FreeInst>(F) ? F->getOperand(0) : F->getOperand(1);
180   if (AA.alias(FreeVal, 1, DepPointer, 1) !=
181          AliasAnalysis::MustAlias)
182     return false;
183   
184   // DCE instructions only used to calculate that store
185   DeleteDeadInstruction(Dependency);
186   NumFastStores++;
187   return true;
188 }
189
190 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
191 /// function end block.  Ex:
192 /// %A = alloca i32
193 /// ...
194 /// store i32 1, i32* %A
195 /// ret void
196 bool DSE::handleEndBlock(BasicBlock &BB) {
197   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
198   
199   bool MadeChange = false;
200   
201   // Pointers alloca'd in this function are dead in the end block
202   SmallPtrSet<Value*, 64> deadPointers;
203   
204   // Find all of the alloca'd pointers in the entry block.
205   BasicBlock *Entry = BB.getParent()->begin();
206   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
207     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
208       deadPointers.insert(AI);
209   
210   // Treat byval arguments the same, stores to them are dead at the end of the
211   // function.
212   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
213        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
214     if (AI->hasByValAttr())
215       deadPointers.insert(AI);
216   
217   // Scan the basic block backwards
218   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
219     --BBI;
220     
221     // If we find a store whose pointer is dead.
222     if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
223       if (!S->isVolatile()) {
224         // See through pointer-to-pointer bitcasts
225         Value* pointerOperand = S->getPointerOperand()->getUnderlyingObject();
226
227         // Alloca'd pointers or byval arguments (which are functionally like
228         // alloca's) are valid candidates for removal.
229         if (deadPointers.count(pointerOperand)) {
230           // DCE instructions only used to calculate that store.
231           BBI++;
232           DeleteDeadInstruction(S, &deadPointers);
233           NumFastStores++;
234           MadeChange = true;
235         }
236       }
237       
238       continue;
239     }
240     
241     // We can also remove memcpy's to local variables at the end of a function.
242     if (MemCpyInst *M = dyn_cast<MemCpyInst>(BBI)) {
243       Value *dest = M->getDest()->getUnderlyingObject();
244
245       if (deadPointers.count(dest)) {
246         BBI++;
247         DeleteDeadInstruction(M, &deadPointers);
248         NumFastOther++;
249         MadeChange = true;
250         continue;
251       }
252       
253       // Because a memcpy is also a load, we can't skip it if we didn't remove
254       // it.
255     }
256     
257     Value* killPointer = 0;
258     uint64_t killPointerSize = ~0UL;
259     
260     // If we encounter a use of the pointer, it is no longer considered dead
261     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
262       // However, if this load is unused and not volatile, we can go ahead and
263       // remove it, and not have to worry about it making our pointer undead!
264       if (L->use_empty() && !L->isVolatile()) {
265         BBI++;
266         DeleteDeadInstruction(L, &deadPointers);
267         NumFastOther++;
268         MadeChange = true;
269         continue;
270       }
271       
272       killPointer = L->getPointerOperand();
273     } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
274       killPointer = V->getOperand(0);
275     } else if (isa<MemCpyInst>(BBI) &&
276                isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) {
277       killPointer = cast<MemCpyInst>(BBI)->getSource();
278       killPointerSize = cast<ConstantInt>(
279                             cast<MemCpyInst>(BBI)->getLength())->getZExtValue();
280     } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
281       deadPointers.erase(A);
282       
283       // Dead alloca's can be DCE'd when we reach them
284       if (A->use_empty()) {
285         BBI++;
286         DeleteDeadInstruction(A, &deadPointers);
287         NumFastOther++;
288         MadeChange = true;
289       }
290       
291       continue;
292     } else if (CallSite::get(BBI).getInstruction() != 0) {
293       // If this call does not access memory, it can't
294       // be undeadifying any of our pointers.
295       CallSite CS = CallSite::get(BBI);
296       if (AA.doesNotAccessMemory(CS))
297         continue;
298       
299       unsigned modRef = 0;
300       unsigned other = 0;
301       
302       // Remove any pointers made undead by the call from the dead set
303       std::vector<Value*> dead;
304       for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
305            E = deadPointers.end(); I != E; ++I) {
306         // HACK: if we detect that our AA is imprecise, it's not
307         // worth it to scan the rest of the deadPointers set.  Just
308         // assume that the AA will return ModRef for everything, and
309         // go ahead and bail.
310         if (modRef >= 16 && other == 0) {
311           deadPointers.clear();
312           return MadeChange;
313         }
314
315         // Get size information for the alloca
316         unsigned pointerSize = ~0U;
317         if (TD) {
318           if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
319             if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
320               pointerSize = C->getZExtValue() *
321                             TD->getTypeAllocSize(A->getAllocatedType());
322           } else {
323             const PointerType* PT = cast<PointerType>(
324                                                    cast<Argument>(*I)->getType());
325             pointerSize = TD->getTypeAllocSize(PT->getElementType());
326           }
327         }
328
329         // See if the call site touches it
330         AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
331         
332         if (A == AliasAnalysis::ModRef)
333           modRef++;
334         else
335           other++;
336         
337         if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
338           dead.push_back(*I);
339       }
340
341       for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
342            I != E; ++I)
343         deadPointers.erase(*I);
344       
345       continue;
346     } else if (isInstructionTriviallyDead(BBI)) {
347       // For any non-memory-affecting non-terminators, DCE them as we reach them
348       Instruction *Inst = BBI;
349       BBI++;
350       DeleteDeadInstruction(Inst, &deadPointers);
351       NumFastOther++;
352       MadeChange = true;
353       continue;
354     }
355     
356     if (!killPointer)
357       continue;
358
359     killPointer = killPointer->getUnderlyingObject();
360
361     // Deal with undead pointers
362     MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
363                                        deadPointers);
364   }
365   
366   return MadeChange;
367 }
368
369 /// RemoveUndeadPointers - check for uses of a pointer that make it
370 /// undead when scanning for dead stores to alloca's.
371 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
372                                BasicBlock::iterator &BBI,
373                                SmallPtrSet<Value*, 64>& deadPointers) {
374   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
375                                   
376   // If the kill pointer can be easily reduced to an alloca,
377   // don't bother doing extraneous AA queries.
378   if (deadPointers.count(killPointer)) {
379     deadPointers.erase(killPointer);
380     return false;
381   }
382   
383   // A global can't be in the dead pointer set.
384   if (isa<GlobalValue>(killPointer))
385     return false;
386   
387   bool MadeChange = false;
388   
389   SmallVector<Value*, 16> undead;
390     
391   for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
392       E = deadPointers.end(); I != E; ++I) {
393     // Get size information for the alloca.
394     unsigned pointerSize = ~0U;
395     if (TD) {
396       if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
397         if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
398           pointerSize = C->getZExtValue() *
399                         TD->getTypeAllocSize(A->getAllocatedType());
400       } else {
401         const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
402         pointerSize = TD->getTypeAllocSize(PT->getElementType());
403       }
404     }
405
406     // See if this pointer could alias it
407     AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
408                                             killPointer, killPointerSize);
409
410     // If it must-alias and a store, we can delete it
411     if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
412       StoreInst* S = cast<StoreInst>(BBI);
413
414       // Remove it!
415       BBI++;
416       DeleteDeadInstruction(S, &deadPointers);
417       NumFastStores++;
418       MadeChange = true;
419
420       continue;
421
422       // Otherwise, it is undead
423     } else if (A != AliasAnalysis::NoAlias)
424       undead.push_back(*I);
425   }
426
427   for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
428        I != E; ++I)
429       deadPointers.erase(*I);
430   
431   return MadeChange;
432 }
433
434 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
435 /// and zero out all the operands of this instruction.  If any of them become
436 /// dead, delete them and the computation tree that feeds them.
437 ///
438 /// If ValueSet is non-null, remove any deleted instructions from it as well.
439 ///
440 void DSE::DeleteDeadInstruction(Instruction *I,
441                                 SmallPtrSet<Value*, 64> *ValueSet) {
442   SmallVector<Instruction*, 32> NowDeadInsts;
443   
444   NowDeadInsts.push_back(I);
445   --NumFastOther;
446
447   // Before we touch this instruction, remove it from memdep!
448   MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
449   while (!NowDeadInsts.empty()) {
450     Instruction *DeadInst = NowDeadInsts.back();
451     NowDeadInsts.pop_back();
452     
453     ++NumFastOther;
454     
455     // This instruction is dead, zap it, in stages.  Start by removing it from
456     // MemDep, which needs to know the operands and needs it to be in the
457     // function.
458     MDA.removeInstruction(DeadInst);
459     
460     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
461       Value *Op = DeadInst->getOperand(op);
462       DeadInst->setOperand(op, 0);
463       
464       // If this operand just became dead, add it to the NowDeadInsts list.
465       if (!Op->use_empty()) continue;
466       
467       if (Instruction *OpI = dyn_cast<Instruction>(Op))
468         if (isInstructionTriviallyDead(OpI))
469           NowDeadInsts.push_back(OpI);
470     }
471     
472     DeadInst->eraseFromParent();
473     
474     if (ValueSet) ValueSet->erase(DeadInst);
475   }
476 }