Remove support for NOT instruction
[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     virtual bool runOnFunction(Function &F);
46
47     // Visitation methods, these are invoked depending on the type of
48     // instruction being checked.  They should return true if a common
49     // subexpression was folded.
50     //
51     bool visitBinaryOperator(Instruction &I);
52     bool visitGetElementPtrInst(GetElementPtrInst &I);
53     bool visitCastInst(CastInst &I);
54     bool visitShiftInst(ShiftInst &I) {
55       return visitBinaryOperator((Instruction&)I);
56     }
57     bool visitLoadInst(LoadInst &LI);
58     bool visitInstruction(Instruction &) { return false; }
59
60   private:
61     void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
62     void CommonSubExpressionFound(Instruction *I, Instruction *Other);
63
64     // TryToRemoveALoad - Try to remove one of L1 or L2.  The problem with
65     // removing loads is that intervening stores might make otherwise identical
66     // load's yield different values.  To ensure that this is not the case, we
67     // check that there are no intervening stores or calls between the
68     // instructions.
69     //
70     bool TryToRemoveALoad(LoadInst *L1, LoadInst *L2);
71
72     // CheckForInvalidatingInst - Return true if BB or any of the predecessors
73     // of BB (until DestBB) contain a store (or other invalidating) instruction.
74     //
75     bool CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
76                                   set<BasicBlock*> &VisitedSet);
77
78     // This transformation requires dominator and immediate dominator info
79     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80       AU.preservesCFG();
81       AU.addRequired<DominatorSet>();
82       AU.addRequired<ImmediateDominators>();
83     }
84   };
85
86   RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
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   Second.getParent()->getInstList().erase(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 = Second;
182
183     // Destroy Second, using First instead.
184     ReplaceInstWithInst(First, BI);    
185
186     // Otherwise, the two instructions are in different basic blocks.  If one
187     // dominates the other instruction, we can simply use it
188     //
189   } else if (DomSetInfo->dominates(BB1, BB2)) {    // I dom Other?
190     ReplaceInstWithInst(I, Other);
191   } else if (DomSetInfo->dominates(BB2, BB1)) {    // Other dom I?
192     ReplaceInstWithInst(Other, I);
193   } else {
194     // This code is disabled because it has several problems:
195     // One, the actual assumption is wrong, as shown by this code:
196     // int "test"(int %X, int %Y) {
197     //         %Z = add int %X, %Y
198     //         ret int %Z
199     // Unreachable:
200     //         %Q = add int %X, %Y
201     //         ret int %Q
202     // }
203     //
204     // Here there are no shared dominators.  Additionally, this had the habit of
205     // moving computations where they were not always computed.  For example, in
206     // a cast like this:
207     //  if (c) {
208     //    if (d)  ...
209     //    else ... X+Y ...
210     //  } else {
211     //    ... X+Y ...
212     //  }
213     // 
214     // In thiscase, the expression would be hoisted to outside the 'if' stmt,
215     // causing the expression to be evaluated, even for the if (d) path, which
216     // could cause problems, if, for example, it caused a divide by zero.  In
217     // general the problem this case is trying to solve is better addressed with
218     // PRE than GCSE.
219     //
220
221 #if 0
222     // Handle the most general case now.  In this case, neither I dom Other nor
223     // Other dom I.  Because we are in SSA form, we are guaranteed that the
224     // operands of the two instructions both dominate the uses, so we _know_
225     // that there must exist a block that dominates both instructions (if the
226     // operands of the instructions are globals or constants, worst case we
227     // would get the entry node of the function).  Search for this block now.
228     //
229
230     // Search up the immediate dominator chain of BB1 for the shared dominator
231     BasicBlock *SharedDom = (*ImmDominator)[BB1];
232     while (!DomSetInfo->dominates(SharedDom, BB2))
233       SharedDom = (*ImmDominator)[SharedDom];
234
235     // At this point, shared dom must dominate BOTH BB1 and BB2...
236     assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
237            DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
238
239     // Rip 'I' out of BB1, and move it to the end of SharedDom.
240     BB1->getInstList().remove(I);
241     SharedDom->getInstList().insert(--SharedDom->end(), I);
242
243     // Eliminate 'Other' now.
244     ReplaceInstWithInst(I, Other);
245 #endif
246   }
247 }
248
249 //===----------------------------------------------------------------------===//
250 //
251 // Visitation methods, these are invoked depending on the type of instruction
252 // being checked.  They should return true if a common subexpression was folded.
253 //
254 //===----------------------------------------------------------------------===//
255
256 bool GCSE::visitCastInst(CastInst &I) {
257   Value *Op = I.getOperand(0);
258   Function *F = I.getParent()->getParent();
259   
260   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
261        UI != UE; ++UI)
262     if (Instruction *Other = dyn_cast<Instruction>(*UI))
263       // Check to see if this new cast is not I, but has the same operand...
264       if (Other != &I && Other->getOpcode() == I.getOpcode() &&
265           Other->getOperand(0) == Op &&     // Is the operand the same?
266           // Is it embeded in the same function?  (This could be false if LHS
267           // is a constant or global!)
268           Other->getParent()->getParent() == F &&
269
270           // Check that the types are the same, since this code handles casts...
271           Other->getType() == I.getType()) {
272         
273         // These instructions are identical.  Handle the situation.
274         CommonSubExpressionFound(&I, Other);
275         return true;   // One instruction eliminated!
276       }
277   
278   return false;
279 }
280
281 // isIdenticalBinaryInst - Return true if the two binary instructions are
282 // identical.
283 //
284 static inline bool isIdenticalBinaryInst(const Instruction &I1,
285                                          const Instruction *I2) {
286   // Is it embeded in the same function?  (This could be false if LHS
287   // is a constant or global!)
288   if (I1.getOpcode() != I2->getOpcode() ||
289       I1.getParent()->getParent() != I2->getParent()->getParent())
290     return false;
291   
292   // They are identical if both operands are the same!
293   if (I1.getOperand(0) == I2->getOperand(0) &&
294       I1.getOperand(1) == I2->getOperand(1))
295     return true;
296   
297   // If the instruction is commutative and associative, the instruction can
298   // match if the operands are swapped!
299   //
300   if ((I1.getOperand(0) == I2->getOperand(1) &&
301        I1.getOperand(1) == I2->getOperand(0)) &&
302       (I1.getOpcode() == Instruction::Add || 
303        I1.getOpcode() == Instruction::Mul ||
304        I1.getOpcode() == Instruction::And || 
305        I1.getOpcode() == Instruction::Or  ||
306        I1.getOpcode() == Instruction::Xor))
307     return true;
308
309   return false;
310 }
311
312 bool GCSE::visitBinaryOperator(Instruction &I) {
313   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
314   Function *F = I.getParent()->getParent();
315   
316   for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
317        UI != UE; ++UI)
318     if (Instruction *Other = dyn_cast<Instruction>(*UI))
319       // Check to see if this new binary operator is not I, but same operand...
320       if (Other != &I && isIdenticalBinaryInst(I, Other)) {        
321         // These instructions are identical.  Handle the situation.
322         CommonSubExpressionFound(&I, Other);
323         return true;   // One instruction eliminated!
324       }
325   
326   return false;
327 }
328
329 // IdenticalComplexInst - Return true if the two instructions are the same, by
330 // using a brute force comparison.
331 //
332 static bool IdenticalComplexInst(const Instruction *I1, const Instruction *I2) {
333   assert(I1->getOpcode() == I2->getOpcode());
334   // Equal if they are in the same function...
335   return I1->getParent()->getParent() == I2->getParent()->getParent() &&
336     // And return the same type...
337     I1->getType() == I2->getType() &&
338     // And have the same number of operands...
339     I1->getNumOperands() == I2->getNumOperands() &&
340     // And all of the operands are equal.
341     std::equal(I1->op_begin(), I1->op_end(), I2->op_begin());
342 }
343
344 bool GCSE::visitGetElementPtrInst(GetElementPtrInst &I) {
345   Value *Op = I.getOperand(0);
346   Function *F = I.getParent()->getParent();
347   
348   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
349        UI != UE; ++UI)
350     if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
351       // Check to see if this new getelementptr is not I, but same operand...
352       if (Other != &I && IdenticalComplexInst(&I, Other)) {
353         // These instructions are identical.  Handle the situation.
354         CommonSubExpressionFound(&I, Other);
355         return true;   // One instruction eliminated!
356       }
357   
358   return false;
359 }
360
361 bool GCSE::visitLoadInst(LoadInst &LI) {
362   Value *Op = LI.getOperand(0);
363   Function *F = LI.getParent()->getParent();
364   
365   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
366        UI != UE; ++UI)
367     if (LoadInst *Other = dyn_cast<LoadInst>(*UI))
368       // Check to see if this new load is not LI, but has the same operands...
369       if (Other != &LI && IdenticalComplexInst(&LI, Other) &&
370           TryToRemoveALoad(&LI, Other))
371         return true;   // An instruction was eliminated!
372   
373   return false;
374 }
375
376 static inline bool isInvalidatingInst(const Instruction &I) {
377   return I.getOpcode() == Instruction::Store ||
378          I.getOpcode() == Instruction::Call ||
379          I.getOpcode() == Instruction::Invoke;
380 }
381
382 // TryToRemoveALoad - Try to remove one of L1 or L2.  The problem with removing
383 // loads is that intervening stores might make otherwise identical load's yield
384 // different values.  To ensure that this is not the case, we check that there
385 // are no intervening stores or calls between the instructions.
386 //
387 bool GCSE::TryToRemoveALoad(LoadInst *L1, LoadInst *L2) {
388   // Figure out which load dominates the other one.  If neither dominates the
389   // other we cannot eliminate one...
390   //
391   if (DomSetInfo->dominates(L2, L1)) 
392     std::swap(L1, L2);   // Make L1 dominate L2
393   else if (!DomSetInfo->dominates(L1, L2))
394     return false;  // Neither instruction dominates the other one...
395
396   BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
397
398   BasicBlock::iterator L1I = L1;
399
400   // L1 now dominates L2.  Check to see if the intervening instructions between
401   // the two loads include a store or call...
402   //
403   if (BB1 == BB2) {  // In same basic block?
404     // In this degenerate case, no checking of global basic blocks has to occur
405     // just check the instructions BETWEEN L1 & L2...
406     //
407     for (++L1I; &*L1I != L2; ++L1I)
408       if (isInvalidatingInst(*L1I))
409         return false;   // Cannot eliminate load
410
411     ++NumLoadRemoved;
412     CommonSubExpressionFound(L1, L2);
413     return true;
414   } else {
415     // Make sure that there are no store instructions between L1 and the end of
416     // it's basic block...
417     //
418     for (++L1I; L1I != BB1->end(); ++L1I)
419       if (isInvalidatingInst(*L1I)) {
420         BBContainsStore[BB1] = true;
421         return false;   // Cannot eliminate load
422       }
423
424     // Make sure that there are no store instructions between the start of BB2
425     // and the second load instruction...
426     //
427     for (BasicBlock::iterator II = BB2->begin(); &*II != L2; ++II)
428       if (isInvalidatingInst(*II)) {
429         BBContainsStore[BB2] = true;
430         return false;   // Cannot eliminate load
431       }
432
433     // Do a depth first traversal of the inverse CFG starting at L2's block,
434     // looking for L1's block.  The inverse CFG is made up of the predecessor
435     // nodes of a block... so all of the edges in the graph are "backward".
436     //
437     set<BasicBlock*> VisitedSet;
438     for (pred_iterator PI = pred_begin(BB2), PE = pred_end(BB2); PI != PE; ++PI)
439       if (CheckForInvalidatingInst(*PI, BB1, VisitedSet))
440         return false;
441     
442     ++NumLoadRemoved;
443     CommonSubExpressionFound(L1, L2);
444     return true;
445   }
446   return false;
447 }
448
449 // CheckForInvalidatingInst - Return true if BB or any of the predecessors of BB
450 // (until DestBB) contain a store (or other invalidating) instruction.
451 //
452 bool GCSE::CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
453                                     set<BasicBlock*> &VisitedSet) {
454   // Found the termination point!
455   if (BB == DestBB || VisitedSet.count(BB)) return false;
456
457   // Avoid infinite recursion!
458   VisitedSet.insert(BB);
459
460   // Have we already checked this block?
461   map<BasicBlock*, bool>::iterator MI = BBContainsStore.find(BB);
462   
463   if (MI != BBContainsStore.end()) {
464     // If this block is known to contain a store, exit the recursion early...
465     if (MI->second) return true;
466     // Otherwise continue checking predecessors...
467   } else {
468     // We don't know if this basic block contains an invalidating instruction.
469     // Check now:
470     bool HasStore = std::find_if(BB->begin(), BB->end(),
471                                  isInvalidatingInst) != BB->end();
472     if ((BBContainsStore[BB] = HasStore))   // Update map
473       return true;   // Exit recursion early...
474   }
475
476   // Check all of our predecessor blocks...
477   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
478     if (CheckForInvalidatingInst(*PI, DestBB, VisitedSet))
479       return true;
480
481   // None of our predecessor blocks contain a store, and we don't either!
482   return false;
483 }