Fix obvious typo.
[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/MemoryBuiltins.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 /// doesClobberMemory - Does this instruction clobber (write without reading)
82 /// some memory?
83 static bool doesClobberMemory(Instruction *I) {
84   if (isa<StoreInst>(I))
85     return true;
86   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
87     switch (II->getIntrinsicID()) {
88     default: return false;
89     case Intrinsic::memset: case Intrinsic::memmove: case Intrinsic::memcpy:
90     case Intrinsic::init_trampoline: case Intrinsic::lifetime_end: return true;
91     }
92   }
93   return false;
94 }
95
96 /// isElidable - If the value of this instruction and the memory it writes to is
97 /// unused, may we delete this instrtction?
98 static bool isElidable(Instruction *I) {
99   assert(doesClobberMemory(I));
100   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
101     return II->getIntrinsicID() != Intrinsic::lifetime_end;
102   if (StoreInst *SI = dyn_cast<StoreInst>(I))
103     return !SI->isVolatile();
104   return true;
105 }
106
107 /// getPointerOperand - Return the pointer that is being clobbered.
108 static Value *getPointerOperand(Instruction *I) {
109   assert(doesClobberMemory(I));
110   if (StoreInst *SI = dyn_cast<StoreInst>(I))
111     return SI->getPointerOperand();
112   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
113     return MI->getOperand(1);
114   IntrinsicInst *II = cast<IntrinsicInst>(I);
115   switch (II->getIntrinsicID()) {
116     default:
117       assert(false && "Unexpected intrinsic!");
118     case Intrinsic::init_trampoline:
119       return II->getOperand(1);
120     case Intrinsic::lifetime_end:
121       return II->getOperand(2);
122   }
123 }
124
125 /// getStoreSize - Return the length in bytes of the write by the clobbering
126 /// instruction. If variable or unknown, returns -1.
127 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
128   assert(doesClobberMemory(I));
129   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
130     if (!TD) return -1u;
131     return TD->getTypeStoreSize(SI->getOperand(0)->getType());
132   }
133
134   Value *Len;
135   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
136     Len = MI->getLength();
137   } else {
138     IntrinsicInst *II = cast<IntrinsicInst>(I);
139     switch (II->getIntrinsicID()) {
140       default:
141         assert(false && "Unexpected intrinsic!");
142       case Intrinsic::init_trampoline:
143         return -1u;
144       case Intrinsic::lifetime_end:
145         Len = II->getOperand(1);
146     }
147   }
148   if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
149     if (!LenCI->isAllOnesValue())
150       return LenCI->getZExtValue();
151   return -1u;
152 }
153
154 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
155 /// greater than or equal to the store in I2.  This returns false if we don't
156 /// know.
157 ///
158 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
159                                    const TargetData *TD) {
160   const Type *I1Ty = getPointerOperand(I1)->getType();
161   const Type *I2Ty = getPointerOperand(I2)->getType();
162   
163   // Exactly the same type, must have exactly the same size.
164   if (I1Ty == I2Ty) return true;
165   
166   int I1Size = getStoreSize(I1, TD);
167   int I2Size = getStoreSize(I2, TD);
168   
169   return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
170 }
171
172 bool DSE::runOnBasicBlock(BasicBlock &BB) {
173   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
174   TD = getAnalysisIfAvailable<TargetData>();
175
176   bool MadeChange = false;
177   
178   // Do a top-down walk on the BB.
179   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
180     Instruction *Inst = BBI++;
181     
182     // If we find a store or a free, get its memory dependence.
183     if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
184       continue;
185     
186     MemDepResult InstDep = MD.getDependency(Inst);
187     
188     // Ignore non-local stores.
189     // FIXME: cross-block DSE would be fun. :)
190     if (InstDep.isNonLocal()) continue;
191   
192     // Handle frees whose dependencies are non-trivial.
193     if (isFreeCall(Inst)) {
194       MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
195       continue;
196     }
197     
198     // If not a definite must-alias dependency, ignore it.
199     if (!InstDep.isDef())
200       continue;
201     
202     // If this is a store-store dependence, then the previous store is dead so
203     // long as this store is at least as big as it.
204     if (doesClobberMemory(InstDep.getInst())) {
205       Instruction *DepStore = InstDep.getInst();
206       if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
207           isElidable(DepStore)) {
208         // Delete the store and now-dead instructions that feed it.
209         DeleteDeadInstruction(DepStore);
210         NumFastStores++;
211         MadeChange = true;
212
213         // DeleteDeadInstruction can delete the current instruction in loop
214         // cases, reset BBI.
215         BBI = Inst;
216         if (BBI != BB.begin())
217           --BBI;
218         continue;
219       }
220     }
221     
222     if (!isElidable(Inst))
223       continue;
224     
225     // If we're storing the same value back to a pointer that we just
226     // loaded from, then the store can be removed.
227     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
228       if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
229         if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
230             SI->getOperand(0) == DepLoad) {
231           // DeleteDeadInstruction can delete the current instruction.  Save BBI
232           // in case we need it.
233           WeakVH NextInst(BBI);
234           
235           DeleteDeadInstruction(SI);
236           
237           if (NextInst == 0)  // Next instruction deleted.
238             BBI = BB.begin();
239           else if (BBI != BB.begin())  // Revisit this instruction if possible.
240             --BBI;
241           NumFastStores++;
242           MadeChange = true;
243           continue;
244         }
245       }
246     }
247     
248     // If this is a lifetime end marker, we can throw away the store.
249     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
250       if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
251         // Delete the store and now-dead instructions that feed it.
252         // DeleteDeadInstruction can delete the current instruction.  Save BBI
253         // in case we need it.
254         WeakVH NextInst(BBI);
255         
256         DeleteDeadInstruction(Inst);
257         
258         if (NextInst == 0)  // Next instruction deleted.
259           BBI = BB.begin();
260         else if (BBI != BB.begin())  // Revisit this instruction if possible.
261           --BBI;
262         NumFastStores++;
263         MadeChange = true;
264         continue;
265       }
266     }
267   }
268   
269   // If this block ends in a return, unwind, or unreachable, all allocas are
270   // dead at its end, which means stores to them are also dead.
271   if (BB.getTerminator()->getNumSuccessors() == 0)
272     MadeChange |= handleEndBlock(BB);
273   
274   return MadeChange;
275 }
276
277 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
278 /// dependency is a store to a field of that structure.
279 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
280   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
281   
282   Instruction *Dependency = Dep.getInst();
283   if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
284     return false;
285   
286   Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
287
288   // Check for aliasing.
289   if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
290          AliasAnalysis::MustAlias)
291     return false;
292   
293   // DCE instructions only used to calculate that store
294   DeleteDeadInstruction(Dependency);
295   NumFastStores++;
296   return true;
297 }
298
299 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
300 /// function end block.  Ex:
301 /// %A = alloca i32
302 /// ...
303 /// store i32 1, i32* %A
304 /// ret void
305 bool DSE::handleEndBlock(BasicBlock &BB) {
306   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
307   
308   bool MadeChange = false;
309   
310   // Pointers alloca'd in this function are dead in the end block
311   SmallPtrSet<Value*, 64> deadPointers;
312   
313   // Find all of the alloca'd pointers in the entry block.
314   BasicBlock *Entry = BB.getParent()->begin();
315   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
316     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
317       deadPointers.insert(AI);
318   
319   // Treat byval arguments the same, stores to them are dead at the end of the
320   // function.
321   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
322        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
323     if (AI->hasByValAttr())
324       deadPointers.insert(AI);
325   
326   // Scan the basic block backwards
327   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
328     --BBI;
329     
330     // If we find a store whose pointer is dead.
331     if (doesClobberMemory(BBI)) {
332       if (isElidable(BBI)) {
333         // See through pointer-to-pointer bitcasts
334         Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
335
336         // Alloca'd pointers or byval arguments (which are functionally like
337         // alloca's) are valid candidates for removal.
338         if (deadPointers.count(pointerOperand)) {
339           // DCE instructions only used to calculate that store.
340           Instruction *Dead = BBI;
341           BBI++;
342           DeleteDeadInstruction(Dead, &deadPointers);
343           NumFastStores++;
344           MadeChange = true;
345           continue;
346         }
347       }
348       
349       // Because a memcpy or memmove is also a load, we can't skip it if we
350       // didn't remove it.
351       if (!isa<MemTransferInst>(BBI))
352         continue;
353     }
354     
355     Value* killPointer = 0;
356     uint64_t killPointerSize = ~0UL;
357     
358     // If we encounter a use of the pointer, it is no longer considered dead
359     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
360       // However, if this load is unused and not volatile, we can go ahead and
361       // remove it, and not have to worry about it making our pointer undead!
362       if (L->use_empty() && !L->isVolatile()) {
363         BBI++;
364         DeleteDeadInstruction(L, &deadPointers);
365         NumFastOther++;
366         MadeChange = true;
367         continue;
368       }
369       
370       killPointer = L->getPointerOperand();
371     } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
372       killPointer = V->getOperand(0);
373     } else if (isa<MemTransferInst>(BBI) &&
374                isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
375       killPointer = cast<MemTransferInst>(BBI)->getSource();
376       killPointerSize = cast<ConstantInt>(
377                        cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
378     } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
379       deadPointers.erase(A);
380       
381       // Dead alloca's can be DCE'd when we reach them
382       if (A->use_empty()) {
383         BBI++;
384         DeleteDeadInstruction(A, &deadPointers);
385         NumFastOther++;
386         MadeChange = true;
387       }
388       
389       continue;
390     } else if (CallSite::get(BBI).getInstruction() != 0) {
391       // If this call does not access memory, it can't
392       // be undeadifying any of our pointers.
393       CallSite CS = CallSite::get(BBI);
394       if (AA.doesNotAccessMemory(CS))
395         continue;
396       
397       unsigned modRef = 0;
398       unsigned other = 0;
399       
400       // Remove any pointers made undead by the call from the dead set
401       std::vector<Value*> dead;
402       for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
403            E = deadPointers.end(); I != E; ++I) {
404         // HACK: if we detect that our AA is imprecise, it's not
405         // worth it to scan the rest of the deadPointers set.  Just
406         // assume that the AA will return ModRef for everything, and
407         // go ahead and bail.
408         if (modRef >= 16 && other == 0) {
409           deadPointers.clear();
410           return MadeChange;
411         }
412
413         // Get size information for the alloca
414         unsigned pointerSize = ~0U;
415         if (TD) {
416           if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
417             if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
418               pointerSize = C->getZExtValue() *
419                             TD->getTypeAllocSize(A->getAllocatedType());
420           } else {
421             const PointerType* PT = cast<PointerType>(
422                                                    cast<Argument>(*I)->getType());
423             pointerSize = TD->getTypeAllocSize(PT->getElementType());
424           }
425         }
426
427         // See if the call site touches it
428         AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
429         
430         if (A == AliasAnalysis::ModRef)
431           modRef++;
432         else
433           other++;
434         
435         if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
436           dead.push_back(*I);
437       }
438
439       for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
440            I != E; ++I)
441         deadPointers.erase(*I);
442       
443       continue;
444     } else if (isInstructionTriviallyDead(BBI)) {
445       // For any non-memory-affecting non-terminators, DCE them as we reach them
446       Instruction *Inst = BBI;
447       BBI++;
448       DeleteDeadInstruction(Inst, &deadPointers);
449       NumFastOther++;
450       MadeChange = true;
451       continue;
452     }
453     
454     if (!killPointer)
455       continue;
456
457     killPointer = killPointer->getUnderlyingObject();
458
459     // Deal with undead pointers
460     MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
461                                        deadPointers);
462   }
463   
464   return MadeChange;
465 }
466
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>();
473                                   
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);
478     return false;
479   }
480   
481   // A global can't be in the dead pointer set.
482   if (isa<GlobalValue>(killPointer))
483     return false;
484   
485   bool MadeChange = false;
486   
487   SmallVector<Value*, 16> undead;
488     
489   for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
490       E = deadPointers.end(); I != E; ++I) {
491     // Get size information for the alloca.
492     unsigned pointerSize = ~0U;
493     if (TD) {
494       if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
495         if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
496           pointerSize = C->getZExtValue() *
497                         TD->getTypeAllocSize(A->getAllocatedType());
498       } else {
499         const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
500         pointerSize = TD->getTypeAllocSize(PT->getElementType());
501       }
502     }
503
504     // See if this pointer could alias it
505     AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
506                                             killPointer, killPointerSize);
507
508     // If it must-alias and a store, we can delete it
509     if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
510       StoreInst* S = cast<StoreInst>(BBI);
511
512       // Remove it!
513       BBI++;
514       DeleteDeadInstruction(S, &deadPointers);
515       NumFastStores++;
516       MadeChange = true;
517
518       continue;
519
520       // Otherwise, it is undead
521     } else if (A != AliasAnalysis::NoAlias)
522       undead.push_back(*I);
523   }
524
525   for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
526        I != E; ++I)
527       deadPointers.erase(*I);
528   
529   return MadeChange;
530 }
531
532 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
533 /// and zero out all the operands of this instruction.  If any of them become
534 /// dead, delete them and the computation tree that feeds them.
535 ///
536 /// If ValueSet is non-null, remove any deleted instructions from it as well.
537 ///
538 void DSE::DeleteDeadInstruction(Instruction *I,
539                                 SmallPtrSet<Value*, 64> *ValueSet) {
540   SmallVector<Instruction*, 32> NowDeadInsts;
541   
542   NowDeadInsts.push_back(I);
543   --NumFastOther;
544
545   // Before we touch this instruction, remove it from memdep!
546   MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
547   while (!NowDeadInsts.empty()) {
548     Instruction *DeadInst = NowDeadInsts.back();
549     NowDeadInsts.pop_back();
550     
551     ++NumFastOther;
552     
553     // This instruction is dead, zap it, in stages.  Start by removing it from
554     // MemDep, which needs to know the operands and needs it to be in the
555     // function.
556     MDA.removeInstruction(DeadInst);
557     
558     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
559       Value *Op = DeadInst->getOperand(op);
560       DeadInst->setOperand(op, 0);
561       
562       // If this operand just became dead, add it to the NowDeadInsts list.
563       if (!Op->use_empty()) continue;
564       
565       if (Instruction *OpI = dyn_cast<Instruction>(Op))
566         if (isInstructionTriviallyDead(OpI))
567           NowDeadInsts.push_back(OpI);
568     }
569     
570     DeadInst->eraseFromParent();
571     
572     if (ValueSet) ValueSet->erase(DeadInst);
573   }
574 }