1 //===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
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.
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).
12 // This pass does not attempt to CSE load instructions, because it does not use
13 // pointer analysis to determine when it is safe.
15 //===----------------------------------------------------------------------===//
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"
28 class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
29 set<Instruction*> WorkList;
30 DominatorSet *DomSetInfo;
31 ImmediateDominators *ImmDominator;
33 const char *getPassName() const {
34 return "Global Common Subexpression Elimination";
37 virtual bool runOnFunction(Function *F);
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.
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);
50 bool visitInstruction(Instruction *) { return false; }
53 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
54 void CommonSubExpressionFound(Instruction *I, Instruction *Other);
56 // This transformation requires dominator and immediate dominator info
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired(DominatorSet::ID);
60 AU.addRequired(ImmediateDominators::ID);
65 // createGCSEPass - The public interface to this file...
66 Pass *createGCSEPass() { return new GCSE(); }
69 // GCSE::runOnFunction - This is the main transformation entry point for a
72 bool GCSE::runOnFunction(Function *F) {
75 DomSetInfo = &getAnalysis<DominatorSet>();
76 ImmDominator = &getAnalysis<ImmediateDominators>();
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.
82 WorkList.insert(inst_begin(F), inst_end(F));
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!
88 while (!WorkList.empty()) {
89 Instruction *I = *WorkList.begin(); // Get an instruction from the worklist
90 WorkList.erase(WorkList.begin());
92 // Visit the instruction, dispatching to the correct visit function based on
93 // the instruction type. This does the checking.
98 // When the worklist is empty, return whether or not we changed anything...
103 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
104 // uses of the instruction use First now instead.
106 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
107 Instruction *Second = *SI;
109 //cerr << "DEL " << (void*)Second << Second;
111 // Add the first instruction back to the worklist
112 WorkList.insert(First);
114 // Add all uses of the second instruction to the worklist
115 for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
117 WorkList.insert(cast<Instruction>(*UI));
119 // Make all users of 'Second' now use 'First'
120 Second->replaceAllUsesWith(First);
122 // Erase the second instruction from the program
123 delete Second->getParent()->getInstList().remove(SI);
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.
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!");
134 WorkList.erase(Other); // Other may not actually be on the worklist anymore...
136 // Handle the easy case, where both instructions are in the same basic block
137 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
139 // Eliminate the second occuring instruction. Add all uses of the second
140 // instruction to the worklist.
142 // Scan the basic block looking for the "first" instruction
143 BasicBlock::iterator BI = BB1->begin();
144 while (*BI != I && *BI != Other) {
146 assert(BI != BB1->end() && "Instructions not found in parent BB!");
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!");
155 // Destroy Second, using First instead.
156 ReplaceInstWithInst(First, BI);
158 // Otherwise, the two instructions are in different basic blocks. If one
159 // dominates the other instruction, we can simply use it
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);
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.
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];
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!");
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);
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);
198 //===----------------------------------------------------------------------===//
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.
203 //===----------------------------------------------------------------------===//
205 bool GCSE::visitUnaryOperator(Instruction *I) {
206 Value *Op = I->getOperand(0);
207 Function *F = I->getParent()->getParent();
209 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
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 &&
219 // Check that the types are the same, since this code handles casts...
220 Other->getType() == I->getType()) {
222 // These instructions are identical. Handle the situation.
223 CommonSubExpressionFound(I, Other);
224 return true; // One instruction eliminated!
230 bool GCSE::visitBinaryOperator(Instruction *I) {
231 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
232 Function *F = I->getParent()->getParent();
234 for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
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) {
245 // These instructions are identical. Handle the situation.
246 CommonSubExpressionFound(I, Other);
247 return true; // One instruction eliminated!
253 bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
254 Value *Op = I->getOperand(0);
255 Function *F = I->getParent()->getParent();
257 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
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()) {
264 // Check to see that all operators past the 0th are the same...
265 unsigned i = 1, e = I->getNumOperands();
267 if (I->getOperand(i) != Other->getOperand(i)) break;
270 // These instructions are identical. Handle the situation.
271 CommonSubExpressionFound(I, Other);
272 return true; // One instruction eliminated!