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