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