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