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 virtual bool runOnFunction(Function *F);
35 // Visitation methods, these are invoked depending on the type of
36 // instruction being checked. They should return true if a common
37 // subexpression was folded.
39 bool visitUnaryOperator(Instruction *I);
40 bool visitBinaryOperator(Instruction *I);
41 bool visitGetElementPtrInst(GetElementPtrInst *I);
42 bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
43 bool visitShiftInst(ShiftInst *I) {
44 return visitBinaryOperator((Instruction*)I);
46 bool visitInstruction(Instruction *) { return false; }
49 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
50 void CommonSubExpressionFound(Instruction *I, Instruction *Other);
52 // This transformation requires dominator and immediate dominator info
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.addRequired(DominatorSet::ID);
56 AU.addRequired(ImmediateDominators::ID);
61 // createGCSEPass - The public interface to this file...
62 Pass *createGCSEPass() { return new GCSE(); }
65 // GCSE::runOnFunction - This is the main transformation entry point for a
68 bool GCSE::runOnFunction(Function *F) {
71 DomSetInfo = &getAnalysis<DominatorSet>();
72 ImmDominator = &getAnalysis<ImmediateDominators>();
74 // Step #1: Add all instructions in the function to the worklist for
75 // processing. All of the instructions are considered to be our
76 // subexpressions to eliminate if possible.
78 WorkList.insert(inst_begin(F), inst_end(F));
80 // Step #2: WorkList processing. Iterate through all of the instructions,
81 // checking to see if there are any additionally defined subexpressions in the
82 // program. If so, eliminate them!
84 while (!WorkList.empty()) {
85 Instruction *I = *WorkList.begin(); // Get an instruction from the worklist
86 WorkList.erase(WorkList.begin());
88 // Visit the instruction, dispatching to the correct visit function based on
89 // the instruction type. This does the checking.
94 // When the worklist is empty, return whether or not we changed anything...
99 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
100 // uses of the instruction use First now instead.
102 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
103 Instruction *Second = *SI;
105 // Add the first instruction back to the worklist
106 WorkList.insert(First);
108 // Add all uses of the second instruction to the worklist
109 for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
111 WorkList.insert(cast<Instruction>(*UI));
113 // Make all users of 'Second' now use 'First'
114 Second->replaceAllUsesWith(First);
116 // Erase the second instruction from the program
117 delete Second->getParent()->getInstList().remove(SI);
120 // CommonSubExpressionFound - The two instruction I & Other have been found to
121 // be common subexpressions. This function is responsible for eliminating one
122 // of them, and for fixing the worklist to be correct.
124 void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
125 // I has already been removed from the worklist, Other needs to be.
126 assert(WorkList.count(I) == 0 && WorkList.count(Other) &&
127 "I in worklist or Other not!");
128 WorkList.erase(Other);
130 // Handle the easy case, where both instructions are in the same basic block
131 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
133 // Eliminate the second occuring instruction. Add all uses of the second
134 // instruction to the worklist.
136 // Scan the basic block looking for the "first" instruction
137 BasicBlock::iterator BI = BB1->begin();
138 while (*BI != I && *BI != Other) {
140 assert(BI != BB1->end() && "Instructions not found in parent BB!");
143 // Keep track of which instructions occurred first & second
144 Instruction *First = *BI;
145 Instruction *Second = I != First ? I : Other; // Get iterator to second inst
146 BI = find(BI, BB1->end(), Second);
147 assert(BI != BB1->end() && "Second instruction not found in parent block!");
149 // Destroy Second, using First instead.
150 ReplaceInstWithInst(First, BI);
152 // Otherwise, the two instructions are in different basic blocks. If one
153 // dominates the other instruction, we can simply use it
155 } else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
156 BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
157 assert(BI != BB2->end() && "Other not in parent basic block!");
158 ReplaceInstWithInst(I, BI);
159 } else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
160 BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
161 assert(BI != BB1->end() && "I not in parent basic block!");
162 ReplaceInstWithInst(Other, BI);
164 // Handle the most general case now. In this case, neither I dom Other nor
165 // Other dom I. Because we are in SSA form, we are guaranteed that the
166 // operands of the two instructions both dominate the uses, so we _know_
167 // that there must exist a block that dominates both instructions (if the
168 // operands of the instructions are globals or constants, worst case we
169 // would get the entry node of the function). Search for this block now.
172 // Search up the immediate dominator chain of BB1 for the shared dominator
173 BasicBlock *SharedDom = (*ImmDominator)[BB1];
174 while (!DomSetInfo->dominates(SharedDom, BB2))
175 SharedDom = (*ImmDominator)[SharedDom];
177 // At this point, shared dom must dominate BOTH BB1 and BB2...
178 assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
179 DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
181 // Rip 'I' out of BB1, and move it to the end of SharedDom.
182 BB1->getInstList().remove(I);
183 SharedDom->getInstList().insert(SharedDom->end()-1, I);
185 // Eliminate 'Other' now.
186 BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
187 assert(BI != BB2->end() && "I not in parent basic block!");
188 ReplaceInstWithInst(I, BI);
192 //===----------------------------------------------------------------------===//
194 // Visitation methods, these are invoked depending on the type of instruction
195 // being checked. They should return true if a common subexpression was folded.
197 //===----------------------------------------------------------------------===//
199 bool GCSE::visitUnaryOperator(Instruction *I) {
200 Value *Op = I->getOperand(0);
201 Function *F = I->getParent()->getParent();
203 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
205 if (Instruction *Other = dyn_cast<Instruction>(*UI))
206 // Check to see if this new binary operator is not I, but same operand...
207 if (Other != I && Other->getOpcode() == I->getOpcode() &&
208 Other->getOperand(0) == Op && // Is the operand the same?
209 // Is it embeded in the same function? (This could be false if LHS
210 // is a constant or global!)
211 Other->getParent()->getParent() == F &&
213 // Check that the types are the same, since this code handles casts...
214 Other->getType() == I->getType()) {
216 // These instructions are identical. Handle the situation.
217 CommonSubExpressionFound(I, Other);
218 return true; // One instruction eliminated!
224 bool GCSE::visitBinaryOperator(Instruction *I) {
225 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
226 Function *F = I->getParent()->getParent();
228 for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
230 if (Instruction *Other = dyn_cast<Instruction>(*UI))
231 // Check to see if this new binary operator is not I, but same operand...
232 if (Other != I && Other->getOpcode() == I->getOpcode() &&
233 // Are the LHS and RHS the same?
234 Other->getOperand(0) == LHS && Other->getOperand(1) == RHS &&
235 // Is it embeded in the same function? (This could be false if LHS
236 // is a constant or global!)
237 Other->getParent()->getParent() == F) {
239 // These instructions are identical. Handle the situation.
240 CommonSubExpressionFound(I, Other);
241 return true; // One instruction eliminated!
247 bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
248 Value *Op = I->getOperand(0);
249 Function *F = I->getParent()->getParent();
251 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
253 if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
254 // Check to see if this new binary operator is not I, but same operand...
255 if (Other != I && Other->getParent()->getParent() == F &&
256 Other->getType() == I->getType()) {
258 // Check to see that all operators past the 0th are the same...
259 unsigned i = 1, e = I->getNumOperands();
261 if (I->getOperand(i) != Other->getOperand(i)) break;
264 // These instructions are identical. Handle the situation.
265 CommonSubExpressionFound(I, Other);
266 return true; // One instruction eliminated!