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.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"
30 static Statistic<> NumInstRemoved("gcse\t\t- Number of instructions removed");
31 static Statistic<> NumLoadRemoved("gcse\t\t- Number of loads removed");
34 class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
35 set<Instruction*> WorkList;
36 DominatorSet *DomSetInfo;
37 ImmediateDominators *ImmDominator;
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.
43 map<BasicBlock*, bool> BBContainsStore;
45 const char *getPassName() const {
46 return "Global Common Subexpression Elimination";
49 virtual bool runOnFunction(Function &F);
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.
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);
62 bool visitLoadInst(LoadInst &LI);
63 bool visitInstruction(Instruction &) { return false; }
66 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
67 void CommonSubExpressionFound(Instruction *I, Instruction *Other);
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
75 bool TryToRemoveALoad(LoadInst *L1, LoadInst *L2);
77 // CheckForInvalidatingInst - Return true if BB or any of the predecessors
78 // of BB (until DestBB) contain a store (or other invalidating) instruction.
80 bool CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
81 set<BasicBlock*> &VisitedSet);
83 // This transformation requires dominator and immediate dominator info
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired(DominatorSet::ID);
87 AU.addRequired(ImmediateDominators::ID);
92 // createGCSEPass - The public interface to this file...
93 Pass *createGCSEPass() { return new GCSE(); }
96 // GCSE::runOnFunction - This is the main transformation entry point for a
99 bool GCSE::runOnFunction(Function &F) {
100 bool Changed = false;
102 DomSetInfo = &getAnalysis<DominatorSet>();
103 ImmDominator = &getAnalysis<ImmediateDominators>();
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.
109 WorkList.insert(inst_begin(F), inst_end(F));
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!
115 while (!WorkList.empty()) {
116 Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
117 WorkList.erase(WorkList.begin());
119 // Visit the instruction, dispatching to the correct visit function based on
120 // the instruction type. This does the checking.
125 // Clear out data structure so that next function starts fresh
126 BBContainsStore.clear();
128 // When the worklist is empty, return whether or not we changed anything...
133 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
134 // uses of the instruction use First now instead.
136 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
137 Instruction &Second = *SI;
139 //cerr << "DEL " << (void*)Second << Second;
141 // Add the first instruction back to the worklist
142 WorkList.insert(First);
144 // Add all uses of the second instruction to the worklist
145 for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
147 WorkList.insert(cast<Instruction>(*UI));
149 // Make all users of 'Second' now use 'First'
150 Second.replaceAllUsesWith(First);
152 // Erase the second instruction from the program
153 Second.getParent()->getInstList().erase(SI);
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.
160 void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
164 WorkList.erase(Other); // Other may not actually be on the worklist anymore...
166 ++NumInstRemoved; // Keep track of number of instructions eliminated
168 // Handle the easy case, where both instructions are in the same basic block
169 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
171 // Eliminate the second occuring instruction. Add all uses of the second
172 // instruction to the worklist.
174 // Scan the basic block looking for the "first" instruction
175 BasicBlock::iterator BI = BB1->begin();
176 while (&*BI != I && &*BI != Other) {
178 assert(BI != BB1->end() && "Instructions not found in parent BB!");
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
186 // Destroy Second, using First instead.
187 ReplaceInstWithInst(First, BI);
189 // Otherwise, the two instructions are in different basic blocks. If one
190 // dominates the other instruction, we can simply use it
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);
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.
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];
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!");
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);
218 // Eliminate 'Other' now.
219 ReplaceInstWithInst(I, Other);
223 //===----------------------------------------------------------------------===//
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.
228 //===----------------------------------------------------------------------===//
230 bool GCSE::visitUnaryOperator(Instruction &I) {
231 Value *Op = I.getOperand(0);
232 Function *F = I.getParent()->getParent();
234 for (Value::use_iterator UI = Op->use_begin(), UE = Op->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 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 &&
244 // Check that the types are the same, since this code handles casts...
245 Other->getType() == I.getType()) {
247 // These instructions are identical. Handle the situation.
248 CommonSubExpressionFound(&I, Other);
249 return true; // One instruction eliminated!
255 // isIdenticalBinaryInst - Return true if the two binary instructions are
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())
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))
271 // If the instruction is commutative and associative, the instruction can
272 // match if the operands are swapped!
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))
286 bool GCSE::visitBinaryOperator(Instruction &I) {
287 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
288 Function *F = I.getParent()->getParent();
290 for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
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!
303 // IdenticalComplexInst - Return true if the two instructions are the same, by
304 // using a brute force comparison.
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());
318 bool GCSE::visitGetElementPtrInst(GetElementPtrInst &I) {
319 Value *Op = I.getOperand(0);
320 Function *F = I.getParent()->getParent();
322 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
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!
335 bool GCSE::visitLoadInst(LoadInst &LI) {
336 Value *Op = LI.getOperand(0);
337 Function *F = LI.getParent()->getParent();
339 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
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!
350 static inline bool isInvalidatingInst(const Instruction &I) {
351 return I.getOpcode() == Instruction::Store ||
352 I.getOpcode() == Instruction::Call ||
353 I.getOpcode() == Instruction::Invoke;
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.
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...
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...
370 BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
372 BasicBlock::iterator L1I = L1;
374 // L1 now dominates L2. Check to see if the intervening instructions between
375 // the two loads include a store or call...
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...
381 for (++L1I; &*L1I != L2; ++L1I)
382 if (isInvalidatingInst(*L1I))
383 return false; // Cannot eliminate load
386 CommonSubExpressionFound(L1, L2);
389 // Make sure that there are no store instructions between L1 and the end of
390 // it's basic block...
392 for (++L1I; L1I != BB1->end(); ++L1I)
393 if (isInvalidatingInst(*L1I)) {
394 BBContainsStore[BB1] = true;
395 return false; // Cannot eliminate load
398 // Make sure that there are no store instructions between the start of BB2
399 // and the second load instruction...
401 for (BasicBlock::iterator II = BB2->begin(); &*II != L2; ++II)
402 if (isInvalidatingInst(*II)) {
403 BBContainsStore[BB2] = true;
404 return false; // Cannot eliminate load
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".
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))
417 CommonSubExpressionFound(L1, L2);
423 // CheckForInvalidatingInst - Return true if BB or any of the predecessors of BB
424 // (until DestBB) contain a store (or other invalidating) instruction.
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;
431 // Avoid infinite recursion!
432 VisitedSet.insert(BB);
434 // Have we already checked this block?
435 map<BasicBlock*, bool>::iterator MI = BBContainsStore.find(BB);
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...
442 // We don't know if this basic block contains an invalidating instruction.
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...
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))
455 // None of our predecessor blocks contain a store, and we don't either!