1 //===- SCCP.cpp - Sparse Conditional Constant Propogation -----------------===//
3 // This file implements sparse conditional constant propogation and merging:
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
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.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Scalar/ConstantProp.h"
19 #include "llvm/ConstantHandling.h"
20 #include "llvm/Function.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/ConstantVals.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iMemory.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iOther.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/STLExtras.h"
36 // InstVal class - This class represents the different lattice values that an
37 // instruction may occupy. It is a simple class with value semantics. The
38 // potential constant value that is pointed to is owned by the constant pool
39 // for the method being optimized.
43 undefined, // This instruction has no known value
44 constant, // This instruction has a constant value
45 // Range, // This instruction is known to fall within a range
46 overdefined // This instruction has an unknown value
47 } LatticeValue; // The current lattice position
48 Constant *ConstantVal; // If Constant value, the current value
50 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
52 // markOverdefined - Return true if this is a new status to be in...
53 inline bool markOverdefined() {
54 if (LatticeValue != overdefined) {
55 LatticeValue = overdefined;
61 // markConstant - Return true if this is a new status for us...
62 inline bool markConstant(Constant *V) {
63 if (LatticeValue != constant) {
64 LatticeValue = constant;
68 assert(ConstantVal == V && "Marking constant with different value");
73 inline bool isUndefined() const { return LatticeValue == undefined; }
74 inline bool isConstant() const { return LatticeValue == constant; }
75 inline bool isOverdefined() const { return LatticeValue == overdefined; }
77 inline Constant *getConstant() const { return ConstantVal; }
82 //===----------------------------------------------------------------------===//
85 // This class does all of the work of Sparse Conditional Constant Propogation.
86 // It's public interface consists of a constructor and a doSCCP() method.
88 class SCCP : public InstVisitor<SCCP> {
89 Function *M; // The function that we are working on
91 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
92 std::map<Value*, InstVal> ValueState; // The state each value is in...
94 std::vector<Instruction*> InstWorkList;// The instruction work list
95 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
97 //===--------------------------------------------------------------------===//
98 // The public interface for this class
102 // SCCP Ctor - Save the method to operate on...
103 inline SCCP(Function *f) : M(f) {}
105 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
106 // return true if the method was modified.
109 //===--------------------------------------------------------------------===//
110 // The implementation of this class
113 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
115 // markValueOverdefined - Make a value be marked as "constant". If the value
116 // is not already a constant, add it to the instruction work list so that
117 // the users of the instruction are updated later.
119 inline bool markConstant(Instruction *I, Constant *V) {
120 //cerr << "markConstant: " << V << " = " << I;
121 if (ValueState[I].markConstant(V)) {
122 InstWorkList.push_back(I);
128 // markValueOverdefined - Make a value be marked as "overdefined". If the
129 // value is not already overdefined, add it to the instruction work list so
130 // that the users of the instruction are updated later.
132 inline bool markOverdefined(Value *V) {
133 if (ValueState[V].markOverdefined()) {
134 if (Instruction *I = dyn_cast<Instruction>(V)) {
135 //cerr << "markOverdefined: " << V;
136 InstWorkList.push_back(I); // Only instructions go on the work list
143 // getValueState - Return the InstVal object that corresponds to the value.
144 // This function is neccesary because not all values should start out in the
145 // underdefined state... Argument's should be overdefined, and
146 // constants should be marked as constants. If a value is not known to be an
147 // Instruction object, then use this accessor to get its value from the map.
149 inline InstVal &getValueState(Value *V) {
150 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
151 if (I != ValueState.end()) return I->second; // Common case, in the map
153 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
154 ValueState[CPV].markConstant(CPV);
155 } else if (isa<Argument>(V)) { // Arguments are overdefined
156 ValueState[V].markOverdefined();
158 // All others are underdefined by default...
159 return ValueState[V];
162 // markExecutable - Mark a basic block as executable, adding it to the BB
163 // work list if it is not already executable...
165 void markExecutable(BasicBlock *BB) {
166 if (BBExecutable.count(BB)) return;
167 //cerr << "Marking BB Executable: " << BB;
168 BBExecutable.insert(BB); // Basic block is executable!
169 BBWorkList.push_back(BB); // Add the block to the work list!
173 // visit implementations - Something changed in this instruction... Either an
174 // operand made a transition, or the instruction is newly executable. Change
175 // the value type of I to reflect these changes if appropriate.
177 void visitPHINode(PHINode *I);
180 void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
181 void visitBranchInst(BranchInst *I);
182 void visitSwitchInst(SwitchInst *I);
184 void visitUnaryOperator(Instruction *I);
185 void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
186 void visitBinaryOperator(Instruction *I);
187 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
189 // Instructions that cannot be folded away...
190 void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
191 void visitCallInst (Instruction *I) { markOverdefined(I); }
192 void visitInvokeInst (Instruction *I) { markOverdefined(I); }
193 void visitAllocationInst(Instruction *I) { markOverdefined(I); }
194 void visitFreeInst (Instruction *I) { markOverdefined(I); }
196 void visitInstruction(Instruction *I) {
197 // If a new instruction is added to LLVM that we don't handle...
198 cerr << "SCCP: Don't know how to handle: " << I;
199 markOverdefined(I); // Just in case
202 // OperandChangedState - This method is invoked on all of the users of an
203 // instruction that was just changed state somehow.... Based on this
204 // information, we need to update the specified user of this instruction.
206 void OperandChangedState(User *U);
210 //===----------------------------------------------------------------------===//
211 // SCCP Class Implementation
214 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
215 // return true if the method was modified.
217 bool SCCP::doSCCP() {
218 // Mark the first block of the method as being executable...
219 markExecutable(M->front());
221 // Process the work lists until their are empty!
222 while (!BBWorkList.empty() || !InstWorkList.empty()) {
223 // Process the instruction work list...
224 while (!InstWorkList.empty()) {
225 Instruction *I = InstWorkList.back();
226 InstWorkList.pop_back();
228 //cerr << "\nPopped off I-WL: " << I;
231 // "I" got into the work list because it either made the transition from
232 // bottom to constant, or to Overdefined.
234 // Update all of the users of this instruction's value...
236 for_each(I->use_begin(), I->use_end(),
237 bind_obj(this, &SCCP::OperandChangedState));
240 // Process the basic block work list...
241 while (!BBWorkList.empty()) {
242 BasicBlock *BB = BBWorkList.back();
243 BBWorkList.pop_back();
245 //cerr << "\nPopped off BBWL: " << BB;
247 // If this block only has a single successor, mark it as executable as
248 // well... if not, terminate the do loop.
250 if (BB->getTerminator()->getNumSuccessors() == 1)
251 markExecutable(BB->getTerminator()->getSuccessor(0));
253 // Notify all instructions in this basic block that they are newly
260 for (Function::iterator BBI = M->begin(), BBEnd = M->end();
262 if (!BBExecutable.count(*BBI))
263 cerr << "BasicBlock Dead:" << *BBI;
267 // Iterate over all of the instructions in a method, replacing them with
268 // constants if we have found them to be of constant values.
270 bool MadeChanges = false;
271 for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
272 BasicBlock *BB = *MI;
273 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
274 Instruction *Inst = *BI;
275 InstVal &IV = ValueState[Inst];
276 if (IV.isConstant()) {
277 Constant *Const = IV.getConstant();
278 // cerr << "Constant: " << Inst << " is: " << Const;
280 // Replaces all of the uses of a variable with uses of the constant.
281 Inst->replaceAllUsesWith(Const);
283 // Remove the operator from the list of definitions...
284 BB->getInstList().remove(BI);
286 // The new constant inherits the old name of the operator...
287 if (Inst->hasName() && !Const->hasName())
288 Const->setName(Inst->getName(), M->getSymbolTableSure());
290 // Delete the operator now...
293 // Hey, we just changed something!
295 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) {
296 MadeChanges |= ConstantFoldTerminator(BB, BI, TI);
303 // Merge identical constants last: this is important because we may have just
304 // introduced constants that already exist, and we don't want to pollute later
305 // stages with extraneous constants.
311 // visit Implementations - Something changed in this instruction... Either an
312 // operand made a transition, or the instruction is newly executable. Change
313 // the value type of I to reflect these changes if appropriate. This method
314 // makes sure to do the following actions:
316 // 1. If a phi node merges two constants in, and has conflicting value coming
317 // from different branches, or if the PHI node merges in an overdefined
318 // value, then the PHI node becomes overdefined.
319 // 2. If a phi node merges only constants in, and they all agree on value, the
320 // PHI node becomes a constant value equal to that.
321 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
322 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
323 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
324 // 6. If a conditional branch has a value that is constant, make the selected
325 // destination executable
326 // 7. If a conditional branch has a value that is overdefined, make all
327 // successors executable.
330 void SCCP::visitPHINode(PHINode *PN) {
331 unsigned NumValues = PN->getNumIncomingValues(), i;
332 InstVal *OperandIV = 0;
334 // Look at all of the executable operands of the PHI node. If any of them
335 // are overdefined, the PHI becomes overdefined as well. If they are all
336 // constant, and they agree with each other, the PHI becomes the identical
337 // constant. If they are constant and don't agree, the PHI is overdefined.
338 // If there are no executable operands, the PHI remains undefined.
340 for (i = 0; i < NumValues; ++i) {
341 if (BBExecutable.count(PN->getIncomingBlock(i))) {
342 InstVal &IV = getValueState(PN->getIncomingValue(i));
343 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
344 if (IV.isOverdefined()) { // PHI node becomes overdefined!
349 if (OperandIV == 0) { // Grab the first value...
351 } else { // Another value is being merged in!
352 // There is already a reachable operand. If we conflict with it,
353 // then the PHI node becomes overdefined. If we agree with it, we
356 // Check to see if there are two different constants merging...
357 if (IV.getConstant() != OperandIV->getConstant()) {
358 // Yes there is. This means the PHI node is not constant.
359 // You must be overdefined poor PHI.
361 markOverdefined(PN); // The PHI node now becomes overdefined
362 return; // I'm done analyzing you
368 // If we exited the loop, this means that the PHI node only has constant
369 // arguments that agree with each other(and OperandIV is a pointer to one
370 // of their InstVal's) or OperandIV is null because there are no defined
371 // incoming arguments. If this is the case, the PHI remains undefined.
374 assert(OperandIV->isConstant() && "Should only be here for constants!");
375 markConstant(PN, OperandIV->getConstant()); // Aquire operand value
379 void SCCP::visitBranchInst(BranchInst *BI) {
380 if (BI->isUnconditional())
381 return; // Unconditional branches are already handled!
383 InstVal &BCValue = getValueState(BI->getCondition());
384 if (BCValue.isOverdefined()) {
385 // Overdefined condition variables mean the branch could go either way.
386 markExecutable(BI->getSuccessor(0));
387 markExecutable(BI->getSuccessor(1));
388 } else if (BCValue.isConstant()) {
389 // Constant condition variables mean the branch can only go a single way.
390 if (BCValue.getConstant() == ConstantBool::True)
391 markExecutable(BI->getSuccessor(0));
393 markExecutable(BI->getSuccessor(1));
397 void SCCP::visitSwitchInst(SwitchInst *SI) {
398 InstVal &SCValue = getValueState(SI->getCondition());
399 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe
400 for(unsigned i = 0; BasicBlock *Succ = SI->getSuccessor(i); ++i)
401 markExecutable(Succ);
402 } else if (SCValue.isConstant()) {
403 Constant *CPV = SCValue.getConstant();
404 // Make sure to skip the "default value" which isn't a value
405 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
406 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
407 markExecutable(SI->getSuccessor(i));
412 // Constant value not equal to any of the branches... must execute
413 // default branch then...
414 markExecutable(SI->getDefaultDest());
418 void SCCP::visitUnaryOperator(Instruction *I) {
419 Value *V = I->getOperand(0);
420 InstVal &VState = getValueState(V);
421 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
423 } else if (VState.isConstant()) { // Propogate constant value
424 Constant *Result = isa<CastInst>(I)
425 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
426 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
429 // This instruction constant folds!
430 markConstant(I, Result);
432 markOverdefined(I); // Don't know how to fold this instruction. :(
437 // Handle BinaryOperators and Shift Instructions...
438 void SCCP::visitBinaryOperator(Instruction *I) {
439 InstVal &V1State = getValueState(I->getOperand(0));
440 InstVal &V2State = getValueState(I->getOperand(1));
441 if (V1State.isOverdefined() || V2State.isOverdefined()) {
443 } else if (V1State.isConstant() && V2State.isConstant()) {
444 Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(),
445 V1State.getConstant(),
446 V2State.getConstant());
448 markConstant(I, Result); // This instruction constant fold!s
450 markOverdefined(I); // Don't know how to fold this instruction. :(
454 // OperandChangedState - This method is invoked on all of the users of an
455 // instruction that was just changed state somehow.... Based on this
456 // information, we need to update the specified user of this instruction.
458 void SCCP::OperandChangedState(User *U) {
459 // Only instructions use other variable values!
460 Instruction *I = cast<Instruction>(U);
461 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet!
467 // SCCPPass - Use Sparse Conditional Constant Propogation
468 // to prove whether a value is constant and whether blocks are used.
470 struct SCCPPass : public MethodPass {
471 inline bool runOnMethod(Function *F) {
478 Pass *createSCCPPass() {
479 return new SCCPPass();