Add comment.
[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/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Support/Compiler.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 VISIBILITY_HIDDEN DSE : public FunctionPass {
40     static char ID; // Pass identification, replacement for typeid
41     DSE() : FunctionPass((intptr_t)&ID) {}
42
43     virtual bool runOnFunction(Function &F) {
44       bool Changed = false;
45       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
46         Changed |= runOnBasicBlock(*I);
47       return Changed;
48     }
49
50     bool runOnBasicBlock(BasicBlock &BB);
51     bool handleFreeWithNonTrivialDependency(FreeInst* F,
52                                             Instruction* dependency,
53                                         SetVector<Instruction*>& possiblyDead);
54     bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
55     bool RemoveUndeadPointers(Value* pointer, uint64_t killPointerSize,
56                               BasicBlock::iterator& BBI,
57                               SmallPtrSet<Value*, 64>& deadPointers, 
58                               SetVector<Instruction*>& possiblyDead);
59     void DeleteDeadInstructionChains(Instruction *I,
60                                      SetVector<Instruction*> &DeadInsts);
61     
62     /// Find the base pointer that a pointer came from
63     /// Because this is used to find pointers that originate
64     /// from allocas, it is safe to ignore GEP indices, since
65     /// either the store will be in the alloca, and thus dead,
66     /// or beyond the end of the alloca, and thus undefined.
67     void TranslatePointerBitCasts(Value*& v, bool zeroGepsOnly = false) {
68       assert(isa<PointerType>(v->getType()) &&
69              "Translating a non-pointer type?");
70       while (true) {
71         if (BitCastInst* C = dyn_cast<BitCastInst>(v))
72           v = C->getOperand(0);
73         else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
74           if (!zeroGepsOnly || G->hasAllZeroIndices()) {
75             v = G->getOperand(0);
76           } else {
77             break;
78           }
79         else
80           break;
81       }
82     }
83
84     // getAnalysisUsage - We require post dominance frontiers (aka Control
85     // Dependence Graph)
86     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87       AU.setPreservesCFG();
88       AU.addRequired<TargetData>();
89       AU.addRequired<AliasAnalysis>();
90       AU.addRequired<MemoryDependenceAnalysis>();
91       AU.addPreserved<AliasAnalysis>();
92       AU.addPreserved<MemoryDependenceAnalysis>();
93     }
94   };
95   char DSE::ID = 0;
96   RegisterPass<DSE> X("dse", "Dead Store Elimination");
97 }
98
99 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
100
101 bool DSE::runOnBasicBlock(BasicBlock &BB) {
102   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
103   TargetData &TD = getAnalysis<TargetData>();  
104
105   // Record the last-seen store to this pointer
106   DenseMap<Value*, StoreInst*> lastStore;
107   // Record instructions possibly made dead by deleting a store
108   SetVector<Instruction*> possiblyDead;
109   
110   bool MadeChange = false;
111   
112   // Do a top-down walk on the BB
113   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
114        BBI != BBE; ++BBI) {
115     // If we find a store or a free...
116     if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
117       continue;
118       
119     Value* pointer = 0;
120     if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
121       if (!S->isVolatile())
122         pointer = S->getPointerOperand();
123       else
124         continue;
125     } else
126       pointer = cast<FreeInst>(BBI)->getPointerOperand();
127       
128     TranslatePointerBitCasts(pointer, true);
129     StoreInst*& last = lastStore[pointer];
130     bool deletedStore = false;
131       
132     // ... to a pointer that has been stored to before...
133     if (last) {
134       Instruction* dep = MD.getDependency(BBI);
135         
136       // ... and no other memory dependencies are between them....
137       while (dep != MemoryDependenceAnalysis::None &&
138              dep != MemoryDependenceAnalysis::NonLocal &&
139              isa<StoreInst>(dep)) {
140         if (dep != last ||
141              TD.getTypeStoreSize(last->getOperand(0)->getType()) >
142              TD.getTypeStoreSize(BBI->getOperand(0)->getType())) {
143           dep = MD.getDependency(BBI, dep);
144           continue;
145         }
146         
147         // Remove it!
148         MD.removeInstruction(last);
149           
150         // DCE instructions only used to calculate that store
151         if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
152           possiblyDead.insert(D);
153         if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
154           possiblyDead.insert(D);
155         
156         last->eraseFromParent();
157         NumFastStores++;
158         deletedStore = true;
159         MadeChange = true;
160           
161         break;
162       }
163     }
164     
165     // Handle frees whose dependencies are non-trivial.
166     if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
167       if (!deletedStore)
168         MadeChange |= handleFreeWithNonTrivialDependency(F,
169                                                          MD.getDependency(F),
170                                                          possiblyDead);
171       // No known stores after the free
172       last = 0;
173     } else {
174       // Update our most-recent-store map.
175       last = cast<StoreInst>(BBI);
176     }
177   }
178   
179   // If this block ends in a return, unwind, unreachable, and eventually
180   // tailcall, then all allocas are dead at its end.
181   if (BB.getTerminator()->getNumSuccessors() == 0)
182     MadeChange |= handleEndBlock(BB, possiblyDead);
183   
184   // Do a trivial DCE
185   while (!possiblyDead.empty()) {
186     Instruction *I = possiblyDead.back();
187     possiblyDead.pop_back();
188     DeleteDeadInstructionChains(I, possiblyDead);
189   }
190   
191   return MadeChange;
192 }
193
194 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
195 /// dependency is a store to a field of that structure
196 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
197                                        SetVector<Instruction*>& possiblyDead) {
198   TargetData &TD = getAnalysis<TargetData>();
199   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
200   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
201   
202   if (dep == MemoryDependenceAnalysis::None ||
203       dep == MemoryDependenceAnalysis::NonLocal)
204     return false;
205   
206   StoreInst* dependency = dyn_cast<StoreInst>(dep);
207   if (!dependency)
208     return false;
209   else if (dependency->isVolatile())
210     return false;
211   
212   Value* depPointer = dependency->getPointerOperand();
213   const Type* depType = dependency->getOperand(0)->getType();
214   unsigned depPointerSize = TD.getTypeStoreSize(depType);
215
216   // Check for aliasing
217   AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0U,
218                                           depPointer, depPointerSize);
219
220   if (A == AliasAnalysis::MustAlias) {
221     // Remove it!
222     MD.removeInstruction(dependency);
223
224     // DCE instructions only used to calculate that store
225     if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
226       possiblyDead.insert(D);
227     if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
228       possiblyDead.insert(D);
229
230     dependency->eraseFromParent();
231     NumFastStores++;
232     return true;
233   }
234   
235   return false;
236 }
237
238 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
239 /// function end block.  Ex:
240 /// %A = alloca i32
241 /// ...
242 /// store i32 1, i32* %A
243 /// ret void
244 bool DSE::handleEndBlock(BasicBlock& BB,
245                          SetVector<Instruction*>& possiblyDead) {
246   TargetData &TD = getAnalysis<TargetData>();
247   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
248   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
249   
250   bool MadeChange = false;
251   
252   // Pointers alloca'd in this function are dead in the end block
253   SmallPtrSet<Value*, 64> deadPointers;
254   
255   // Find all of the alloca'd pointers in the entry block
256   BasicBlock *Entry = BB.getParent()->begin();
257   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
258     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
259       deadPointers.insert(AI);
260   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
261        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
262     if (AI->hasByValAttr())
263       deadPointers.insert(AI);
264   
265   // Scan the basic block backwards
266   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
267     --BBI;
268     
269     // If we find a store whose pointer is dead...
270     if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
271       if (!S->isVolatile()) {
272         Value* pointerOperand = S->getPointerOperand();
273         // See through pointer-to-pointer bitcasts
274         TranslatePointerBitCasts(pointerOperand);
275       
276         // Alloca'd pointers or byval arguments (which are functionally like
277         // alloca's) are valid candidates for removal.
278         if (deadPointers.count(pointerOperand)) {
279           // Remove it!
280           MD.removeInstruction(S);
281         
282           // DCE instructions only used to calculate that store
283           if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
284             possiblyDead.insert(D);
285           if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
286             possiblyDead.insert(D);
287         
288           BBI++;
289           S->eraseFromParent();
290           NumFastStores++;
291           MadeChange = true;
292         }
293       }
294       
295       continue;
296     
297     // We can also remove memcpy's to local variables at the end of a function
298     } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(BBI)) {
299       Value* dest = M->getDest();
300       TranslatePointerBitCasts(dest);
301       
302       if (deadPointers.count(dest)) {
303         MD.removeInstruction(M);
304         
305         // DCE instructions only used to calculate that memcpy
306         if (Instruction* D = dyn_cast<Instruction>(M->getRawSource()))
307           possiblyDead.insert(D);
308         if (Instruction* D = dyn_cast<Instruction>(M->getLength()))
309           possiblyDead.insert(D);
310         if (Instruction* D = dyn_cast<Instruction>(M->getRawDest()))
311           possiblyDead.insert(D);
312         
313         BBI++;
314         M->eraseFromParent();
315         NumFastOther++;
316         MadeChange = true;
317         
318         continue;
319       }
320       
321       // Because a memcpy is also a load, we can't skip it if we didn't remove it
322     }
323     
324     Value* killPointer = 0;
325     uint64_t killPointerSize = ~0UL;
326     
327     // If we encounter a use of the pointer, it is no longer considered dead
328     if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
329       // However, if this load is unused, we can go ahead and remove it, and
330       // not have to worry about it making our pointer undead!
331       if (L->use_empty()) {
332         MD.removeInstruction(L);
333         
334         // DCE instructions only used to calculate that load
335         if (Instruction* D = dyn_cast<Instruction>(L->getPointerOperand()))
336           possiblyDead.insert(D);
337         
338         BBI++;
339         L->eraseFromParent();
340         NumFastOther++;
341         MadeChange = true;
342         possiblyDead.remove(L);
343         
344         continue;
345       }
346       
347       killPointer = L->getPointerOperand();
348     } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
349       killPointer = V->getOperand(0);
350     } else if (isa<MemCpyInst>(BBI) &&
351                isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) {
352       killPointer = cast<MemCpyInst>(BBI)->getSource();
353       killPointerSize = cast<ConstantInt>(
354                             cast<MemCpyInst>(BBI)->getLength())->getZExtValue();
355     } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
356       deadPointers.erase(A);
357       
358       // Dead alloca's can be DCE'd when we reach them
359       if (A->use_empty()) {
360         MD.removeInstruction(A);
361         
362         // DCE instructions only used to calculate that load
363         if (Instruction* D = dyn_cast<Instruction>(A->getArraySize()))
364           possiblyDead.insert(D);
365         
366         BBI++;
367         A->eraseFromParent();
368         NumFastOther++;
369         MadeChange = true;
370         possiblyDead.remove(A);
371       }
372       
373       continue;
374     } else if (CallSite::get(BBI).getInstruction() != 0) {
375       // If this call does not access memory, it can't
376       // be undeadifying any of our pointers.
377       CallSite CS = CallSite::get(BBI);
378       if (AA.doesNotAccessMemory(CS))
379         continue;
380       
381       unsigned modRef = 0;
382       unsigned other = 0;
383       
384       // Remove any pointers made undead by the call from the dead set
385       std::vector<Value*> dead;
386       for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
387            E = deadPointers.end(); I != E; ++I) {
388         // HACK: if we detect that our AA is imprecise, it's not
389         // worth it to scan the rest of the deadPointers set.  Just
390         // assume that the AA will return ModRef for everything, and
391         // go ahead and bail.
392         if (modRef >= 16 && other == 0) {
393           deadPointers.clear();
394           return MadeChange;
395         }
396
397         // Get size information for the alloca
398         unsigned pointerSize = ~0U;
399         if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
400           if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
401             pointerSize = C->getZExtValue() * \
402                           TD.getABITypeSize(A->getAllocatedType());
403         } else {
404           const PointerType* PT = cast<PointerType>(
405                                                  cast<Argument>(*I)->getType());
406           pointerSize = TD.getABITypeSize(PT->getElementType());
407         }
408
409         // See if the call site touches it
410         AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
411         
412         if (A == AliasAnalysis::ModRef)
413           modRef++;
414         else
415           other++;
416         
417         if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
418           dead.push_back(*I);
419       }
420
421       for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
422            I != E; ++I)
423         deadPointers.erase(*I);
424       
425       continue;
426     } else {
427       // For any non-memory-affecting non-terminators, DCE them as we reach them
428       Instruction *CI = BBI;
429       if (!CI->isTerminator() && CI->use_empty() && !isa<FreeInst>(CI)) {
430         
431         // DCE instructions only used to calculate that load
432         for (Instruction::op_iterator OI = CI->op_begin(), OE = CI->op_end();
433              OI != OE; ++OI)
434           if (Instruction* D = dyn_cast<Instruction>(OI))
435             possiblyDead.insert(D);
436         
437         BBI++;
438         CI->eraseFromParent();
439         NumFastOther++;
440         MadeChange = true;
441         possiblyDead.remove(CI);
442         
443         continue;
444       }
445     }
446     
447     if (!killPointer)
448       continue;
449     
450     TranslatePointerBitCasts(killPointer);
451     
452     // Deal with undead pointers
453     MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
454                                        deadPointers, possiblyDead);
455   }
456   
457   return MadeChange;
458 }
459
460 /// RemoveUndeadPointers - check for uses of a pointer that make it
461 /// undead when scanning for dead stores to alloca's.
462 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
463                                 BasicBlock::iterator& BBI,
464                                 SmallPtrSet<Value*, 64>& deadPointers, 
465                                 SetVector<Instruction*>& possiblyDead) {
466   TargetData &TD = getAnalysis<TargetData>();
467   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
468   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
469                                   
470   // If the kill pointer can be easily reduced to an alloca,
471   // don't bother doing extraneous AA queries
472   if (deadPointers.count(killPointer)) {
473     deadPointers.erase(killPointer);
474     return false;
475   } else if (isa<GlobalValue>(killPointer)) {
476     // A global can't be in the dead pointer set
477     return false;
478   }
479   
480   bool MadeChange = false;
481   
482   std::vector<Value*> undead;
483     
484   for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
485       E = deadPointers.end(); I != E; ++I) {
486     // Get size information for the alloca
487     unsigned pointerSize = ~0U;
488     if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
489       if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
490         pointerSize = C->getZExtValue() * \
491                       TD.getABITypeSize(A->getAllocatedType());
492     } else {
493       const PointerType* PT = cast<PointerType>(
494                                                 cast<Argument>(*I)->getType());
495       pointerSize = TD.getABITypeSize(PT->getElementType());
496     }
497
498     // See if this pointer could alias it
499     AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
500                                             killPointer, killPointerSize);
501
502     // If it must-alias and a store, we can delete it
503     if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
504       StoreInst* S = cast<StoreInst>(BBI);
505
506       // Remove it!
507       MD.removeInstruction(S);
508
509       // DCE instructions only used to calculate that store
510       if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
511         possiblyDead.insert(D);
512       if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
513         possiblyDead.insert(D);
514
515       BBI++;
516       S->eraseFromParent();
517       NumFastStores++;
518       MadeChange = true;
519
520       continue;
521
522       // Otherwise, it is undead
523       } else if (A != AliasAnalysis::NoAlias)
524         undead.push_back(*I);
525   }
526
527   for (std::vector<Value*>::iterator I = undead.begin(), E = undead.end();
528        I != E; ++I)
529       deadPointers.erase(*I);
530   
531   return MadeChange;
532 }
533
534 /// DeleteDeadInstructionChains - takes an instruction and a setvector of
535 /// dead instructions.  If I is dead, it is erased, and its operands are
536 /// checked for deadness.  If they are dead, they are added to the dead
537 /// setvector.
538 void DSE::DeleteDeadInstructionChains(Instruction *I,
539                                       SetVector<Instruction*> &DeadInsts) {
540   // Instruction must be dead.
541   if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
542
543   // Let the memory dependence know
544   getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
545
546   // See if this made any operands dead.  We do it this way in case the
547   // instruction uses the same operand twice.  We don't want to delete a
548   // value then reference it.
549   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
550     if (I->getOperand(i)->hasOneUse())
551       if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
552         DeadInsts.insert(Op);      // Attempt to nuke it later.
553     
554     I->setOperand(i, 0);         // Drop from the operand list.
555   }
556
557   I->eraseFromParent();
558   ++NumFastOther;
559 }