Avoid deleting individual instructions until AFTER dead blocks have dropped
[oota-llvm.git] / lib / Transforms / Scalar / GCSE.cpp
1 //===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
2 //
3 // This pass is designed to be a very quick global transformation that
4 // eliminates global common subexpressions from a function.  It does this by
5 // examining the SSA value graph of the function, instead of doing slow, dense,
6 // bit-vector computations.
7 //
8 // This pass works best if it is proceeded with a simple constant propogation
9 // pass and an instruction combination pass because this pass does not do any
10 // value numbering (in order to be speedy).
11 //
12 // This pass does not attempt to CSE load instructions, because it does not use
13 // pointer analysis to determine when it is safe.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/InstrTypes.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Support/InstVisitor.h"
22 #include "llvm/Support/InstIterator.h"
23 #include "llvm/Support/CFG.h"
24 #include "Support/StatisticReporter.h"
25 #include <algorithm>
26
27 static Statistic<> NumInstRemoved("gcse\t\t- Number of instructions removed");
28 static Statistic<> NumLoadRemoved("gcse\t\t- Number of loads removed");
29
30 namespace {
31   class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
32     set<Instruction*>       WorkList;
33     DominatorSet           *DomSetInfo;
34     ImmediateDominators    *ImmDominator;
35
36     // BBContainsStore - Contains a value that indicates whether a basic block
37     // has a store or call instruction in it.  This map is demand populated, so
38     // not having an entry means that the basic block has not been scanned yet.
39     //
40     map<BasicBlock*, bool>  BBContainsStore;
41   public:
42     const char *getPassName() const {
43       return "Global Common Subexpression Elimination";
44     }
45
46     virtual bool runOnFunction(Function *F);
47
48     // Visitation methods, these are invoked depending on the type of
49     // instruction being checked.  They should return true if a common
50     // subexpression was folded.
51     //
52     bool visitUnaryOperator(Instruction *I);
53     bool visitBinaryOperator(Instruction *I);
54     bool visitGetElementPtrInst(GetElementPtrInst *I);
55     bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
56     bool visitShiftInst(ShiftInst *I) {
57       return visitBinaryOperator((Instruction*)I);
58     }
59     bool visitLoadInst(LoadInst *LI);
60     bool visitInstruction(Instruction *) { return false; }
61
62   private:
63     void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
64     void CommonSubExpressionFound(Instruction *I, Instruction *Other);
65
66     // TryToRemoveALoad - Try to remove one of L1 or L2.  The problem with
67     // removing loads is that intervening stores might make otherwise identical
68     // load's yield different values.  To ensure that this is not the case, we
69     // check that there are no intervening stores or calls between the
70     // instructions.
71     //
72     bool TryToRemoveALoad(LoadInst *L1, LoadInst *L2);
73
74     // CheckForInvalidatingInst - Return true if BB or any of the predecessors
75     // of BB (until DestBB) contain a store (or other invalidating) instruction.
76     //
77     bool CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
78                                   set<BasicBlock*> &VisitedSet);
79
80     // This transformation requires dominator and immediate dominator info
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.preservesCFG();
83       AU.addRequired(DominatorSet::ID);
84       AU.addRequired(ImmediateDominators::ID); 
85     }
86   };
87 }
88
89 // createGCSEPass - The public interface to this file...
90 Pass *createGCSEPass() { return new GCSE(); }
91
92
93 // GCSE::runOnFunction - This is the main transformation entry point for a
94 // function.
95 //
96 bool GCSE::runOnFunction(Function *F) {
97   bool Changed = false;
98
99   DomSetInfo = &getAnalysis<DominatorSet>();
100   ImmDominator = &getAnalysis<ImmediateDominators>();
101
102   // Step #1: Add all instructions in the function to the worklist for
103   // processing.  All of the instructions are considered to be our
104   // subexpressions to eliminate if possible.
105   //
106   WorkList.insert(inst_begin(F), inst_end(F));
107
108   // Step #2: WorkList processing.  Iterate through all of the instructions,
109   // checking to see if there are any additionally defined subexpressions in the
110   // program.  If so, eliminate them!
111   //
112   while (!WorkList.empty()) {
113     Instruction *I = *WorkList.begin();  // Get an instruction from the worklist
114     WorkList.erase(WorkList.begin());
115
116     // Visit the instruction, dispatching to the correct visit function based on
117     // the instruction type.  This does the checking.
118     //
119     Changed |= visit(I);
120   }
121
122   // Clear out data structure so that next function starts fresh
123   BBContainsStore.clear();
124   
125   // When the worklist is empty, return whether or not we changed anything...
126   return Changed;
127 }
128
129
130 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
131 // uses of the instruction use First now instead.
132 //
133 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
134   Instruction *Second = *SI;
135   
136   //cerr << "DEL " << (void*)Second << Second;
137
138   // Add the first instruction back to the worklist
139   WorkList.insert(First);
140
141   // Add all uses of the second instruction to the worklist
142   for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
143        UI != UE; ++UI)
144     WorkList.insert(cast<Instruction>(*UI));
145     
146   // Make all users of 'Second' now use 'First'
147   Second->replaceAllUsesWith(First);
148
149   // Erase the second instruction from the program
150   delete Second->getParent()->getInstList().remove(SI);
151 }
152
153 // CommonSubExpressionFound - The two instruction I & Other have been found to
154 // be common subexpressions.  This function is responsible for eliminating one
155 // of them, and for fixing the worklist to be correct.
156 //
157 void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
158   assert(I != Other);
159
160   WorkList.erase(I);
161   WorkList.erase(Other); // Other may not actually be on the worklist anymore...
162
163   ++NumInstRemoved;   // Keep track of number of instructions eliminated
164
165   // Handle the easy case, where both instructions are in the same basic block
166   BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
167   if (BB1 == BB2) {
168     // Eliminate the second occuring instruction.  Add all uses of the second
169     // instruction to the worklist.
170     //
171     // Scan the basic block looking for the "first" instruction
172     BasicBlock::iterator BI = BB1->begin();
173     while (*BI != I && *BI != Other) {
174       ++BI;
175       assert(BI != BB1->end() && "Instructions not found in parent BB!");
176     }
177
178     // Keep track of which instructions occurred first & second
179     Instruction *First = *BI;
180     Instruction *Second = I != First ? I : Other; // Get iterator to second inst
181     BI = find(BI, BB1->end(), Second);
182     assert(BI != BB1->end() && "Second instruction not found in parent block!");
183
184     // Destroy Second, using First instead.
185     ReplaceInstWithInst(First, BI);    
186
187     // Otherwise, the two instructions are in different basic blocks.  If one
188     // dominates the other instruction, we can simply use it
189     //
190   } else if (DomSetInfo->dominates(BB1, BB2)) {    // I dom Other?
191     BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
192     assert(BI != BB2->end() && "Other not in parent basic block!");
193     ReplaceInstWithInst(I, BI);    
194   } else if (DomSetInfo->dominates(BB2, BB1)) {    // Other dom I?
195     BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
196     assert(BI != BB1->end() && "I not in parent basic block!");
197     ReplaceInstWithInst(Other, BI);
198   } else {
199     // Handle the most general case now.  In this case, neither I dom Other nor
200     // Other dom I.  Because we are in SSA form, we are guaranteed that the
201     // operands of the two instructions both dominate the uses, so we _know_
202     // that there must exist a block that dominates both instructions (if the
203     // operands of the instructions are globals or constants, worst case we
204     // would get the entry node of the function).  Search for this block now.
205     //
206
207     // Search up the immediate dominator chain of BB1 for the shared dominator
208     BasicBlock *SharedDom = (*ImmDominator)[BB1];
209     while (!DomSetInfo->dominates(SharedDom, BB2))
210       SharedDom = (*ImmDominator)[SharedDom];
211
212     // At this point, shared dom must dominate BOTH BB1 and BB2...
213     assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
214            DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
215
216     // Rip 'I' out of BB1, and move it to the end of SharedDom.
217     BB1->getInstList().remove(I);
218     SharedDom->getInstList().insert(SharedDom->end()-1, I);
219
220     // Eliminate 'Other' now.
221     BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
222     assert(BI != BB2->end() && "I not in parent basic block!");
223     ReplaceInstWithInst(I, BI);
224   }
225 }
226
227 //===----------------------------------------------------------------------===//
228 //
229 // Visitation methods, these are invoked depending on the type of instruction
230 // being checked.  They should return true if a common subexpression was folded.
231 //
232 //===----------------------------------------------------------------------===//
233
234 bool GCSE::visitUnaryOperator(Instruction *I) {
235   Value *Op = I->getOperand(0);
236   Function *F = I->getParent()->getParent();
237   
238   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
239        UI != UE; ++UI)
240     if (Instruction *Other = dyn_cast<Instruction>(*UI))
241       // Check to see if this new binary operator is not I, but same operand...
242       if (Other != I && Other->getOpcode() == I->getOpcode() &&
243           Other->getOperand(0) == Op &&     // Is the operand the same?
244           // Is it embeded in the same function?  (This could be false if LHS
245           // is a constant or global!)
246           Other->getParent()->getParent() == F &&
247
248           // Check that the types are the same, since this code handles casts...
249           Other->getType() == I->getType()) {
250         
251         // These instructions are identical.  Handle the situation.
252         CommonSubExpressionFound(I, Other);
253         return true;   // One instruction eliminated!
254       }
255   
256   return false;
257 }
258
259 // isIdenticalBinaryInst - Return true if the two binary instructions are
260 // identical.
261 //
262 static inline bool isIdenticalBinaryInst(const Instruction *I1,
263                                          const Instruction *I2) {
264   // Is it embeded in the same function?  (This could be false if LHS
265   // is a constant or global!)
266   if (I1->getOpcode() != I2->getOpcode() ||
267       I1->getParent()->getParent() != I2->getParent()->getParent())
268     return false;
269   
270   // They are identical if both operands are the same!
271   if (I1->getOperand(0) == I2->getOperand(0) &&
272       I1->getOperand(1) == I2->getOperand(1))
273     return true;
274   
275   // If the instruction is commutative and associative, the instruction can
276   // match if the operands are swapped!
277   //
278   if ((I1->getOperand(0) == I2->getOperand(1) &&
279        I1->getOperand(1) == I2->getOperand(0)) &&
280       (I1->getOpcode() == Instruction::Add || 
281        I1->getOpcode() == Instruction::Mul ||
282        I1->getOpcode() == Instruction::And || 
283        I1->getOpcode() == Instruction::Or  ||
284        I1->getOpcode() == Instruction::Xor))
285     return true;
286
287   return false;
288 }
289
290 bool GCSE::visitBinaryOperator(Instruction *I) {
291   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
292   Function *F = I->getParent()->getParent();
293   
294   for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
295        UI != UE; ++UI)
296     if (Instruction *Other = dyn_cast<Instruction>(*UI))
297       // Check to see if this new binary operator is not I, but same operand...
298       if (Other != I && isIdenticalBinaryInst(I, Other)) {        
299         // These instructions are identical.  Handle the situation.
300         CommonSubExpressionFound(I, Other);
301         return true;   // One instruction eliminated!
302       }
303   
304   return false;
305 }
306
307 // IdenticalComplexInst - Return true if the two instructions are the same, by
308 // using a brute force comparison.
309 //
310 static bool IdenticalComplexInst(const Instruction *I1, const Instruction *I2) {
311   assert(I1->getOpcode() == I2->getOpcode());
312   // Equal if they are in the same function...
313   return I1->getParent()->getParent() == I2->getParent()->getParent() &&
314     // And return the same type...
315     I1->getType() == I2->getType() &&
316     // And have the same number of operands...
317     I1->getNumOperands() == I2->getNumOperands() &&
318     // And all of the operands are equal.
319     std::equal(I1->op_begin(), I1->op_end(), I2->op_begin());
320 }
321
322 bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
323   Value *Op = I->getOperand(0);
324   Function *F = I->getParent()->getParent();
325   
326   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
327        UI != UE; ++UI)
328     if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
329       // Check to see if this new getelementptr is not I, but same operand...
330       if (Other != I && IdenticalComplexInst(I, Other)) {
331         // These instructions are identical.  Handle the situation.
332         CommonSubExpressionFound(I, Other);
333         return true;   // One instruction eliminated!
334       }
335   
336   return false;
337 }
338
339 bool GCSE::visitLoadInst(LoadInst *LI) {
340   Value *Op = LI->getOperand(0);
341   Function *F = LI->getParent()->getParent();
342   
343   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
344        UI != UE; ++UI)
345     if (LoadInst *Other = dyn_cast<LoadInst>(*UI))
346       // Check to see if this new load is not LI, but has the same operands...
347       if (Other != LI && IdenticalComplexInst(LI, Other) &&
348           TryToRemoveALoad(LI, Other))
349         return true;   // An instruction was eliminated!
350   
351   return false;
352 }
353
354 static inline bool isInvalidatingInst(const Instruction *I) {
355   return I->getOpcode() == Instruction::Store ||
356          I->getOpcode() == Instruction::Call ||
357          I->getOpcode() == Instruction::Invoke;
358 }
359
360 // TryToRemoveALoad - Try to remove one of L1 or L2.  The problem with removing
361 // loads is that intervening stores might make otherwise identical load's yield
362 // different values.  To ensure that this is not the case, we check that there
363 // are no intervening stores or calls between the instructions.
364 //
365 bool GCSE::TryToRemoveALoad(LoadInst *L1, LoadInst *L2) {
366   // Figure out which load dominates the other one.  If neither dominates the
367   // other we cannot eliminate one...
368   //
369   if (DomSetInfo->dominates(L2, L1)) 
370     std::swap(L1, L2);   // Make L1 dominate L2
371   else if (!DomSetInfo->dominates(L1, L2))
372     return false;  // Neither instruction dominates the other one...
373
374   BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
375
376   // FIXME: This is incredibly painful with broken rep
377   BasicBlock::iterator L1I = std::find(BB1->begin(), BB1->end(), L1);
378   assert(L1I != BB1->end() && "Inst not in own parent?");
379
380   // L1 now dominates L2.  Check to see if the intervening instructions between
381   // the two loads include a store or call...
382   //
383   if (BB1 == BB2) {  // In same basic block?
384     // In this degenerate case, no checking of global basic blocks has to occur
385     // just check the instructions BETWEEN L1 & L2...
386     //
387     for (++L1I; *L1I != L2; ++L1I)
388       if (isInvalidatingInst(*L1I))
389         return false;   // Cannot eliminate load
390
391     ++NumLoadRemoved;
392     CommonSubExpressionFound(L1, L2);
393     return true;
394   } else {
395     // Make sure that there are no store instructions between L1 and the end of
396     // it's basic block...
397     //
398     for (++L1I; L1I != BB1->end(); ++L1I)
399       if (isInvalidatingInst(*L1I)) {
400         BBContainsStore[BB1] = true;
401         return false;   // Cannot eliminate load
402       }
403
404     // Make sure that there are no store instructions between the start of BB2
405     // and the second load instruction...
406     //
407     for (BasicBlock::iterator II = BB2->begin(); *II != L2; ++II)
408       if (isInvalidatingInst(*II)) {
409         BBContainsStore[BB2] = true;
410         return false;   // Cannot eliminate load
411       }
412
413     // Do a depth first traversal of the inverse CFG starting at L2's block,
414     // looking for L1's block.  The inverse CFG is made up of the predecessor
415     // nodes of a block... so all of the edges in the graph are "backward".
416     //
417     set<BasicBlock*> VisitedSet;
418     for (pred_iterator PI = pred_begin(BB2), PE = pred_end(BB2); PI != PE; ++PI)
419       if (CheckForInvalidatingInst(*PI, BB1, VisitedSet))
420         return false;
421     
422     ++NumLoadRemoved;
423     CommonSubExpressionFound(L1, L2);
424     return true;
425   }
426   return false;
427 }
428
429 // CheckForInvalidatingInst - Return true if BB or any of the predecessors of BB
430 // (until DestBB) contain a store (or other invalidating) instruction.
431 //
432 bool GCSE::CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
433                                     set<BasicBlock*> &VisitedSet) {
434   // Found the termination point!
435   if (BB == DestBB || VisitedSet.count(BB)) return false;
436
437   // Avoid infinite recursion!
438   VisitedSet.insert(BB);
439
440   // Have we already checked this block?
441   map<BasicBlock*, bool>::iterator MI = BBContainsStore.find(BB);
442   
443   if (MI != BBContainsStore.end()) {
444     // If this block is known to contain a store, exit the recursion early...
445     if (MI->second) return true;
446     // Otherwise continue checking predecessors...
447   } else {
448     // We don't know if this basic block contains an invalidating instruction.
449     // Check now:
450     bool HasStore = std::find_if(BB->begin(), BB->end(),
451                                  isInvalidatingInst) != BB->end();
452     if ((BBContainsStore[BB] = HasStore))   // Update map
453       return true;   // Exit recursion early...
454   }
455
456   // Check all of our predecessor blocks...
457   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
458     if (CheckForInvalidatingInst(*PI, DestBB, VisitedSet))
459       return true;
460
461   // None of our predecessor blocks contain a store, and we don't either!
462   return false;
463 }