blob: ef1d056ed7520783ee7b1bbe615cf21ed86ecbc4 [file] [log] [blame]
Chris Lattner1467f642002-04-28 00:47:11 +00001//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
2//
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.
7//
Chris Lattner1467f642002-04-28 00:47:11 +00008//===----------------------------------------------------------------------===//
9
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000010#include "llvm/Transforms/Scalar.h"
Chris Lattner1467f642002-04-28 00:47:11 +000011#include "llvm/InstrTypes.h"
12#include "llvm/iMemory.h"
13#include "llvm/Analysis/Dominators.h"
Chris Lattnerb2a31092002-08-30 20:22:29 +000014#include "llvm/Analysis/ValueNumbering.h"
Chris Lattner1467f642002-04-28 00:47:11 +000015#include "llvm/Support/InstIterator.h"
Chris Lattnerd38ddb12002-05-14 05:02:40 +000016#include "llvm/Support/CFG.h"
Chris Lattnerb2a31092002-08-30 20:22:29 +000017#include "llvm/Type.h"
Chris Lattner0b18c1d2002-05-10 15:38:35 +000018#include "Support/StatisticReporter.h"
Chris Lattner1467f642002-04-28 00:47:11 +000019#include <algorithm>
Anand Shukla2bc64192002-06-25 21:07:58 +000020using std::set;
21using std::map;
22
Chris Lattner1467f642002-04-28 00:47:11 +000023
24namespace {
Chris Lattnerb2a31092002-08-30 20:22:29 +000025 Statistic<> NumInstRemoved("gcse\t\t- Number of instructions removed");
26 Statistic<> NumLoadRemoved("gcse\t\t- Number of loads removed");
27 Statistic<> NumNonInsts ("gcse\t\t- Number of instructions removed due "
28 "to non-instruction values");
29
30 class GCSE : public FunctionPass {
Chris Lattnerd38ddb12002-05-14 05:02:40 +000031 set<Instruction*> WorkList;
32 DominatorSet *DomSetInfo;
Chris Lattnerb2a31092002-08-30 20:22:29 +000033#if 0
Chris Lattnerd38ddb12002-05-14 05:02:40 +000034 ImmediateDominators *ImmDominator;
Chris Lattnerb2a31092002-08-30 20:22:29 +000035#endif
36 ValueNumbering *VN;
Chris Lattner1467f642002-04-28 00:47:11 +000037 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000038 virtual bool runOnFunction(Function &F);
Chris Lattner1467f642002-04-28 00:47:11 +000039
Chris Lattner1467f642002-04-28 00:47:11 +000040 private:
Chris Lattnerb2a31092002-08-30 20:22:29 +000041 bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
42 Instruction *EliminateCSE(Instruction *I, Instruction *Other);
Chris Lattner1467f642002-04-28 00:47:11 +000043 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
Chris Lattnerd38ddb12002-05-14 05:02:40 +000044
Chris Lattner1467f642002-04-28 00:47:11 +000045 // This transformation requires dominator and immediate dominator info
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf12cc842002-04-28 21:27:06 +000047 AU.preservesCFG();
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000048 AU.addRequired<DominatorSet>();
49 AU.addRequired<ImmediateDominators>();
Chris Lattnerb2a31092002-08-30 20:22:29 +000050 AU.addRequired<ValueNumbering>();
Chris Lattner1467f642002-04-28 00:47:11 +000051 }
52 };
Chris Lattnerb28b6802002-07-23 18:06:35 +000053
Chris Lattnerc8b70922002-07-26 21:12:46 +000054 RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
Chris Lattner1467f642002-04-28 00:47:11 +000055}
56
57// createGCSEPass - The public interface to this file...
58Pass *createGCSEPass() { return new GCSE(); }
59
60
61// GCSE::runOnFunction - This is the main transformation entry point for a
62// function.
63//
Chris Lattner113f4f42002-06-25 16:13:24 +000064bool GCSE::runOnFunction(Function &F) {
Chris Lattner1467f642002-04-28 00:47:11 +000065 bool Changed = false;
66
Chris Lattner879cb972002-08-22 18:24:48 +000067 // Get pointers to the analysis results that we will be using...
Chris Lattner1467f642002-04-28 00:47:11 +000068 DomSetInfo = &getAnalysis<DominatorSet>();
Chris Lattnerb2a31092002-08-30 20:22:29 +000069#if 0
Chris Lattner1467f642002-04-28 00:47:11 +000070 ImmDominator = &getAnalysis<ImmediateDominators>();
Chris Lattnerb2a31092002-08-30 20:22:29 +000071#endif
72 VN = &getAnalysis<ValueNumbering>();
Chris Lattner1467f642002-04-28 00:47:11 +000073
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.
77 //
78 WorkList.insert(inst_begin(F), inst_end(F));
79
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!
83 //
84 while (!WorkList.empty()) {
Chris Lattner113f4f42002-06-25 16:13:24 +000085 Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
Chris Lattner1467f642002-04-28 00:47:11 +000086 WorkList.erase(WorkList.begin());
87
Chris Lattnerb2a31092002-08-30 20:22:29 +000088 // If this instruction computes a value, try to fold together common
89 // instructions that compute it.
Chris Lattner1467f642002-04-28 00:47:11 +000090 //
Chris Lattnerb2a31092002-08-30 20:22:29 +000091 if (I.getType() != Type::VoidTy) {
92 std::vector<Value*> EqualValues;
93 VN->getEqualNumberNodes(&I, EqualValues);
94
95 if (!EqualValues.empty())
96 Changed |= EliminateRedundancies(&I, EqualValues);
97 }
Chris Lattner1467f642002-04-28 00:47:11 +000098 }
Chris Lattnerd38ddb12002-05-14 05:02:40 +000099
Chris Lattner1467f642002-04-28 00:47:11 +0000100 // When the worklist is empty, return whether or not we changed anything...
101 return Changed;
102}
103
Chris Lattnerb2a31092002-08-30 20:22:29 +0000104bool GCSE::EliminateRedundancies(Instruction *I,
105 std::vector<Value*> &EqualValues) {
106 // If the EqualValues set contains any non-instruction values, then we know
107 // that all of the instructions can be replaced with the non-instruction value
108 // because it is guaranteed to dominate all of the instructions in the
109 // function. We only have to do hard work if all we have are instructions.
110 //
111 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
112 if (!isa<Instruction>(EqualValues[i])) {
113 // Found a non-instruction. Replace all instructions with the
114 // non-instruction.
115 //
116 Value *Replacement = EqualValues[i];
117
118 // Make sure we get I as well...
119 EqualValues[i] = I;
120
121 // Replace all instructions with the Replacement value.
122 for (i = 0; i != e; ++i)
123 if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
124 // Change all users of I to use Replacement.
125 I->replaceAllUsesWith(Replacement);
126
127 if (isa<LoadInst>(I))
128 ++NumLoadRemoved; // Keep track of loads eliminated
129 ++NumInstRemoved; // Keep track of number of instructions eliminated
130 ++NumNonInsts; // Keep track of number of insts repl with values
131
132 // Erase the instruction from the program.
133 I->getParent()->getInstList().erase(I);
134 }
135
136 return true;
137 }
138
139 // Remove duplicate entries from EqualValues...
140 std::sort(EqualValues.begin(), EqualValues.end());
141 EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
142 EqualValues.end());
143
144 // From this point on, EqualValues is logically a vector of instructions.
145 //
146 bool Changed = false;
147 EqualValues.push_back(I); // Make sure I is included...
148 while (EqualValues.size() > 1) {
149 // FIXME, this could be done better than simple iteration!
150 Instruction *Test = cast<Instruction>(EqualValues.back());
151 EqualValues.pop_back();
152
153 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
154 if (Instruction *Ret = EliminateCSE(Test,
155 cast<Instruction>(EqualValues[i]))) {
156 if (Ret == Test) // Eliminated EqualValues[i]
157 EqualValues[i] = Test; // Make sure that we reprocess I at some point
158 Changed = true;
159 break;
160 }
161 }
162 return Changed;
163}
164
Chris Lattner1467f642002-04-28 00:47:11 +0000165
166// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
167// uses of the instruction use First now instead.
168//
169void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000170 Instruction &Second = *SI;
Chris Lattner2dfc6672002-04-29 16:20:25 +0000171
172 //cerr << "DEL " << (void*)Second << Second;
Chris Lattner1467f642002-04-28 00:47:11 +0000173
174 // Add the first instruction back to the worklist
175 WorkList.insert(First);
176
177 // Add all uses of the second instruction to the worklist
Chris Lattner113f4f42002-06-25 16:13:24 +0000178 for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
Chris Lattner1467f642002-04-28 00:47:11 +0000179 UI != UE; ++UI)
180 WorkList.insert(cast<Instruction>(*UI));
181
182 // Make all users of 'Second' now use 'First'
Chris Lattner113f4f42002-06-25 16:13:24 +0000183 Second.replaceAllUsesWith(First);
Chris Lattner1467f642002-04-28 00:47:11 +0000184
185 // Erase the second instruction from the program
Chris Lattner113f4f42002-06-25 16:13:24 +0000186 Second.getParent()->getInstList().erase(SI);
Chris Lattner1467f642002-04-28 00:47:11 +0000187}
188
Chris Lattnerb2a31092002-08-30 20:22:29 +0000189// EliminateCSE - The two instruction I & Other have been found to be common
190// subexpressions. This function is responsible for eliminating one of them,
191// and for fixing the worklist to be correct. The instruction that is preserved
192// is returned from the function if the other is eliminated, otherwise null is
193// returned.
Chris Lattner1467f642002-04-28 00:47:11 +0000194//
Chris Lattnerb2a31092002-08-30 20:22:29 +0000195Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
Chris Lattnerd38ddb12002-05-14 05:02:40 +0000196 assert(I != Other);
Chris Lattner2dfc6672002-04-29 16:20:25 +0000197
Chris Lattnerd38ddb12002-05-14 05:02:40 +0000198 WorkList.erase(I);
Chris Lattner2dfc6672002-04-29 16:20:25 +0000199 WorkList.erase(Other); // Other may not actually be on the worklist anymore...
Chris Lattner1467f642002-04-28 00:47:11 +0000200
Chris Lattner1467f642002-04-28 00:47:11 +0000201 // Handle the easy case, where both instructions are in the same basic block
202 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
Chris Lattnerb2a31092002-08-30 20:22:29 +0000203 Instruction *Ret = 0;
204
Chris Lattner1467f642002-04-28 00:47:11 +0000205 if (BB1 == BB2) {
206 // Eliminate the second occuring instruction. Add all uses of the second
207 // instruction to the worklist.
208 //
209 // Scan the basic block looking for the "first" instruction
210 BasicBlock::iterator BI = BB1->begin();
Chris Lattner113f4f42002-06-25 16:13:24 +0000211 while (&*BI != I && &*BI != Other) {
Chris Lattner1467f642002-04-28 00:47:11 +0000212 ++BI;
213 assert(BI != BB1->end() && "Instructions not found in parent BB!");
214 }
215
216 // Keep track of which instructions occurred first & second
Chris Lattner113f4f42002-06-25 16:13:24 +0000217 Instruction *First = BI;
Chris Lattner1467f642002-04-28 00:47:11 +0000218 Instruction *Second = I != First ? I : Other; // Get iterator to second inst
Chris Lattner113f4f42002-06-25 16:13:24 +0000219 BI = Second;
Chris Lattner1467f642002-04-28 00:47:11 +0000220
221 // Destroy Second, using First instead.
Chris Lattnerb2a31092002-08-30 20:22:29 +0000222 ReplaceInstWithInst(First, BI);
223 Ret = First;
Chris Lattner1467f642002-04-28 00:47:11 +0000224
225 // Otherwise, the two instructions are in different basic blocks. If one
226 // dominates the other instruction, we can simply use it
227 //
228 } else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
Chris Lattner113f4f42002-06-25 16:13:24 +0000229 ReplaceInstWithInst(I, Other);
Chris Lattnerb2a31092002-08-30 20:22:29 +0000230 Ret = I;
Chris Lattner1467f642002-04-28 00:47:11 +0000231 } else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
Chris Lattner113f4f42002-06-25 16:13:24 +0000232 ReplaceInstWithInst(Other, I);
Chris Lattnerb2a31092002-08-30 20:22:29 +0000233 Ret = Other;
Chris Lattner1467f642002-04-28 00:47:11 +0000234 } else {
Chris Lattnerf56bd892002-08-02 18:06:01 +0000235 // This code is disabled because it has several problems:
236 // One, the actual assumption is wrong, as shown by this code:
237 // int "test"(int %X, int %Y) {
238 // %Z = add int %X, %Y
239 // ret int %Z
240 // Unreachable:
241 // %Q = add int %X, %Y
242 // ret int %Q
243 // }
244 //
245 // Here there are no shared dominators. Additionally, this had the habit of
246 // moving computations where they were not always computed. For example, in
247 // a cast like this:
248 // if (c) {
249 // if (d) ...
250 // else ... X+Y ...
251 // } else {
252 // ... X+Y ...
253 // }
254 //
255 // In thiscase, the expression would be hoisted to outside the 'if' stmt,
256 // causing the expression to be evaluated, even for the if (d) path, which
257 // could cause problems, if, for example, it caused a divide by zero. In
258 // general the problem this case is trying to solve is better addressed with
259 // PRE than GCSE.
260 //
Chris Lattnerb2a31092002-08-30 20:22:29 +0000261 return 0;
Chris Lattnerf56bd892002-08-02 18:06:01 +0000262
263#if 0
Chris Lattner1467f642002-04-28 00:47:11 +0000264 // Handle the most general case now. In this case, neither I dom Other nor
265 // Other dom I. Because we are in SSA form, we are guaranteed that the
266 // operands of the two instructions both dominate the uses, so we _know_
267 // that there must exist a block that dominates both instructions (if the
268 // operands of the instructions are globals or constants, worst case we
269 // would get the entry node of the function). Search for this block now.
270 //
271
272 // Search up the immediate dominator chain of BB1 for the shared dominator
273 BasicBlock *SharedDom = (*ImmDominator)[BB1];
274 while (!DomSetInfo->dominates(SharedDom, BB2))
275 SharedDom = (*ImmDominator)[SharedDom];
276
277 // At this point, shared dom must dominate BOTH BB1 and BB2...
278 assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
279 DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
280
281 // Rip 'I' out of BB1, and move it to the end of SharedDom.
282 BB1->getInstList().remove(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000283 SharedDom->getInstList().insert(--SharedDom->end(), I);
Chris Lattner1467f642002-04-28 00:47:11 +0000284
285 // Eliminate 'Other' now.
Chris Lattner113f4f42002-06-25 16:13:24 +0000286 ReplaceInstWithInst(I, Other);
Chris Lattnerf56bd892002-08-02 18:06:01 +0000287#endif
Chris Lattner1467f642002-04-28 00:47:11 +0000288 }
Chris Lattner1467f642002-04-28 00:47:11 +0000289
Chris Lattnerb2a31092002-08-30 20:22:29 +0000290 if (isa<LoadInst>(Ret))
291 ++NumLoadRemoved; // Keep track of loads eliminated
292 ++NumInstRemoved; // Keep track of number of instructions eliminated
Chris Lattner1467f642002-04-28 00:47:11 +0000293
Chris Lattnerb2a31092002-08-30 20:22:29 +0000294 // Add all users of Ret to the worklist...
295 for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
296 if (Instruction *Inst = dyn_cast<Instruction>(*I))
297 WorkList.insert(Inst);
Chris Lattner1467f642002-04-28 00:47:11 +0000298
Chris Lattnerb2a31092002-08-30 20:22:29 +0000299 return Ret;
Chris Lattnerd38ddb12002-05-14 05:02:40 +0000300}