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