1 //===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is designed to be a very quick global transformation that
11 // eliminates global common subexpressions from a function. It does this by
12 // using an existing value numbering implementation to identify the common
13 // subexpressions, eliminating them when possible.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/iMemory.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Analysis/ValueNumbering.h"
22 #include "llvm/Support/InstIterator.h"
23 #include "Support/Statistic.h"
28 Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
29 Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
30 Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
31 "to non-instruction values");
33 class GCSE : public FunctionPass {
34 std::set<Instruction*> WorkList;
35 DominatorSet *DomSetInfo;
38 virtual bool runOnFunction(Function &F);
41 bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
42 Instruction *EliminateCSE(Instruction *I, Instruction *Other);
43 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
45 // This transformation requires dominator and immediate dominator info
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequired<DominatorSet>();
49 AU.addRequired<ImmediateDominators>();
50 AU.addRequired<ValueNumbering>();
54 RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
57 // createGCSEPass - The public interface to this file...
58 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
60 // GCSE::runOnFunction - This is the main transformation entry point for a
63 bool GCSE::runOnFunction(Function &F) {
66 // Get pointers to the analysis results that we will be using...
67 DomSetInfo = &getAnalysis<DominatorSet>();
68 VN = &getAnalysis<ValueNumbering>();
70 // Step #1: Add all instructions in the function to the worklist for
71 // processing. All of the instructions are considered to be our
72 // subexpressions to eliminate if possible.
74 WorkList.insert(inst_begin(F), inst_end(F));
76 // Step #2: WorkList processing. Iterate through all of the instructions,
77 // checking to see if there are any additionally defined subexpressions in the
78 // program. If so, eliminate them!
80 while (!WorkList.empty()) {
81 Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
82 WorkList.erase(WorkList.begin());
84 // If this instruction computes a value, try to fold together common
85 // instructions that compute it.
87 if (I.getType() != Type::VoidTy) {
88 std::vector<Value*> EqualValues;
89 VN->getEqualNumberNodes(&I, EqualValues);
91 if (!EqualValues.empty())
92 Changed |= EliminateRedundancies(&I, EqualValues);
96 // When the worklist is empty, return whether or not we changed anything...
100 bool GCSE::EliminateRedundancies(Instruction *I,
101 std::vector<Value*> &EqualValues) {
102 // If the EqualValues set contains any non-instruction values, then we know
103 // that all of the instructions can be replaced with the non-instruction value
104 // because it is guaranteed to dominate all of the instructions in the
105 // function. We only have to do hard work if all we have are instructions.
107 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
108 if (!isa<Instruction>(EqualValues[i])) {
109 // Found a non-instruction. Replace all instructions with the
112 Value *Replacement = EqualValues[i];
114 // Make sure we get I as well...
117 // Replace all instructions with the Replacement value.
118 for (i = 0; i != e; ++i)
119 if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
120 // Change all users of I to use Replacement.
121 I->replaceAllUsesWith(Replacement);
123 if (isa<LoadInst>(I))
124 ++NumLoadRemoved; // Keep track of loads eliminated
125 ++NumInstRemoved; // Keep track of number of instructions eliminated
126 ++NumNonInsts; // Keep track of number of insts repl with values
128 // Erase the instruction from the program.
129 I->getParent()->getInstList().erase(I);
136 // Remove duplicate entries from EqualValues...
137 std::sort(EqualValues.begin(), EqualValues.end());
138 EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
141 // From this point on, EqualValues is logically a vector of instructions.
143 bool Changed = false;
144 EqualValues.push_back(I); // Make sure I is included...
145 while (EqualValues.size() > 1) {
146 // FIXME, this could be done better than simple iteration!
147 Instruction *Test = cast<Instruction>(EqualValues.back());
148 EqualValues.pop_back();
150 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
151 if (Instruction *Ret = EliminateCSE(Test,
152 cast<Instruction>(EqualValues[i]))) {
153 if (Ret == Test) // Eliminated EqualValues[i]
154 EqualValues[i] = Test; // Make sure that we reprocess I at some point
163 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
164 // uses of the instruction use First now instead.
166 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
167 Instruction &Second = *SI;
169 //cerr << "DEL " << (void*)Second << Second;
171 // Add the first instruction back to the worklist
172 WorkList.insert(First);
174 // Add all uses of the second instruction to the worklist
175 for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
177 WorkList.insert(cast<Instruction>(*UI));
179 // Make all users of 'Second' now use 'First'
180 Second.replaceAllUsesWith(First);
182 // Erase the second instruction from the program
183 Second.getParent()->getInstList().erase(SI);
186 // EliminateCSE - The two instruction I & Other have been found to be common
187 // subexpressions. This function is responsible for eliminating one of them,
188 // and for fixing the worklist to be correct. The instruction that is preserved
189 // is returned from the function if the other is eliminated, otherwise null is
192 Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
196 WorkList.erase(Other); // Other may not actually be on the worklist anymore...
198 // Handle the easy case, where both instructions are in the same basic block
199 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
200 Instruction *Ret = 0;
203 // Eliminate the second occurring instruction. Add all uses of the second
204 // instruction to the worklist.
206 // Scan the basic block looking for the "first" instruction
207 BasicBlock::iterator BI = BB1->begin();
208 while (&*BI != I && &*BI != Other) {
210 assert(BI != BB1->end() && "Instructions not found in parent BB!");
213 // Keep track of which instructions occurred first & second
214 Instruction *First = BI;
215 Instruction *Second = I != First ? I : Other; // Get iterator to second inst
218 // Destroy Second, using First instead.
219 ReplaceInstWithInst(First, BI);
222 // Otherwise, the two instructions are in different basic blocks. If one
223 // dominates the other instruction, we can simply use it
225 } else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
226 ReplaceInstWithInst(I, Other);
228 } else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
229 ReplaceInstWithInst(Other, I);
232 // This code is disabled because it has several problems:
233 // One, the actual assumption is wrong, as shown by this code:
234 // int "test"(int %X, int %Y) {
235 // %Z = add int %X, %Y
238 // %Q = add int %X, %Y
242 // Here there are no shared dominators. Additionally, this had the habit of
243 // moving computations where they were not always computed. For example, in
252 // In this case, the expression would be hoisted to outside the 'if' stmt,
253 // causing the expression to be evaluated, even for the if (d) path, which
254 // could cause problems, if, for example, it caused a divide by zero. In
255 // general the problem this case is trying to solve is better addressed with
261 if (isa<LoadInst>(Ret))
262 ++NumLoadRemoved; // Keep track of loads eliminated
263 ++NumInstRemoved; // Keep track of number of instructions eliminated
265 // Add all users of Ret to the worklist...
266 for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
267 if (Instruction *Inst = dyn_cast<Instruction>(*I))
268 WorkList.insert(Inst);