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/iPHINode.h"
23 #include "llvm/iMemory.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/iOther.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/STLExtras.h"
34 #if 0 // Enable this to get SCCP debug output
35 #define DEBUG_SCCP(X) X
40 // InstVal class - This class represents the different lattice values that an
41 // instruction may occupy. It is a simple class with value semantics.
46 undefined, // This instruction has no known value
47 constant, // This instruction has a constant value
48 // Range, // This instruction is known to fall within a range
49 overdefined // This instruction has an unknown value
50 } LatticeValue; // The current lattice position
51 Constant *ConstantVal; // If Constant value, the current value
53 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
55 // markOverdefined - Return true if this is a new status to be in...
56 inline bool markOverdefined() {
57 if (LatticeValue != overdefined) {
58 LatticeValue = overdefined;
64 // markConstant - Return true if this is a new status for us...
65 inline bool markConstant(Constant *V) {
66 if (LatticeValue != constant) {
67 LatticeValue = constant;
71 assert(ConstantVal == V && "Marking constant with different value");
76 inline bool isUndefined() const { return LatticeValue == undefined; }
77 inline bool isConstant() const { return LatticeValue == constant; }
78 inline bool isOverdefined() const { return LatticeValue == overdefined; }
80 inline Constant *getConstant() const { return ConstantVal; }
83 } // end anonymous namespace
86 //===----------------------------------------------------------------------===//
89 // This class does all of the work of Sparse Conditional Constant Propogation.
92 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
93 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
94 std::map<Value*, InstVal> ValueState; // The state each value is in...
96 std::vector<Instruction*> InstWorkList;// The instruction work list
97 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
100 const char *getPassName() const {
101 return "Sparse Conditional Constant Propogation";
104 // runOnFunction - Run the Sparse Conditional Constant Propogation algorithm,
105 // and return true if the function was modified.
107 bool runOnFunction(Function *F);
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
114 //===--------------------------------------------------------------------===//
115 // The implementation of this class
118 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
120 // markValueOverdefined - Make a value be marked as "constant". If the value
121 // is not already a constant, add it to the instruction work list so that
122 // the users of the instruction are updated later.
124 inline bool markConstant(Instruction *I, Constant *V) {
125 DEBUG_SCCP(cerr << "markConstant: " << V << " = " << I);
127 if (ValueState[I].markConstant(V)) {
128 InstWorkList.push_back(I);
134 // markValueOverdefined - Make a value be marked as "overdefined". If the
135 // value is not already overdefined, add it to the instruction work list so
136 // that the users of the instruction are updated later.
138 inline bool markOverdefined(Value *V) {
139 if (ValueState[V].markOverdefined()) {
140 if (Instruction *I = dyn_cast<Instruction>(V)) {
141 DEBUG_SCCP(cerr << "markOverdefined: " << V);
142 InstWorkList.push_back(I); // Only instructions go on the work list
149 // getValueState - Return the InstVal object that corresponds to the value.
150 // This function is neccesary because not all values should start out in the
151 // underdefined state... Argument's should be overdefined, and
152 // constants should be marked as constants. If a value is not known to be an
153 // Instruction object, then use this accessor to get its value from the map.
155 inline InstVal &getValueState(Value *V) {
156 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
157 if (I != ValueState.end()) return I->second; // Common case, in the map
159 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
160 ValueState[CPV].markConstant(CPV);
161 } else if (isa<Argument>(V)) { // Arguments are overdefined
162 ValueState[V].markOverdefined();
164 // All others are underdefined by default...
165 return ValueState[V];
168 // markExecutable - Mark a basic block as executable, adding it to the BB
169 // work list if it is not already executable...
171 void markExecutable(BasicBlock *BB) {
172 if (BBExecutable.count(BB)) return;
173 DEBUG_SCCP(cerr << "Marking BB Executable: " << BB);
174 BBExecutable.insert(BB); // Basic block is executable!
175 BBWorkList.push_back(BB); // Add the block to the work list!
179 // visit implementations - Something changed in this instruction... Either an
180 // operand made a transition, or the instruction is newly executable. Change
181 // the value type of I to reflect these changes if appropriate.
183 void visitPHINode(PHINode *I);
186 void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
187 void visitTerminatorInst(TerminatorInst *TI);
189 void visitUnaryOperator(Instruction *I);
190 void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
191 void visitBinaryOperator(Instruction *I);
192 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
194 // Instructions that cannot be folded away...
195 void visitStoreInst (Instruction *I) { /*returns void*/ }
196 void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
197 void visitCallInst (Instruction *I) { markOverdefined(I); }
198 void visitInvokeInst (Instruction *I) { markOverdefined(I); }
199 void visitAllocationInst(Instruction *I) { markOverdefined(I); }
200 void visitFreeInst (Instruction *I) { /*returns void*/ }
202 void visitInstruction(Instruction *I) {
203 // If a new instruction is added to LLVM that we don't handle...
204 cerr << "SCCP: Don't know how to handle: " << I;
205 markOverdefined(I); // Just in case
208 // getFeasibleSuccessors - Return a vector of booleans to indicate which
209 // successors are reachable from a given terminator instruction.
211 void getFeasibleSuccessors(TerminatorInst *I, std::vector<bool> &Succs);
213 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
214 // block to the 'To' basic block is currently feasible...
216 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
218 // OperandChangedState - This method is invoked on all of the users of an
219 // instruction that was just changed state somehow.... Based on this
220 // information, we need to update the specified user of this instruction.
222 void OperandChangedState(User *U) {
223 // Only instructions use other variable values!
224 Instruction *I = cast<Instruction>(U);
225 if (!BBExecutable.count(I->getParent())) return;// Inst not executable yet!
229 } // end anonymous namespace
232 // createSCCPPass - This is the public interface to this file...
234 Pass *createSCCPPass() {
240 //===----------------------------------------------------------------------===//
241 // SCCP Class Implementation
244 // runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm,
245 // and return true if the function was modified.
247 bool SCCP::runOnFunction(Function *F) {
248 // Mark the first block of the function as being executable...
249 markExecutable(F->front());
251 // Process the work lists until their are empty!
252 while (!BBWorkList.empty() || !InstWorkList.empty()) {
253 // Process the instruction work list...
254 while (!InstWorkList.empty()) {
255 Instruction *I = InstWorkList.back();
256 InstWorkList.pop_back();
258 DEBUG_SCCP(cerr << "\nPopped off I-WL: " << I);
261 // "I" got into the work list because it either made the transition from
262 // bottom to constant, or to Overdefined.
264 // Update all of the users of this instruction's value...
266 for_each(I->use_begin(), I->use_end(),
267 bind_obj(this, &SCCP::OperandChangedState));
270 // Process the basic block work list...
271 while (!BBWorkList.empty()) {
272 BasicBlock *BB = BBWorkList.back();
273 BBWorkList.pop_back();
275 DEBUG_SCCP(cerr << "\nPopped off BBWL: " << BB);
277 // If this block only has a single successor, mark it as executable as
278 // well... if not, terminate the do loop.
280 if (BB->getTerminator()->getNumSuccessors() == 1)
281 markExecutable(BB->getTerminator()->getSuccessor(0));
283 // Notify all instructions in this basic block that they are newly
290 for (Function::iterator BBI = F->begin(), BBEnd = F->end();
292 if (!BBExecutable.count(*BBI))
293 cerr << "BasicBlock Dead:" << *BBI;
297 // Iterate over all of the instructions in a function, replacing them with
298 // constants if we have found them to be of constant values.
300 bool MadeChanges = false;
301 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) {
302 BasicBlock *BB = *FI;
303 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
304 Instruction *Inst = *BI;
305 InstVal &IV = ValueState[Inst];
306 if (IV.isConstant()) {
307 Constant *Const = IV.getConstant();
308 DEBUG_SCCP(cerr << "Constant: " << Inst << " is: " << Const);
310 // Replaces all of the uses of a variable with uses of the constant.
311 Inst->replaceAllUsesWith(Const);
313 // Remove the operator from the list of definitions... and delete it.
314 delete BB->getInstList().remove(BI);
316 // Hey, we just changed something!
324 // Reset state so that the next invocation will have empty data structures
325 BBExecutable.clear();
332 // getFeasibleSuccessors - Return a vector of booleans to indicate which
333 // successors are reachable from a given terminator instruction.
335 void SCCP::getFeasibleSuccessors(TerminatorInst *TI, std::vector<bool> &Succs) {
336 assert(Succs.size() == TI->getNumSuccessors() && "Succs vector wrong size!");
337 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
338 if (BI->isUnconditional()) {
341 InstVal &BCValue = getValueState(BI->getCondition());
342 if (BCValue.isOverdefined()) {
343 // Overdefined condition variables mean the branch could go either way.
344 Succs[0] = Succs[1] = true;
345 } else if (BCValue.isConstant()) {
346 // Constant condition variables mean the branch can only go a single way
347 Succs[BCValue.getConstant() == ConstantBool::False] = true;
350 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
351 // Invoke instructions successors are always executable.
352 Succs[0] = Succs[1] = true;
353 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
354 InstVal &SCValue = getValueState(SI->getCondition());
355 if (SCValue.isOverdefined()) { // Overdefined condition?
356 // All destinations are executable!
357 Succs.assign(TI->getNumSuccessors(), true);
358 } else if (SCValue.isConstant()) {
359 Constant *CPV = SCValue.getConstant();
360 // Make sure to skip the "default value" which isn't a value
361 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
362 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
368 // Constant value not equal to any of the branches... must execute
369 // default branch then...
373 cerr << "SCCP: Don't know how to handle: " << TI;
374 Succs.assign(TI->getNumSuccessors(), true);
379 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
380 // block to the 'To' basic block is currently feasible...
382 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
383 assert(BBExecutable.count(To) && "Dest should always be alive!");
385 // Make sure the source basic block is executable!!
386 if (!BBExecutable.count(From)) return false;
388 // Check to make sure this edge itself is actually feasible now...
389 TerminatorInst *FT = From->getTerminator();
390 std::vector<bool> SuccFeasible(FT->getNumSuccessors());
391 getFeasibleSuccessors(FT, SuccFeasible);
393 // Check all edges from From to To. If any are feasible, return true.
394 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
395 if (FT->getSuccessor(i) == To && SuccFeasible[i])
398 // Otherwise, none of the edges are actually feasible at this time...
402 // visit Implementations - Something changed in this instruction... Either an
403 // operand made a transition, or the instruction is newly executable. Change
404 // the value type of I to reflect these changes if appropriate. This method
405 // makes sure to do the following actions:
407 // 1. If a phi node merges two constants in, and has conflicting value coming
408 // from different branches, or if the PHI node merges in an overdefined
409 // value, then the PHI node becomes overdefined.
410 // 2. If a phi node merges only constants in, and they all agree on value, the
411 // PHI node becomes a constant value equal to that.
412 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
413 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
414 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
415 // 6. If a conditional branch has a value that is constant, make the selected
416 // destination executable
417 // 7. If a conditional branch has a value that is overdefined, make all
418 // successors executable.
421 void SCCP::visitPHINode(PHINode *PN) {
422 unsigned NumValues = PN->getNumIncomingValues(), i;
423 InstVal *OperandIV = 0;
425 // Look at all of the executable operands of the PHI node. If any of them
426 // are overdefined, the PHI becomes overdefined as well. If they are all
427 // constant, and they agree with each other, the PHI becomes the identical
428 // constant. If they are constant and don't agree, the PHI is overdefined.
429 // If there are no executable operands, the PHI remains undefined.
431 for (i = 0; i < NumValues; ++i) {
432 if (isEdgeFeasible(PN->getIncomingBlock(i), PN->getParent())) {
433 InstVal &IV = getValueState(PN->getIncomingValue(i));
434 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
435 if (IV.isOverdefined()) { // PHI node becomes overdefined!
440 if (OperandIV == 0) { // Grab the first value...
442 } else { // Another value is being merged in!
443 // There is already a reachable operand. If we conflict with it,
444 // then the PHI node becomes overdefined. If we agree with it, we
447 // Check to see if there are two different constants merging...
448 if (IV.getConstant() != OperandIV->getConstant()) {
449 // Yes there is. This means the PHI node is not constant.
450 // You must be overdefined poor PHI.
452 markOverdefined(PN); // The PHI node now becomes overdefined
453 return; // I'm done analyzing you
459 // If we exited the loop, this means that the PHI node only has constant
460 // arguments that agree with each other(and OperandIV is a pointer to one
461 // of their InstVal's) or OperandIV is null because there are no defined
462 // incoming arguments. If this is the case, the PHI remains undefined.
465 assert(OperandIV->isConstant() && "Should only be here for constants!");
466 markConstant(PN, OperandIV->getConstant()); // Aquire operand value
470 void SCCP::visitTerminatorInst(TerminatorInst *TI) {
471 std::vector<bool> SuccFeasible(TI->getNumSuccessors());
472 getFeasibleSuccessors(TI, SuccFeasible);
474 // Mark all feasible successors executable...
475 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
477 markExecutable(TI->getSuccessor(i));
480 void SCCP::visitUnaryOperator(Instruction *I) {
481 Value *V = I->getOperand(0);
482 InstVal &VState = getValueState(V);
483 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
485 } else if (VState.isConstant()) { // Propogate constant value
486 Constant *Result = isa<CastInst>(I)
487 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
488 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
491 // This instruction constant folds!
492 markConstant(I, Result);
494 markOverdefined(I); // Don't know how to fold this instruction. :(
499 // Handle BinaryOperators and Shift Instructions...
500 void SCCP::visitBinaryOperator(Instruction *I) {
501 InstVal &V1State = getValueState(I->getOperand(0));
502 InstVal &V2State = getValueState(I->getOperand(1));
503 if (V1State.isOverdefined() || V2State.isOverdefined()) {
505 } else if (V1State.isConstant() && V2State.isConstant()) {
506 Constant *Result = 0;
507 if (isa<BinaryOperator>(I))
508 Result = ConstantFoldBinaryInstruction(I->getOpcode(),
509 V1State.getConstant(),
510 V2State.getConstant());
511 else if (isa<ShiftInst>(I))
512 Result = ConstantFoldShiftInstruction(I->getOpcode(),
513 V1State.getConstant(),
514 V2State.getConstant());
516 markConstant(I, Result); // This instruction constant folds!
518 markOverdefined(I); // Don't know how to fold this instruction. :(