blob: e8e140f2032884836f2680d08321ad2e2300d0be [file] [log] [blame]
Chris Lattnerd80e9732002-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
Chris Lattner2964f362002-08-30 22:53:30 +00005// using an existing value numbering implementation to identify the common
6// subexpressions, eliminating them when possible.
Chris Lattnerd80e9732002-04-28 00:47:11 +00007//
Chris Lattnerd80e9732002-04-28 00:47:11 +00008//===----------------------------------------------------------------------===//
9
Chris Lattner022103b2002-05-07 20:03:00 +000010#include "llvm/Transforms/Scalar.h"
Chris Lattnerd80e9732002-04-28 00:47:11 +000011#include "llvm/iMemory.h"
Chris Lattner2964f362002-08-30 22:53:30 +000012#include "llvm/Type.h"
Chris Lattnerd80e9732002-04-28 00:47:11 +000013#include "llvm/Analysis/Dominators.h"
Chris Lattner14987f12002-08-30 20:22:29 +000014#include "llvm/Analysis/ValueNumbering.h"
Chris Lattnerd80e9732002-04-28 00:47:11 +000015#include "llvm/Support/InstIterator.h"
Chris Lattner3dec1f22002-05-10 15:38:35 +000016#include "Support/StatisticReporter.h"
Chris Lattnerd80e9732002-04-28 00:47:11 +000017#include <algorithm>
Chris Lattnerd80e9732002-04-28 00:47:11 +000018
19namespace {
Chris Lattner14987f12002-08-30 20:22:29 +000020 Statistic<> NumInstRemoved("gcse\t\t- Number of instructions removed");
21 Statistic<> NumLoadRemoved("gcse\t\t- Number of loads removed");
22 Statistic<> NumNonInsts ("gcse\t\t- Number of instructions removed due "
23 "to non-instruction values");
24
25 class GCSE : public FunctionPass {
Chris Lattner2964f362002-08-30 22:53:30 +000026 std::set<Instruction*> WorkList;
Chris Lattner18fb2a62002-05-14 05:02:40 +000027 DominatorSet *DomSetInfo;
Chris Lattner14987f12002-08-30 20:22:29 +000028#if 0
Chris Lattner18fb2a62002-05-14 05:02:40 +000029 ImmediateDominators *ImmDominator;
Chris Lattner14987f12002-08-30 20:22:29 +000030#endif
31 ValueNumbering *VN;
Chris Lattnerd80e9732002-04-28 00:47:11 +000032 public:
Chris Lattner7e708292002-06-25 16:13:24 +000033 virtual bool runOnFunction(Function &F);
Chris Lattnerd80e9732002-04-28 00:47:11 +000034
Chris Lattnerd80e9732002-04-28 00:47:11 +000035 private:
Chris Lattner14987f12002-08-30 20:22:29 +000036 bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
37 Instruction *EliminateCSE(Instruction *I, Instruction *Other);
Chris Lattnerd80e9732002-04-28 00:47:11 +000038 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
Chris Lattner18fb2a62002-05-14 05:02:40 +000039
Chris Lattnerd80e9732002-04-28 00:47:11 +000040 // This transformation requires dominator and immediate dominator info
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner97e52e42002-04-28 21:27:06 +000042 AU.preservesCFG();
Chris Lattner5f0eb8d2002-08-08 19:01:30 +000043 AU.addRequired<DominatorSet>();
44 AU.addRequired<ImmediateDominators>();
Chris Lattner14987f12002-08-30 20:22:29 +000045 AU.addRequired<ValueNumbering>();
Chris Lattnerd80e9732002-04-28 00:47:11 +000046 }
47 };
Chris Lattnerf6293092002-07-23 18:06:35 +000048
Chris Lattnera6275cc2002-07-26 21:12:46 +000049 RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
Chris Lattnerd80e9732002-04-28 00:47:11 +000050}
51
52// createGCSEPass - The public interface to this file...
53Pass *createGCSEPass() { return new GCSE(); }
54
55
56// GCSE::runOnFunction - This is the main transformation entry point for a
57// function.
58//
Chris Lattner7e708292002-06-25 16:13:24 +000059bool GCSE::runOnFunction(Function &F) {
Chris Lattnerd80e9732002-04-28 00:47:11 +000060 bool Changed = false;
61
Chris Lattnerd456ec92002-08-22 18:24:48 +000062 // Get pointers to the analysis results that we will be using...
Chris Lattnerd80e9732002-04-28 00:47:11 +000063 DomSetInfo = &getAnalysis<DominatorSet>();
Chris Lattner14987f12002-08-30 20:22:29 +000064#if 0
Chris Lattnerd80e9732002-04-28 00:47:11 +000065 ImmDominator = &getAnalysis<ImmediateDominators>();
Chris Lattner14987f12002-08-30 20:22:29 +000066#endif
67 VN = &getAnalysis<ValueNumbering>();
Chris Lattnerd80e9732002-04-28 00:47:11 +000068
69 // Step #1: Add all instructions in the function to the worklist for
70 // processing. All of the instructions are considered to be our
71 // subexpressions to eliminate if possible.
72 //
73 WorkList.insert(inst_begin(F), inst_end(F));
74
75 // Step #2: WorkList processing. Iterate through all of the instructions,
76 // checking to see if there are any additionally defined subexpressions in the
77 // program. If so, eliminate them!
78 //
79 while (!WorkList.empty()) {
Chris Lattner7e708292002-06-25 16:13:24 +000080 Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
Chris Lattnerd80e9732002-04-28 00:47:11 +000081 WorkList.erase(WorkList.begin());
82
Chris Lattner14987f12002-08-30 20:22:29 +000083 // If this instruction computes a value, try to fold together common
84 // instructions that compute it.
Chris Lattnerd80e9732002-04-28 00:47:11 +000085 //
Chris Lattner14987f12002-08-30 20:22:29 +000086 if (I.getType() != Type::VoidTy) {
87 std::vector<Value*> EqualValues;
88 VN->getEqualNumberNodes(&I, EqualValues);
89
90 if (!EqualValues.empty())
91 Changed |= EliminateRedundancies(&I, EqualValues);
92 }
Chris Lattnerd80e9732002-04-28 00:47:11 +000093 }
Chris Lattner18fb2a62002-05-14 05:02:40 +000094
Chris Lattnerd80e9732002-04-28 00:47:11 +000095 // When the worklist is empty, return whether or not we changed anything...
96 return Changed;
97}
98
Chris Lattner14987f12002-08-30 20:22:29 +000099bool GCSE::EliminateRedundancies(Instruction *I,
100 std::vector<Value*> &EqualValues) {
101 // If the EqualValues set contains any non-instruction values, then we know
102 // that all of the instructions can be replaced with the non-instruction value
103 // because it is guaranteed to dominate all of the instructions in the
104 // function. We only have to do hard work if all we have are instructions.
105 //
106 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
107 if (!isa<Instruction>(EqualValues[i])) {
108 // Found a non-instruction. Replace all instructions with the
109 // non-instruction.
110 //
111 Value *Replacement = EqualValues[i];
112
113 // Make sure we get I as well...
114 EqualValues[i] = I;
115
116 // Replace all instructions with the Replacement value.
117 for (i = 0; i != e; ++i)
118 if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
119 // Change all users of I to use Replacement.
120 I->replaceAllUsesWith(Replacement);
121
122 if (isa<LoadInst>(I))
123 ++NumLoadRemoved; // Keep track of loads eliminated
124 ++NumInstRemoved; // Keep track of number of instructions eliminated
125 ++NumNonInsts; // Keep track of number of insts repl with values
126
127 // Erase the instruction from the program.
128 I->getParent()->getInstList().erase(I);
129 }
130
131 return true;
132 }
133
134 // Remove duplicate entries from EqualValues...
135 std::sort(EqualValues.begin(), EqualValues.end());
136 EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
137 EqualValues.end());
138
139 // From this point on, EqualValues is logically a vector of instructions.
140 //
141 bool Changed = false;
142 EqualValues.push_back(I); // Make sure I is included...
143 while (EqualValues.size() > 1) {
144 // FIXME, this could be done better than simple iteration!
145 Instruction *Test = cast<Instruction>(EqualValues.back());
146 EqualValues.pop_back();
147
148 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
149 if (Instruction *Ret = EliminateCSE(Test,
150 cast<Instruction>(EqualValues[i]))) {
151 if (Ret == Test) // Eliminated EqualValues[i]
152 EqualValues[i] = Test; // Make sure that we reprocess I at some point
153 Changed = true;
154 break;
155 }
156 }
157 return Changed;
158}
159
Chris Lattnerd80e9732002-04-28 00:47:11 +0000160
161// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
162// uses of the instruction use First now instead.
163//
164void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000165 Instruction &Second = *SI;
Chris Lattner8b054c02002-04-29 16:20:25 +0000166
167 //cerr << "DEL " << (void*)Second << Second;
Chris Lattnerd80e9732002-04-28 00:47:11 +0000168
169 // Add the first instruction back to the worklist
170 WorkList.insert(First);
171
172 // Add all uses of the second instruction to the worklist
Chris Lattner7e708292002-06-25 16:13:24 +0000173 for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
Chris Lattnerd80e9732002-04-28 00:47:11 +0000174 UI != UE; ++UI)
175 WorkList.insert(cast<Instruction>(*UI));
176
177 // Make all users of 'Second' now use 'First'
Chris Lattner7e708292002-06-25 16:13:24 +0000178 Second.replaceAllUsesWith(First);
Chris Lattnerd80e9732002-04-28 00:47:11 +0000179
180 // Erase the second instruction from the program
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Second.getParent()->getInstList().erase(SI);
Chris Lattnerd80e9732002-04-28 00:47:11 +0000182}
183
Chris Lattner14987f12002-08-30 20:22:29 +0000184// EliminateCSE - The two instruction I & Other have been found to be common
185// subexpressions. This function is responsible for eliminating one of them,
186// and for fixing the worklist to be correct. The instruction that is preserved
187// is returned from the function if the other is eliminated, otherwise null is
188// returned.
Chris Lattnerd80e9732002-04-28 00:47:11 +0000189//
Chris Lattner14987f12002-08-30 20:22:29 +0000190Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
Chris Lattner18fb2a62002-05-14 05:02:40 +0000191 assert(I != Other);
Chris Lattner8b054c02002-04-29 16:20:25 +0000192
Chris Lattner18fb2a62002-05-14 05:02:40 +0000193 WorkList.erase(I);
Chris Lattner8b054c02002-04-29 16:20:25 +0000194 WorkList.erase(Other); // Other may not actually be on the worklist anymore...
Chris Lattnerd80e9732002-04-28 00:47:11 +0000195
Chris Lattnerd80e9732002-04-28 00:47:11 +0000196 // Handle the easy case, where both instructions are in the same basic block
197 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
Chris Lattner14987f12002-08-30 20:22:29 +0000198 Instruction *Ret = 0;
199
Chris Lattnerd80e9732002-04-28 00:47:11 +0000200 if (BB1 == BB2) {
201 // Eliminate the second occuring instruction. Add all uses of the second
202 // instruction to the worklist.
203 //
204 // Scan the basic block looking for the "first" instruction
205 BasicBlock::iterator BI = BB1->begin();
Chris Lattner7e708292002-06-25 16:13:24 +0000206 while (&*BI != I && &*BI != Other) {
Chris Lattnerd80e9732002-04-28 00:47:11 +0000207 ++BI;
208 assert(BI != BB1->end() && "Instructions not found in parent BB!");
209 }
210
211 // Keep track of which instructions occurred first & second
Chris Lattner7e708292002-06-25 16:13:24 +0000212 Instruction *First = BI;
Chris Lattnerd80e9732002-04-28 00:47:11 +0000213 Instruction *Second = I != First ? I : Other; // Get iterator to second inst
Chris Lattner7e708292002-06-25 16:13:24 +0000214 BI = Second;
Chris Lattnerd80e9732002-04-28 00:47:11 +0000215
216 // Destroy Second, using First instead.
Chris Lattner14987f12002-08-30 20:22:29 +0000217 ReplaceInstWithInst(First, BI);
218 Ret = First;
Chris Lattnerd80e9732002-04-28 00:47:11 +0000219
220 // Otherwise, the two instructions are in different basic blocks. If one
221 // dominates the other instruction, we can simply use it
222 //
223 } else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
Chris Lattner7e708292002-06-25 16:13:24 +0000224 ReplaceInstWithInst(I, Other);
Chris Lattner14987f12002-08-30 20:22:29 +0000225 Ret = I;
Chris Lattnerd80e9732002-04-28 00:47:11 +0000226 } else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
Chris Lattner7e708292002-06-25 16:13:24 +0000227 ReplaceInstWithInst(Other, I);
Chris Lattner14987f12002-08-30 20:22:29 +0000228 Ret = Other;
Chris Lattnerd80e9732002-04-28 00:47:11 +0000229 } else {
Chris Lattnerbe1ecf62002-08-02 18:06:01 +0000230 // This code is disabled because it has several problems:
231 // One, the actual assumption is wrong, as shown by this code:
232 // int "test"(int %X, int %Y) {
233 // %Z = add int %X, %Y
234 // ret int %Z
235 // Unreachable:
236 // %Q = add int %X, %Y
237 // ret int %Q
238 // }
239 //
240 // Here there are no shared dominators. Additionally, this had the habit of
241 // moving computations where they were not always computed. For example, in
242 // a cast like this:
243 // if (c) {
244 // if (d) ...
245 // else ... X+Y ...
246 // } else {
247 // ... X+Y ...
248 // }
249 //
250 // In thiscase, the expression would be hoisted to outside the 'if' stmt,
251 // causing the expression to be evaluated, even for the if (d) path, which
252 // could cause problems, if, for example, it caused a divide by zero. In
253 // general the problem this case is trying to solve is better addressed with
254 // PRE than GCSE.
255 //
Chris Lattner14987f12002-08-30 20:22:29 +0000256 return 0;
Chris Lattnerbe1ecf62002-08-02 18:06:01 +0000257
258#if 0
Chris Lattnerd80e9732002-04-28 00:47:11 +0000259 // Handle the most general case now. In this case, neither I dom Other nor
260 // Other dom I. Because we are in SSA form, we are guaranteed that the
261 // operands of the two instructions both dominate the uses, so we _know_
262 // that there must exist a block that dominates both instructions (if the
263 // operands of the instructions are globals or constants, worst case we
264 // would get the entry node of the function). Search for this block now.
265 //
266
267 // Search up the immediate dominator chain of BB1 for the shared dominator
268 BasicBlock *SharedDom = (*ImmDominator)[BB1];
269 while (!DomSetInfo->dominates(SharedDom, BB2))
270 SharedDom = (*ImmDominator)[SharedDom];
271
272 // At this point, shared dom must dominate BOTH BB1 and BB2...
273 assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
274 DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
275
276 // Rip 'I' out of BB1, and move it to the end of SharedDom.
277 BB1->getInstList().remove(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000278 SharedDom->getInstList().insert(--SharedDom->end(), I);
Chris Lattnerd80e9732002-04-28 00:47:11 +0000279
280 // Eliminate 'Other' now.
Chris Lattner7e708292002-06-25 16:13:24 +0000281 ReplaceInstWithInst(I, Other);
Chris Lattnerbe1ecf62002-08-02 18:06:01 +0000282#endif
Chris Lattnerd80e9732002-04-28 00:47:11 +0000283 }
Chris Lattnerd80e9732002-04-28 00:47:11 +0000284
Chris Lattner14987f12002-08-30 20:22:29 +0000285 if (isa<LoadInst>(Ret))
286 ++NumLoadRemoved; // Keep track of loads eliminated
287 ++NumInstRemoved; // Keep track of number of instructions eliminated
Chris Lattnerd80e9732002-04-28 00:47:11 +0000288
Chris Lattner14987f12002-08-30 20:22:29 +0000289 // Add all users of Ret to the worklist...
290 for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
291 if (Instruction *Inst = dyn_cast<Instruction>(*I))
292 WorkList.insert(Inst);
Chris Lattnerd80e9732002-04-28 00:47:11 +0000293
Chris Lattner14987f12002-08-30 20:22:29 +0000294 return Ret;
Chris Lattner18fb2a62002-05-14 05:02:40 +0000295}