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