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"
24 #include "Support/Debug.h"
29 Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
30 Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
31 Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
32 "to non-instruction values");
34 class GCSE : public FunctionPass {
35 std::set<Instruction*> WorkList;
36 DominatorSet *DomSetInfo;
39 virtual bool runOnFunction(Function &F);
42 bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
43 Instruction *EliminateCSE(Instruction *I, Instruction *Other);
44 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
46 // This transformation requires dominator and immediate dominator info
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
49 AU.addRequired<DominatorSet>();
50 AU.addRequired<ImmediateDominators>();
51 AU.addRequired<ValueNumbering>();
55 RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
58 // createGCSEPass - The public interface to this file...
59 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
61 // GCSE::runOnFunction - This is the main transformation entry point for a
64 bool GCSE::runOnFunction(Function &F) {
67 // Get pointers to the analysis results that we will be using...
68 DomSetInfo = &getAnalysis<DominatorSet>();
69 VN = &getAnalysis<ValueNumbering>();
71 // Step #1: Add all instructions in the function to the worklist for
72 // processing. All of the instructions are considered to be our
73 // subexpressions to eliminate if possible.
75 WorkList.insert(inst_begin(F), inst_end(F));
77 // Step #2: WorkList processing. Iterate through all of the instructions,
78 // checking to see if there are any additionally defined subexpressions in the
79 // program. If so, eliminate them!
81 while (!WorkList.empty()) {
82 Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
83 WorkList.erase(WorkList.begin());
85 // If this instruction computes a value, try to fold together common
86 // instructions that compute it.
88 if (I.getType() != Type::VoidTy) {
89 std::vector<Value*> EqualValues;
90 VN->getEqualNumberNodes(&I, EqualValues);
92 if (!EqualValues.empty())
93 Changed |= EliminateRedundancies(&I, EqualValues);
97 // When the worklist is empty, return whether or not we changed anything...
101 bool GCSE::EliminateRedundancies(Instruction *I,
102 std::vector<Value*> &EqualValues) {
103 // If the EqualValues set contains any non-instruction values, then we know
104 // that all of the instructions can be replaced with the non-instruction value
105 // because it is guaranteed to dominate all of the instructions in the
106 // function. We only have to do hard work if all we have are instructions.
108 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
109 if (!isa<Instruction>(EqualValues[i])) {
110 // Found a non-instruction. Replace all instructions with the
113 Value *Replacement = EqualValues[i];
115 // Make sure we get I as well...
118 // Replace all instructions with the Replacement value.
119 for (i = 0; i != e; ++i)
120 if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
121 // Change all users of I to use Replacement.
122 I->replaceAllUsesWith(Replacement);
124 if (isa<LoadInst>(I))
125 ++NumLoadRemoved; // Keep track of loads eliminated
126 ++NumInstRemoved; // Keep track of number of instructions eliminated
127 ++NumNonInsts; // Keep track of number of insts repl with values
129 // Erase the instruction from the program.
130 I->getParent()->getInstList().erase(I);
137 // Remove duplicate entries from EqualValues...
138 std::sort(EqualValues.begin(), EqualValues.end());
139 EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
142 // From this point on, EqualValues is logically a vector of instructions.
144 bool Changed = false;
145 EqualValues.push_back(I); // Make sure I is included...
146 while (EqualValues.size() > 1) {
147 // FIXME, this could be done better than simple iteration!
148 Instruction *Test = cast<Instruction>(EqualValues.back());
149 EqualValues.pop_back();
151 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
152 if (Instruction *Ret = EliminateCSE(Test,
153 cast<Instruction>(EqualValues[i]))) {
154 if (Ret == Test) // Eliminated EqualValues[i]
155 EqualValues[i] = Test; // Make sure that we reprocess I at some point
164 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
165 // uses of the instruction use First now instead.
167 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
168 Instruction &Second = *SI;
170 DEBUG(std::cerr << "GCSE: Substituting %" << First->getName() << " for: "
173 //cerr << "DEL " << (void*)Second << Second;
175 // Add the first instruction back to the worklist
176 WorkList.insert(First);
178 // Add all uses of the second instruction to the worklist
179 for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
181 WorkList.insert(cast<Instruction>(*UI));
183 // Make all users of 'Second' now use 'First'
184 Second.replaceAllUsesWith(First);
186 // Erase the second instruction from the program
187 Second.getParent()->getInstList().erase(SI);
190 // EliminateCSE - The two instruction I & Other have been found to be common
191 // subexpressions. This function is responsible for eliminating one of them,
192 // and for fixing the worklist to be correct. The instruction that is preserved
193 // is returned from the function if the other is eliminated, otherwise null is
196 Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
200 WorkList.erase(Other); // Other may not actually be on the worklist anymore...
202 // Handle the easy case, where both instructions are in the same basic block
203 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
204 Instruction *Ret = 0;
207 // Eliminate the second occurring instruction. Add all uses of the second
208 // instruction to the worklist.
210 // Scan the basic block looking for the "first" instruction
211 BasicBlock::iterator BI = BB1->begin();
212 while (&*BI != I && &*BI != Other) {
214 assert(BI != BB1->end() && "Instructions not found in parent BB!");
217 // Keep track of which instructions occurred first & second
218 Instruction *First = BI;
219 Instruction *Second = I != First ? I : Other; // Get iterator to second inst
222 // Destroy Second, using First instead.
223 ReplaceInstWithInst(First, BI);
226 // Otherwise, the two instructions are in different basic blocks. If one
227 // dominates the other instruction, we can simply use it
229 } else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
230 ReplaceInstWithInst(I, Other);
232 } else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
233 ReplaceInstWithInst(Other, I);
236 // This code is disabled because it has several problems:
237 // One, the actual assumption is wrong, as shown by this code:
238 // int "test"(int %X, int %Y) {
239 // %Z = add int %X, %Y
242 // %Q = add int %X, %Y
246 // Here there are no shared dominators. Additionally, this had the habit of
247 // moving computations where they were not always computed. For example, in
256 // In this case, the expression would be hoisted to outside the 'if' stmt,
257 // causing the expression to be evaluated, even for the if (d) path, which
258 // could cause problems, if, for example, it caused a divide by zero. In
259 // general the problem this case is trying to solve is better addressed with
265 if (isa<LoadInst>(Ret))
266 ++NumLoadRemoved; // Keep track of loads eliminated
267 ++NumInstRemoved; // Keep track of number of instructions eliminated
269 // Add all users of Ret to the worklist...
270 for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
271 if (Instruction *Inst = dyn_cast<Instruction>(*I))
272 WorkList.insert(Inst);