blob: 268b654d140dbb5dd3dc05e1f9f1e4f2e22656ae [file] [log] [blame]
Chris Lattner138a1242001-06-27 23:38:11 +00001//===- SCCP.cpp - Sparse Conditional Constant Propogation -----------------===//
2//
3// This file implements sparse conditional constant propogation and merging:
4//
5// Specifically, this:
6// * Assumes values are constant unless proven otherwise
7// * Assumes BasicBlocks are dead unless proven otherwise
8// * Proves values to be constant, and replaces them with constants
9// . Proves conditional branches constant, and unconditionalizes them
10// * Folds multiple identical constants in the constant pool together
11//
12// Notice that:
13// * This pass has a habit of making definitions be dead. It is a good idea
14// to to run a DCE pass sometime after running this pass.
15//
16//===----------------------------------------------------------------------===//
17
Chris Lattner7e02b7e2001-06-30 04:36:40 +000018#include "llvm/Optimizations/ConstantProp.h"
19#include "llvm/Optimizations/ConstantHandling.h"
Chris Lattner138a1242001-06-27 23:38:11 +000020#include "llvm/Method.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/ConstPoolVals.h"
Chris Lattner138a1242001-06-27 23:38:11 +000023#include "llvm/InstrTypes.h"
24#include "llvm/iOther.h"
Chris Lattner3b7bfdb2001-07-14 06:11:51 +000025#include "llvm/iMemory.h"
Chris Lattner138a1242001-06-27 23:38:11 +000026#include "llvm/iTerminators.h"
Chris Lattner57dbb3a2001-07-23 17:46:59 +000027#include "llvm/Support/STLExtras.h"
Chris Lattner0bd654a2001-07-08 21:18:49 +000028#include "llvm/Assembly/Writer.h"
Chris Lattner138a1242001-06-27 23:38:11 +000029#include <algorithm>
30#include <map>
31#include <set>
32
Chris Lattner138a1242001-06-27 23:38:11 +000033// InstVal class - This class represents the different lattice values that an
34// instruction may occupy. It is a simple class with value semantics. The
35// potential constant value that is pointed to is owned by the constant pool
36// for the method being optimized.
37//
38class InstVal {
39 enum {
40 Undefined, // This instruction has no known value
41 Constant, // This instruction has a constant value
42 // Range, // This instruction is known to fall within a range
43 Overdefined // This instruction has an unknown value
44 } LatticeValue; // The current lattice position
45 ConstPoolVal *ConstantVal; // If Constant value, the current value
46public:
47 inline InstVal() : LatticeValue(Undefined), ConstantVal(0) {}
48
49 // markOverdefined - Return true if this is a new status to be in...
50 inline bool markOverdefined() {
51 if (LatticeValue != Overdefined) {
52 LatticeValue = Overdefined;
53 return true;
54 }
55 return false;
56 }
57
58 // markConstant - Return true if this is a new status for us...
59 inline bool markConstant(ConstPoolVal *V) {
60 if (LatticeValue != Constant) {
61 LatticeValue = Constant;
62 ConstantVal = V;
63 return true;
64 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +000065 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +000066 }
67 return false;
68 }
69
70 inline bool isUndefined() const { return LatticeValue == Undefined; }
71 inline bool isConstant() const { return LatticeValue == Constant; }
72 inline bool isOverdefined() const { return LatticeValue == Overdefined; }
73
74 inline ConstPoolVal *getConstant() const { return ConstantVal; }
75};
76
77
78
79//===----------------------------------------------------------------------===//
80// SCCP Class
81//
82// This class does all of the work of Sparse Conditional Constant Propogation.
83// It's public interface consists of a constructor and a doSCCP() method.
84//
85class SCCP {
86 Method *M; // The method that we are working on...
87
88 set<BasicBlock*> BBExecutable; // The basic blocks that are executable
89 map<Value*, InstVal> ValueState; // The state each value is in...
90
91 vector<Instruction*> InstWorkList; // The instruction work list
92 vector<BasicBlock*> BBWorkList; // The BasicBlock work list
93
94 //===--------------------------------------------------------------------===//
95 // The public interface for this class
96 //
97public:
98
99 // SCCP Ctor - Save the method to operate on...
100 inline SCCP(Method *m) : M(m) {}
101
102 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
103 // return true if the method was modified.
104 bool doSCCP();
105
106 //===--------------------------------------------------------------------===//
107 // The implementation of this class
108 //
109private:
110
111 // markValueOverdefined - Make a value be marked as "constant". If the value
112 // is not already a constant, add it to the instruction work list so that
113 // the users of the instruction are updated later.
114 //
115 inline bool markConstant(Instruction *I, ConstPoolVal *V) {
116 //cerr << "markConstant: " << V << " = " << I;
117 if (ValueState[I].markConstant(V)) {
118 InstWorkList.push_back(I);
119 return true;
120 }
121 return false;
122 }
123
124 // markValueOverdefined - Make a value be marked as "overdefined". If the
125 // value is not already overdefined, add it to the instruction work list so
126 // that the users of the instruction are updated later.
127 //
128 inline bool markOverdefined(Value *V) {
129 if (ValueState[V].markOverdefined()) {
130 if (Instruction *I = V->castInstruction()) {
131 //cerr << "markOverdefined: " << V;
132 InstWorkList.push_back(I); // Only instructions go on the work list
133 }
134 return true;
135 }
136 return false;
137 }
138
139 // getValueState - Return the InstVal object that corresponds to the value.
140 // This function is neccesary because not all values should start out in the
141 // underdefined state... MethodArgument's should be overdefined, and constants
142 // should be marked as constants. If a value is not known to be an
143 // Instruction object, then use this accessor to get its value from the map.
144 //
145 inline InstVal &getValueState(Value *V) {
146 map<Value*, InstVal>::iterator I = ValueState.find(V);
147 if (I != ValueState.end()) return I->second; // Common case, in the map
148
149 if (ConstPoolVal *CPV = V->castConstant()) { // Constants are constant
150 ValueState[CPV].markConstant(CPV);
151 } else if (V->isMethodArgument()) { // MethodArgs are overdefined
152 ValueState[V].markOverdefined();
153 }
154 // All others are underdefined by default...
155 return ValueState[V];
156 }
157
158 // markExecutable - Mark a basic block as executable, adding it to the BB
159 // work list if it is not already executable...
160 //
161 void markExecutable(BasicBlock *BB) {
162 if (BBExecutable.count(BB)) return;
163 //cerr << "Marking BB Executable: " << BB;
164 BBExecutable.insert(BB); // Basic block is executable!
165 BBWorkList.push_back(BB); // Add the block to the work list!
166 }
167
Chris Lattner138a1242001-06-27 23:38:11 +0000168
Chris Lattnercb056de2001-06-29 23:56:23 +0000169 // UpdateInstruction - Something changed in this instruction... Either an
170 // operand made a transition, or the instruction is newly executable. Change
171 // the value type of I to reflect these changes if appropriate.
172 //
173 void UpdateInstruction(Instruction *I);
174
175 // OperandChangedState - This method is invoked on all of the users of an
176 // instruction that was just changed state somehow.... Based on this
177 // information, we need to update the specified user of this instruction.
178 //
179 void OperandChangedState(User *U);
180};
Chris Lattner138a1242001-06-27 23:38:11 +0000181
182
183//===----------------------------------------------------------------------===//
184// SCCP Class Implementation
185
186
187// doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
188// return true if the method was modified.
189//
190bool SCCP::doSCCP() {
191 // Mark the first block of the method as being executable...
192 markExecutable(M->front());
193
194 // Process the work lists until their are empty!
195 while (!BBWorkList.empty() || !InstWorkList.empty()) {
196 // Process the instruction work list...
197 while (!InstWorkList.empty()) {
198 Instruction *I = InstWorkList.back();
199 InstWorkList.pop_back();
200
201 //cerr << "\nPopped off I-WL: " << I;
202
203
204 // "I" got into the work list because it either made the transition from
205 // bottom to constant, or to Overdefined.
206 //
207 // Update all of the users of this instruction's value...
208 //
209 for_each(I->use_begin(), I->use_end(),
210 bind_obj(this, &SCCP::OperandChangedState));
211 }
212
213 // Process the basic block work list...
214 while (!BBWorkList.empty()) {
215 BasicBlock *BB = BBWorkList.back();
216 BBWorkList.pop_back();
217
218 //cerr << "\nPopped off BBWL: " << BB;
219
220 // If this block only has a single successor, mark it as executable as
221 // well... if not, terminate the do loop.
222 //
223 if (BB->getTerminator()->getNumSuccessors() == 1)
224 markExecutable(BB->getTerminator()->getSuccessor(0));
225
226 // Loop over all of the instructions and notify them that they are newly
227 // executable...
228 for_each(BB->begin(), BB->end(),
229 bind_obj(this, &SCCP::UpdateInstruction));
230 }
231 }
232
233#if 0
234 for (Method::iterator BBI = M->begin(), BBEnd = M->end(); BBI != BBEnd; ++BBI)
235 if (!BBExecutable.count(*BBI))
236 cerr << "BasicBlock Dead:" << *BBI;
237#endif
238
239
240 // Iterate over all of the instructions in a method, replacing them with
241 // constants if we have found them to be of constant values.
242 //
243 bool MadeChanges = false;
244 for (Method::inst_iterator II = M->inst_begin(); II != M->inst_end(); ) {
245 Instruction *Inst = *II;
246 InstVal &IV = ValueState[Inst];
247 if (IV.isConstant()) {
248 ConstPoolVal *Const = IV.getConstant();
249 // cerr << "Constant: " << Inst << " is: " << Const;
250
251 // Replaces all of the uses of a variable with uses of the constant.
252 Inst->replaceAllUsesWith(Const);
253
254 // Remove the operator from the list of definitions...
255 Inst->getParent()->getInstList().remove(II.getInstructionIterator());
256
257 // The new constant inherits the old name of the operator...
258 if (Inst->hasName() && !Const->hasName())
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000259 Const->setName(Inst->getName(), M->getSymbolTableSure());
Chris Lattner138a1242001-06-27 23:38:11 +0000260
261 // Delete the operator now...
262 delete Inst;
263
264 // Incrementing the iterator in an unchecked manner could mess up the
265 // internals of 'II'. To make sure everything is happy, tell it we might
266 // have broken it.
267 II.resyncInstructionIterator();
268
269 // Hey, we just changed something!
270 MadeChanges = true;
Chris Lattnercb056de2001-06-29 23:56:23 +0000271 continue; // Skip the ++II at the end of the loop here...
272 } else if (Inst->isTerminator()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000273 MadeChanges |= opt::ConstantFoldTerminator((TerminatorInst*)Inst);
Chris Lattner138a1242001-06-27 23:38:11 +0000274 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000275
276 ++II;
Chris Lattner138a1242001-06-27 23:38:11 +0000277 }
278
279 // Merge identical constants last: this is important because we may have just
280 // introduced constants that already exist, and we don't want to pollute later
281 // stages with extraneous constants.
282 //
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000283 return MadeChanges;
Chris Lattner138a1242001-06-27 23:38:11 +0000284}
285
286
287// UpdateInstruction - Something changed in this instruction... Either an
288// operand made a transition, or the instruction is newly executable. Change
289// the value type of I to reflect these changes if appropriate. This method
290// makes sure to do the following actions:
291//
292// 1. If a phi node merges two constants in, and has conflicting value coming
293// from different branches, or if the PHI node merges in an overdefined
294// value, then the PHI node becomes overdefined.
295// 2. If a phi node merges only constants in, and they all agree on value, the
296// PHI node becomes a constant value equal to that.
297// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
298// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
299// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
300// 6. If a conditional branch has a value that is constant, make the selected
301// destination executable
302// 7. If a conditional branch has a value that is overdefined, make all
303// successors executable.
304//
305void SCCP::UpdateInstruction(Instruction *I) {
306 InstVal &IValue = ValueState[I];
307 if (IValue.isOverdefined())
308 return; // If already overdefined, we aren't going to effect anything
309
Chris Lattnera41f50d2001-07-07 19:24:15 +0000310 switch (I->getOpcode()) {
Chris Lattner138a1242001-06-27 23:38:11 +0000311 //===-----------------------------------------------------------------===//
312 // Handle PHI nodes...
313 //
314 case Instruction::PHINode: {
315 PHINode *PN = (PHINode*)I;
316 unsigned NumValues = PN->getNumIncomingValues(), i;
317 InstVal *OperandIV = 0;
318
319 // Look at all of the executable operands of the PHI node. If any of them
320 // are overdefined, the PHI becomes overdefined as well. If they are all
321 // constant, and they agree with each other, the PHI becomes the identical
322 // constant. If they are constant and don't agree, the PHI is overdefined.
323 // If there are no executable operands, the PHI remains undefined.
324 //
325 for (i = 0; i < NumValues; ++i) {
326 if (BBExecutable.count(PN->getIncomingBlock(i))) {
327 InstVal &IV = getValueState(PN->getIncomingValue(i));
328 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
329 if (IV.isOverdefined()) { // PHI node becomes overdefined!
330 markOverdefined(PN);
331 return;
332 }
333
334 if (OperandIV == 0) { // Grab the first value...
335 OperandIV = &IV;
336 } else { // Another value is being merged in!
337 // There is already a reachable operand. If we conflict with it,
338 // then the PHI node becomes overdefined. If we agree with it, we
339 // can continue on.
340
341 // Check to see if there are two different constants merging...
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000342 if (IV.getConstant() != OperandIV->getConstant()) {
Chris Lattner138a1242001-06-27 23:38:11 +0000343 // Yes there is. This means the PHI node is not constant.
344 // You must be overdefined poor PHI.
345 //
346 markOverdefined(I); // The PHI node now becomes overdefined
347 return; // I'm done analyzing you
348 }
349 }
350 }
351 }
352
353 // If we exited the loop, this means that the PHI node only has constant
354 // arguments that agree with each other(and OperandIV is a pointer to one
355 // of their InstVal's) or OperandIV is null because there are no defined
356 // incoming arguments. If this is the case, the PHI remains undefined.
357 //
358 if (OperandIV) {
359 assert(OperandIV->isConstant() && "Should only be here for constants!");
360 markConstant(I, OperandIV->getConstant()); // Aquire operand value
361 }
362 return;
363 }
364
365 //===-----------------------------------------------------------------===//
366 // Handle instructions that unconditionally provide overdefined values...
367 //
368 case Instruction::Malloc:
369 case Instruction::Free:
370 case Instruction::Alloca:
371 case Instruction::Load:
372 case Instruction::Store:
373 // TODO: getfield/putfield?
374 case Instruction::Call:
375 markOverdefined(I); // Memory and call's are all overdefined
376 return;
377
378 //===-----------------------------------------------------------------===//
379 // Handle Terminator instructions...
380 //
381 case Instruction::Ret: return; // Method return doesn't affect anything
382 case Instruction::Br: { // Handle conditional branches...
383 BranchInst *BI = (BranchInst*)I;
384 if (BI->isUnconditional())
385 return; // Unconditional branches are already handled!
386
387 InstVal &BCValue = getValueState(BI->getCondition());
388 if (BCValue.isOverdefined()) {
389 // Overdefined condition variables mean the branch could go either way.
390 markExecutable(BI->getSuccessor(0));
391 markExecutable(BI->getSuccessor(1));
392 } else if (BCValue.isConstant()) {
393 // Constant condition variables mean the branch can only go a single way.
394 ConstPoolBool *CPB = (ConstPoolBool*)BCValue.getConstant();
395 if (CPB->getValue()) // If the branch condition is TRUE...
396 markExecutable(BI->getSuccessor(0));
397 else // Else if the br cond is FALSE...
398 markExecutable(BI->getSuccessor(1));
399 }
400 return;
401 }
402
403 case Instruction::Switch: {
404 SwitchInst *SI = (SwitchInst*)I;
405 InstVal &SCValue = getValueState(SI->getCondition());
406 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe
407 for(unsigned i = 0; BasicBlock *Succ = SI->getSuccessor(i); ++i)
408 markExecutable(Succ);
409 } else if (SCValue.isConstant()) {
410 ConstPoolVal *CPV = SCValue.getConstant();
Chris Lattnerc8b25d42001-07-07 08:36:50 +0000411 // Make sure to skip the "default value" which isn't a value
412 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000413 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
Chris Lattnerc8b25d42001-07-07 08:36:50 +0000414 markExecutable(SI->getSuccessor(i));
Chris Lattner138a1242001-06-27 23:38:11 +0000415 return;
416 }
417 }
418
419 // Constant value not equal to any of the branches... must execute
420 // default branch then...
421 markExecutable(SI->getDefaultDest());
422 }
423 return;
424 }
425
426 default: break; // Handle math operators as groups.
Chris Lattnera41f50d2001-07-07 19:24:15 +0000427 } // end switch(I->getOpcode())
Chris Lattner138a1242001-06-27 23:38:11 +0000428
429
430 //===-------------------------------------------------------------------===//
431 // Handle Unary instructions...
Chris Lattner3b7bfdb2001-07-14 06:11:51 +0000432 // Also treated as unary here, are cast instructions and getelementptr
433 // instructions on struct* operands.
Chris Lattner138a1242001-06-27 23:38:11 +0000434 //
Chris Lattner3b7bfdb2001-07-14 06:11:51 +0000435 if (I->isUnaryOp() || I->getOpcode() == Instruction::Cast ||
436 (I->getOpcode() == Instruction::GetElementPtr &&
437 ((GetElementPtrInst*)I)->isStructSelector())) {
438
Chris Lattner138a1242001-06-27 23:38:11 +0000439 Value *V = I->getOperand(0);
440 InstVal &VState = getValueState(V);
441 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
442 markOverdefined(I);
443 } else if (VState.isConstant()) { // Propogate constant value
444 ConstPoolVal *Result =
Chris Lattnera41f50d2001-07-07 19:24:15 +0000445 opt::ConstantFoldUnaryInstruction(I->getOpcode(),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000446 VState.getConstant());
Chris Lattner138a1242001-06-27 23:38:11 +0000447
448 if (Result) {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000449 // This instruction constant folds!
Chris Lattner138a1242001-06-27 23:38:11 +0000450 markConstant(I, Result);
451 } else {
452 markOverdefined(I); // Don't know how to fold this instruction. :(
453 }
454 }
455 return;
456 }
457
458 //===-----------------------------------------------------------------===//
459 // Handle Binary instructions...
460 //
Chris Lattner0bd654a2001-07-08 21:18:49 +0000461 if (I->isBinaryOp() || I->getOpcode() == Instruction::Shl ||
462 I->getOpcode() == Instruction::Shr) {
Chris Lattner138a1242001-06-27 23:38:11 +0000463 Value *V1 = I->getOperand(0);
464 Value *V2 = I->getOperand(1);
465
466 InstVal &V1State = getValueState(V1);
467 InstVal &V2State = getValueState(V2);
468 if (V1State.isOverdefined() || V2State.isOverdefined()) {
469 markOverdefined(I);
470 } else if (V1State.isConstant() && V2State.isConstant()) {
471 ConstPoolVal *Result =
Chris Lattnera41f50d2001-07-07 19:24:15 +0000472 opt::ConstantFoldBinaryInstruction(I->getOpcode(),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000473 V1State.getConstant(),
474 V2State.getConstant());
Chris Lattner138a1242001-06-27 23:38:11 +0000475 if (Result) {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000476 // This instruction constant folds!
Chris Lattner138a1242001-06-27 23:38:11 +0000477 markConstant(I, Result);
478 } else {
479 markOverdefined(I); // Don't know how to fold this instruction. :(
480 }
481 }
482 return;
483 }
484
485 // Shouldn't get here... either the switch statement or one of the group
486 // handlers should have kicked in...
487 //
488 cerr << "SCCP: Don't know how to handle: " << I;
489 markOverdefined(I); // Just in case
490}
491
492
493
494// OperandChangedState - This method is invoked on all of the users of an
495// instruction that was just changed state somehow.... Based on this
496// information, we need to update the specified user of this instruction.
497//
498void SCCP::OperandChangedState(User *U) {
499 // Only instructions use other variable values!
500 Instruction *I = U->castInstructionAsserting();
501 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet!
502
503 UpdateInstruction(I);
504}
505
506
Chris Lattner138a1242001-06-27 23:38:11 +0000507// DoSparseConditionalConstantProp - Use Sparse Conditional Constant Propogation
508// to prove whether a value is constant and whether blocks are used.
509//
Chris Lattner49c8f642001-06-30 06:37:43 +0000510bool opt::DoSCCP(Method *M) {
Chris Lattnerbc7135f2001-07-15 21:43:45 +0000511 if (M->isExternal()) return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000512 SCCP S(M);
513 return S.doSCCP();
514}