9397869ad31600e58f7dec3fb6e09cfaba0ed432
[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 was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source 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/Pass.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Support/Compiler.h"
32 using namespace llvm;
33
34 STATISTIC(NumFastStores, "Number of stores deleted");
35 STATISTIC(NumFastOther , "Number of other instrs removed");
36
37 namespace {
38   struct VISIBILITY_HIDDEN DSE : public FunctionPass {
39     static char ID; // Pass identification, replacement for typeid
40     DSE() : FunctionPass((intptr_t)&ID) {}
41
42     virtual bool runOnFunction(Function &F) {
43       bool Changed = false;
44       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
45         Changed |= runOnBasicBlock(*I);
46       return Changed;
47     }
48
49     bool runOnBasicBlock(BasicBlock &BB);
50     bool handleFreeWithNonTrivialDependency(FreeInst* F,
51                                             Instruction* dependency,
52                                         SetVector<Instruction*>& possiblyDead);
53     bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
54     bool RemoveUndeadPointers(Value* pointer, unsigned pointerSize,
55                               BasicBlock::iterator& BBI,
56                               SmallPtrSet<AllocaInst*, 4>& deadPointers, 
57                               SetVector<Instruction*>& possiblyDead);
58     void DeleteDeadInstructionChains(Instruction *I,
59                                      SetVector<Instruction*> &DeadInsts);
60     
61     // Find the base pointer that a pointer came from
62     // Because this is used to find pointers that originate
63     // from allocas, it is safe to ignore GEP indices, since
64     // either the store will be in the alloca, and thus dead,
65     // or beyond the end of the alloca, and thus undefined.
66     void TranslatePointerBitCasts(Value*& v) {
67       assert(isa<PointerType>(v->getType()) &&
68              "Translating a non-pointer type?");
69       while (true) {
70         if (BitCastInst* C = dyn_cast<BitCastInst>(v))
71           v = C->getOperand(0);
72         else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
73           v = G->getOperand(0);
74         else
75           break;
76       }
77     }
78
79     // getAnalysisUsage - We require post dominance frontiers (aka Control
80     // Dependence Graph)
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.setPreservesCFG();
83       AU.addRequired<TargetData>();
84       AU.addRequired<AliasAnalysis>();
85       AU.addRequired<MemoryDependenceAnalysis>();
86       AU.addPreserved<AliasAnalysis>();
87       AU.addPreserved<MemoryDependenceAnalysis>();
88     }
89   };
90   char DSE::ID = 0;
91   RegisterPass<DSE> X("dse", "Dead Store Elimination");
92 }
93
94 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
95
96 bool DSE::runOnBasicBlock(BasicBlock &BB) {
97   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
98   
99   // Record the last-seen store to this pointer
100   DenseMap<Value*, StoreInst*> lastStore;
101   // Record instructions possibly made dead by deleting a store
102   SetVector<Instruction*> possiblyDead;
103   
104   bool MadeChange = false;
105   
106   // Do a top-down walk on the BB
107   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
108        BBI != BBE; ++BBI) {
109     // If we find a store or a free...
110     if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
111       continue;
112       
113     Value* pointer = 0;
114     if (StoreInst* S = dyn_cast<StoreInst>(BBI))
115       pointer = S->getPointerOperand();
116     else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
117       pointer = F->getPointerOperand();
118       
119     assert(pointer && "Not a free or a store?");
120       
121     StoreInst*& last = lastStore[pointer];
122     bool deletedStore = false;
123       
124     // ... to a pointer that has been stored to before...
125     if (last) {
126       Instruction* dep = MD.getDependency(BBI);
127         
128       // ... and no other memory dependencies are between them....
129       while (dep != MemoryDependenceAnalysis::None &&
130              dep != MemoryDependenceAnalysis::NonLocal &&
131              isa<StoreInst>(dep)) {
132         if (dep != last) {
133           dep = MD.getDependency(BBI, dep);
134           continue;
135         }
136         
137         // Remove it!
138         MD.removeInstruction(last);
139           
140         // DCE instructions only used to calculate that store
141         if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
142           possiblyDead.insert(D);
143         if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
144           possiblyDead.insert(D);
145           
146         last->eraseFromParent();
147         NumFastStores++;
148         deletedStore = true;
149         MadeChange = true;
150           
151         break;
152       }
153     }
154     
155     // Handle frees whose dependencies are non-trivial.
156     if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
157       if (!deletedStore)
158         MadeChange |= handleFreeWithNonTrivialDependency(F,
159                                                          MD.getDependency(F),
160                                                          possiblyDead);
161       // No known stores after the free
162       last = 0;
163     } else {
164       // Update our most-recent-store map.
165       last = cast<StoreInst>(BBI);
166     }
167   }
168   
169   // If this block ends in a return, unwind, unreachable, and eventually
170   // tailcall, then all allocas are dead at its end.
171   if (BB.getTerminator()->getNumSuccessors() == 0)
172     MadeChange |= handleEndBlock(BB, possiblyDead);
173   
174   // Do a trivial DCE
175   while (!possiblyDead.empty()) {
176     Instruction *I = possiblyDead.back();
177     possiblyDead.pop_back();
178     DeleteDeadInstructionChains(I, possiblyDead);
179   }
180   
181   return MadeChange;
182 }
183
184 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
185 /// dependency is a store to a field of that structure
186 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
187                                        SetVector<Instruction*>& possiblyDead) {
188   TargetData &TD = getAnalysis<TargetData>();
189   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
190   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
191   
192   if (dep == MemoryDependenceAnalysis::None ||
193       dep == MemoryDependenceAnalysis::NonLocal)
194     return false;
195   
196   StoreInst* dependency = dyn_cast<StoreInst>(dep);
197   if (!dependency)
198     return false;
199   
200   Value* depPointer = dependency->getPointerOperand();
201   const Type* depType = dependency->getOperand(0)->getType();
202   unsigned depPointerSize = TD.getTypeSize(depType);
203   
204   // Check for aliasing
205   AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
206                                           depPointer, depPointerSize);
207     
208   if (A == AliasAnalysis::MustAlias) {
209     // Remove it!
210     MD.removeInstruction(dependency);
211
212     // DCE instructions only used to calculate that store
213     if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
214       possiblyDead.insert(D);
215     if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
216       possiblyDead.insert(D);
217
218     dependency->eraseFromParent();
219     NumFastStores++;
220     return true;
221   }
222   
223   return false;
224 }
225
226 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
227 /// function end block
228 bool DSE::handleEndBlock(BasicBlock& BB,
229                          SetVector<Instruction*>& possiblyDead) {
230   TargetData &TD = getAnalysis<TargetData>();
231   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
232   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
233   
234   bool MadeChange = false;
235   
236   // Pointers alloca'd in this function are dead in the end block
237   SmallPtrSet<AllocaInst*, 4> deadPointers;
238   
239   // Find all of the alloca'd pointers in the entry block
240   BasicBlock *Entry = BB.getParent()->begin();
241   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
242     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
243       deadPointers.insert(AI);
244   
245   // Scan the basic block backwards
246   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
247     --BBI;
248     
249     if (deadPointers.empty())
250       break;
251     
252     Value* killPointer = 0;
253     unsigned killPointerSize = 0;
254     
255     // If we find a store whose pointer is dead...
256     if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
257       Value* pointerOperand = S->getPointerOperand();
258       // See through pointer-to-pointer bitcasts
259       TranslatePointerBitCasts(pointerOperand);
260       
261       if (deadPointers.count(pointerOperand)){
262         // Remove it!
263         MD.removeInstruction(S);
264         
265         // DCE instructions only used to calculate that store
266         if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
267           possiblyDead.insert(D);
268         if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
269           possiblyDead.insert(D);
270         
271         BBI++;
272         S->eraseFromParent();
273         NumFastStores++;
274         MadeChange = true;
275       }
276     
277     // If we encounter a use of the pointer, it is no longer considered dead
278     } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
279       killPointer = L->getPointerOperand();
280       killPointerSize = TD.getTypeSize(L->getType());
281     } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
282       killPointer = V->getOperand(0);
283       killPointerSize = TD.getTypeSize(V->getType());
284     } else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
285       killPointer = F->getPointerOperand();
286       killPointerSize = ~0UL;
287     } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
288       deadPointers.erase(A);
289       continue;
290     } else if (CallSite::get(BBI).getInstruction() != 0) {
291       // Remove any pointers made undead by the call from the dead set
292       std::vector<Instruction*> dead;
293       for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
294            E = deadPointers.end(); I != E; ++I) {
295         // Get size information for the alloca
296         unsigned pointerSize = ~0UL;
297         if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
298           pointerSize = C->getZExtValue() * \
299                         TD.getTypeSize((*I)->getAllocatedType());     
300         
301         // See if the call site touches it
302         AliasAnalysis::ModRefResult A = AA.getModRefInfo(CallSite::get(BBI),
303                                                          *I, pointerSize);
304         if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
305           dead.push_back(*I);
306       }
307
308       for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
309            I != E; ++I)
310         deadPointers.erase(*I);
311       
312       continue;
313     }
314     
315     if (!killPointer)
316       continue;
317     
318     // Deal with undead pointers
319     MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
320                                        deadPointers, possiblyDead);
321   }
322   
323   return MadeChange;
324 }
325
326 bool DSE::RemoveUndeadPointers(Value* killPointer, unsigned killPointerSize,
327                                 BasicBlock::iterator& BBI,
328                                 SmallPtrSet<AllocaInst*, 4>& deadPointers, 
329                                 SetVector<Instruction*>& possiblyDead) {
330   TargetData &TD = getAnalysis<TargetData>();
331   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
332   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
333                                   
334   bool MadeChange = false;
335   
336   std::vector<Instruction*> undead;
337     
338   for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
339       E = deadPointers.end(); I != E; ++I) {
340     // Get size information for the alloca
341     unsigned pointerSize = ~0UL;
342     if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
343       pointerSize = C->getZExtValue() * \
344                     TD.getTypeSize((*I)->getAllocatedType());     
345       
346     // See if this pointer could alias it
347     AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
348                                             killPointer, killPointerSize);
349
350     // If it must-alias and a store, we can delete it
351     if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
352       StoreInst* S = cast<StoreInst>(BBI);
353
354       // Remove it!
355       MD.removeInstruction(S);
356
357       // DCE instructions only used to calculate that store
358       if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
359         possiblyDead.insert(D);
360       if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
361         possiblyDead.insert(D);
362
363       BBI++;
364       S->eraseFromParent();
365       NumFastStores++;
366       MadeChange = true;
367
368       continue;
369
370       // Otherwise, it is undead
371       } else if (A != AliasAnalysis::NoAlias)
372         undead.push_back(*I);
373   }
374
375   for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
376        I != E; ++I)
377     deadPointers.erase(*I);
378   
379   return MadeChange;
380 }
381
382 void DSE::DeleteDeadInstructionChains(Instruction *I,
383                                       SetVector<Instruction*> &DeadInsts) {
384   // Instruction must be dead.
385   if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
386
387   // Let the memory dependence know
388   getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
389
390   // See if this made any operands dead.  We do it this way in case the
391   // instruction uses the same operand twice.  We don't want to delete a
392   // value then reference it.
393   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
394     if (I->getOperand(i)->hasOneUse())
395       if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
396         DeadInsts.insert(Op);      // Attempt to nuke it later.
397     
398     I->setOperand(i, 0);         // Drop from the operand list.
399   }
400
401   I->eraseFromParent();
402   ++NumFastOther;
403 }