Remove broken assertion.
[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/GCSE.h"
18 #include "llvm/Pass.h"
19 #include "llvm/InstrTypes.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Support/InstIterator.h"
24 #include <set>
25 #include <algorithm>
26
27 namespace {
28   class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
29     set<Instruction*> WorkList;
30     DominatorSet        *DomSetInfo;
31     ImmediateDominators *ImmDominator;
32   public:
33     const char *getPassName() const {
34       return "Global Common Subexpression Elimination";
35     }
36
37     virtual bool runOnFunction(Function *F);
38
39     // Visitation methods, these are invoked depending on the type of
40     // instruction being checked.  They should return true if a common
41     // subexpression was folded.
42     //
43     bool visitUnaryOperator(Instruction *I);
44     bool visitBinaryOperator(Instruction *I);
45     bool visitGetElementPtrInst(GetElementPtrInst *I);
46     bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
47     bool visitShiftInst(ShiftInst *I) {
48       return visitBinaryOperator((Instruction*)I);
49     }
50     bool visitInstruction(Instruction *) { return false; }
51
52   private:
53     void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
54     void CommonSubExpressionFound(Instruction *I, Instruction *Other);
55
56     // This transformation requires dominator and immediate dominator info
57     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58       AU.preservesCFG();
59       AU.addRequired(DominatorSet::ID);
60       AU.addRequired(ImmediateDominators::ID); 
61     }
62   };
63 }
64
65 // createGCSEPass - The public interface to this file...
66 Pass *createGCSEPass() { return new GCSE(); }
67
68
69 // GCSE::runOnFunction - This is the main transformation entry point for a
70 // function.
71 //
72 bool GCSE::runOnFunction(Function *F) {
73   bool Changed = false;
74
75   DomSetInfo = &getAnalysis<DominatorSet>();
76   ImmDominator = &getAnalysis<ImmediateDominators>();
77
78   // Step #1: Add all instructions in the function to the worklist for
79   // processing.  All of the instructions are considered to be our
80   // subexpressions to eliminate if possible.
81   //
82   WorkList.insert(inst_begin(F), inst_end(F));
83
84   // Step #2: WorkList processing.  Iterate through all of the instructions,
85   // checking to see if there are any additionally defined subexpressions in the
86   // program.  If so, eliminate them!
87   //
88   while (!WorkList.empty()) {
89     Instruction *I = *WorkList.begin();  // Get an instruction from the worklist
90     WorkList.erase(WorkList.begin());
91
92     // Visit the instruction, dispatching to the correct visit function based on
93     // the instruction type.  This does the checking.
94     //
95     Changed |= visit(I);
96   }
97   
98   // When the worklist is empty, return whether or not we changed anything...
99   return Changed;
100 }
101
102
103 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
104 // uses of the instruction use First now instead.
105 //
106 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
107   Instruction *Second = *SI;
108   
109   //cerr << "DEL " << (void*)Second << Second;
110
111   // Add the first instruction back to the worklist
112   WorkList.insert(First);
113
114   // Add all uses of the second instruction to the worklist
115   for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
116        UI != UE; ++UI)
117     WorkList.insert(cast<Instruction>(*UI));
118     
119   // Make all users of 'Second' now use 'First'
120   Second->replaceAllUsesWith(First);
121
122   // Erase the second instruction from the program
123   delete Second->getParent()->getInstList().remove(SI);
124 }
125
126 // CommonSubExpressionFound - The two instruction I & Other have been found to
127 // be common subexpressions.  This function is responsible for eliminating one
128 // of them, and for fixing the worklist to be correct.
129 //
130 void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
131   // I has already been removed from the worklist, Other needs to be.
132   assert(I != Other && WorkList.count(I) == 0 && "I shouldn't be on worklist!");
133
134   WorkList.erase(Other); // Other may not actually be on the worklist anymore...
135
136   // Handle the easy case, where both instructions are in the same basic block
137   BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
138   if (BB1 == BB2) {
139     // Eliminate the second occuring instruction.  Add all uses of the second
140     // instruction to the worklist.
141     //
142     // Scan the basic block looking for the "first" instruction
143     BasicBlock::iterator BI = BB1->begin();
144     while (*BI != I && *BI != Other) {
145       ++BI;
146       assert(BI != BB1->end() && "Instructions not found in parent BB!");
147     }
148
149     // Keep track of which instructions occurred first & second
150     Instruction *First = *BI;
151     Instruction *Second = I != First ? I : Other; // Get iterator to second inst
152     BI = find(BI, BB1->end(), Second);
153     assert(BI != BB1->end() && "Second instruction not found in parent block!");
154
155     // Destroy Second, using First instead.
156     ReplaceInstWithInst(First, BI);    
157
158     // Otherwise, the two instructions are in different basic blocks.  If one
159     // dominates the other instruction, we can simply use it
160     //
161   } else if (DomSetInfo->dominates(BB1, BB2)) {    // I dom Other?
162     BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
163     assert(BI != BB2->end() && "Other not in parent basic block!");
164     ReplaceInstWithInst(I, BI);    
165   } else if (DomSetInfo->dominates(BB2, BB1)) {    // Other dom I?
166     BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
167     assert(BI != BB1->end() && "I not in parent basic block!");
168     ReplaceInstWithInst(Other, BI);
169   } else {
170     // Handle the most general case now.  In this case, neither I dom Other nor
171     // Other dom I.  Because we are in SSA form, we are guaranteed that the
172     // operands of the two instructions both dominate the uses, so we _know_
173     // that there must exist a block that dominates both instructions (if the
174     // operands of the instructions are globals or constants, worst case we
175     // would get the entry node of the function).  Search for this block now.
176     //
177
178     // Search up the immediate dominator chain of BB1 for the shared dominator
179     BasicBlock *SharedDom = (*ImmDominator)[BB1];
180     while (!DomSetInfo->dominates(SharedDom, BB2))
181       SharedDom = (*ImmDominator)[SharedDom];
182
183     // At this point, shared dom must dominate BOTH BB1 and BB2...
184     assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
185            DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
186
187     // Rip 'I' out of BB1, and move it to the end of SharedDom.
188     BB1->getInstList().remove(I);
189     SharedDom->getInstList().insert(SharedDom->end()-1, I);
190
191     // Eliminate 'Other' now.
192     BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
193     assert(BI != BB2->end() && "I not in parent basic block!");
194     ReplaceInstWithInst(I, BI);
195   }
196 }
197
198 //===----------------------------------------------------------------------===//
199 //
200 // Visitation methods, these are invoked depending on the type of instruction
201 // being checked.  They should return true if a common subexpression was folded.
202 //
203 //===----------------------------------------------------------------------===//
204
205 bool GCSE::visitUnaryOperator(Instruction *I) {
206   Value *Op = I->getOperand(0);
207   Function *F = I->getParent()->getParent();
208   
209   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
210        UI != UE; ++UI)
211     if (Instruction *Other = dyn_cast<Instruction>(*UI))
212       // Check to see if this new binary operator is not I, but same operand...
213       if (Other != I && Other->getOpcode() == I->getOpcode() &&
214           Other->getOperand(0) == Op &&     // Is the operand the same?
215           // Is it embeded in the same function?  (This could be false if LHS
216           // is a constant or global!)
217           Other->getParent()->getParent() == F &&
218
219           // Check that the types are the same, since this code handles casts...
220           Other->getType() == I->getType()) {
221         
222         // These instructions are identical.  Handle the situation.
223         CommonSubExpressionFound(I, Other);
224         return true;   // One instruction eliminated!
225       }
226   
227   return false;
228 }
229
230 bool GCSE::visitBinaryOperator(Instruction *I) {
231   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
232   Function *F = I->getParent()->getParent();
233   
234   for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->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           // Are the LHS and RHS the same?
240           Other->getOperand(0) == LHS && Other->getOperand(1) == RHS &&
241           // Is it embeded in the same function?  (This could be false if LHS
242           // is a constant or global!)
243           Other->getParent()->getParent() == F) {
244         
245         // These instructions are identical.  Handle the situation.
246         CommonSubExpressionFound(I, Other);
247         return true;   // One instruction eliminated!
248       }
249   
250   return false;
251 }
252
253 bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
254   Value *Op = I->getOperand(0);
255   Function *F = I->getParent()->getParent();
256   
257   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
258        UI != UE; ++UI)
259     if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
260       // Check to see if this new binary operator is not I, but same operand...
261       if (Other != I && Other->getParent()->getParent() == F &&
262           Other->getType() == I->getType()) {
263
264         // Check to see that all operators past the 0th are the same...
265         unsigned i = 1, e = I->getNumOperands();
266         for (; i != e; ++i)
267           if (I->getOperand(i) != Other->getOperand(i)) break;
268         
269         if (i == e) {
270           // These instructions are identical.  Handle the situation.
271           CommonSubExpressionFound(I, Other);
272           return true;   // One instruction eliminated!
273         }
274       }
275   
276   return false;
277 }