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