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/iPHINode.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "Support/STLExtras.h"
33 #if 0 // Enable this to get SCCP debug output
34 #define DEBUG_SCCP(X) X
39 // InstVal class - This class represents the different lattice values that an
40 // instruction may occupy. It is a simple class with value semantics.
45 undefined, // This instruction has no known value
46 constant, // This instruction has a constant value
47 // Range, // This instruction is known to fall within a range
48 overdefined // This instruction has an unknown value
49 } LatticeValue; // The current lattice position
50 Constant *ConstantVal; // If Constant value, the current value
52 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
54 // markOverdefined - Return true if this is a new status to be in...
55 inline bool markOverdefined() {
56 if (LatticeValue != overdefined) {
57 LatticeValue = overdefined;
63 // markConstant - Return true if this is a new status for us...
64 inline bool markConstant(Constant *V) {
65 if (LatticeValue != constant) {
66 LatticeValue = constant;
70 assert(ConstantVal == V && "Marking constant with different value");
75 inline bool isUndefined() const { return LatticeValue == undefined; }
76 inline bool isConstant() const { return LatticeValue == constant; }
77 inline bool isOverdefined() const { return LatticeValue == overdefined; }
79 inline Constant *getConstant() const { return ConstantVal; }
82 } // end anonymous namespace
85 //===----------------------------------------------------------------------===//
88 // This class does all of the work of Sparse Conditional Constant Propogation.
91 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
92 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
93 std::map<Value*, InstVal> ValueState; // The state each value is in...
95 std::set<Instruction*> InstWorkList;// The instruction work list
96 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
99 const char *getPassName() const {
100 return "Sparse Conditional Constant Propogation";
103 // runOnFunction - Run the Sparse Conditional Constant Propogation algorithm,
104 // and return true if the function was modified.
106 bool runOnFunction(Function *F);
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 //===--------------------------------------------------------------------===//
114 // The implementation of this class
117 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
119 // markValueOverdefined - Make a value be marked as "constant". If the value
120 // is not already a constant, add it to the instruction work list so that
121 // the users of the instruction are updated later.
123 inline bool markConstant(Instruction *I, Constant *V) {
124 DEBUG_SCCP(cerr << "markConstant: " << V << " = " << I);
126 if (ValueState[I].markConstant(V)) {
127 InstWorkList.insert(I);
133 // markValueOverdefined - Make a value be marked as "overdefined". If the
134 // value is not already overdefined, add it to the instruction work list so
135 // that the users of the instruction are updated later.
137 inline bool markOverdefined(Value *V) {
138 if (ValueState[V].markOverdefined()) {
139 if (Instruction *I = dyn_cast<Instruction>(V)) {
140 DEBUG_SCCP(cerr << "markOverdefined: " << V);
141 InstWorkList.insert(I); // Only instructions go on the work list
148 // getValueState - Return the InstVal object that corresponds to the value.
149 // This function is neccesary because not all values should start out in the
150 // underdefined state... Argument's should be overdefined, and
151 // constants should be marked as constants. If a value is not known to be an
152 // Instruction object, then use this accessor to get its value from the map.
154 inline InstVal &getValueState(Value *V) {
155 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
156 if (I != ValueState.end()) return I->second; // Common case, in the map
158 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
159 ValueState[CPV].markConstant(CPV);
160 } else if (isa<Argument>(V)) { // Arguments are overdefined
161 ValueState[V].markOverdefined();
163 // All others are underdefined by default...
164 return ValueState[V];
167 // markExecutable - Mark a basic block as executable, adding it to the BB
168 // work list if it is not already executable...
170 void markExecutable(BasicBlock *BB) {
171 if (BBExecutable.count(BB)) return;
172 DEBUG_SCCP(cerr << "Marking BB Executable: " << BB);
173 BBExecutable.insert(BB); // Basic block is executable!
174 BBWorkList.push_back(BB); // Add the block to the work list!
178 // visit implementations - Something changed in this instruction... Either an
179 // operand made a transition, or the instruction is newly executable. Change
180 // the value type of I to reflect these changes if appropriate.
182 void visitPHINode(PHINode *I);
185 void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
186 void visitTerminatorInst(TerminatorInst *TI);
188 void visitUnaryOperator(Instruction *I);
189 void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
190 void visitBinaryOperator(Instruction *I);
191 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
193 // Instructions that cannot be folded away...
194 void visitStoreInst (Instruction *I) { /*returns void*/ }
195 void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
196 void visitCallInst (Instruction *I) { markOverdefined(I); }
197 void visitInvokeInst (Instruction *I) { markOverdefined(I); }
198 void visitAllocationInst(Instruction *I) { markOverdefined(I); }
199 void visitFreeInst (Instruction *I) { /*returns void*/ }
201 void visitInstruction(Instruction *I) {
202 // If a new instruction is added to LLVM that we don't handle...
203 cerr << "SCCP: Don't know how to handle: " << I;
204 markOverdefined(I); // Just in case
207 // getFeasibleSuccessors - Return a vector of booleans to indicate which
208 // successors are reachable from a given terminator instruction.
210 void getFeasibleSuccessors(TerminatorInst *I, std::vector<bool> &Succs);
212 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
213 // block to the 'To' basic block is currently feasible...
215 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
217 // OperandChangedState - This method is invoked on all of the users of an
218 // instruction that was just changed state somehow.... Based on this
219 // information, we need to update the specified user of this instruction.
221 void OperandChangedState(User *U) {
222 // Only instructions use other variable values!
223 Instruction *I = cast<Instruction>(U);
224 if (!BBExecutable.count(I->getParent())) return;// Inst not executable yet!
228 } // end anonymous namespace
231 // createSCCPPass - This is the public interface to this file...
233 Pass *createSCCPPass() {
239 //===----------------------------------------------------------------------===//
240 // SCCP Class Implementation
243 // runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm,
244 // and return true if the function was modified.
246 bool SCCP::runOnFunction(Function *F) {
247 // Mark the first block of the function as being executable...
248 markExecutable(F->front());
250 // Process the work lists until their are empty!
251 while (!BBWorkList.empty() || !InstWorkList.empty()) {
252 // Process the instruction work list...
253 while (!InstWorkList.empty()) {
254 Instruction *I = *InstWorkList.begin();
255 InstWorkList.erase(InstWorkList.begin());
257 DEBUG_SCCP(cerr << "\nPopped off I-WL: " << I);
260 // "I" got into the work list because it either made the transition from
261 // bottom to constant, or to Overdefined.
263 // Update all of the users of this instruction's value...
265 for_each(I->use_begin(), I->use_end(),
266 bind_obj(this, &SCCP::OperandChangedState));
269 // Process the basic block work list...
270 while (!BBWorkList.empty()) {
271 BasicBlock *BB = BBWorkList.back();
272 BBWorkList.pop_back();
274 DEBUG_SCCP(cerr << "\nPopped off BBWL: " << BB);
276 // If this block only has a single successor, mark it as executable as
277 // well... if not, terminate the do loop.
279 if (BB->getTerminator()->getNumSuccessors() == 1)
280 markExecutable(BB->getTerminator()->getSuccessor(0));
282 // Notify all instructions in this basic block that they are newly
289 for (Function::iterator BBI = F->begin(), BBEnd = F->end();
291 if (!BBExecutable.count(*BBI))
292 cerr << "BasicBlock Dead:" << *BBI;
296 // Iterate over all of the instructions in a function, replacing them with
297 // constants if we have found them to be of constant values.
299 bool MadeChanges = false;
300 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) {
301 BasicBlock *BB = *FI;
302 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
303 Instruction *Inst = *BI;
304 InstVal &IV = ValueState[Inst];
305 if (IV.isConstant()) {
306 Constant *Const = IV.getConstant();
307 DEBUG_SCCP(cerr << "Constant: " << Inst << " is: " << Const);
309 // Replaces all of the uses of a variable with uses of the constant.
310 Inst->replaceAllUsesWith(Const);
312 // Remove the operator from the list of definitions... and delete it.
313 delete BB->getInstList().remove(BI);
315 // Hey, we just changed something!
323 // Reset state so that the next invocation will have empty data structures
324 BBExecutable.clear();
331 // getFeasibleSuccessors - Return a vector of booleans to indicate which
332 // successors are reachable from a given terminator instruction.
334 void SCCP::getFeasibleSuccessors(TerminatorInst *TI, std::vector<bool> &Succs) {
335 assert(Succs.size() == TI->getNumSuccessors() && "Succs vector wrong size!");
336 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
337 if (BI->isUnconditional()) {
340 InstVal &BCValue = getValueState(BI->getCondition());
341 if (BCValue.isOverdefined()) {
342 // Overdefined condition variables mean the branch could go either way.
343 Succs[0] = Succs[1] = true;
344 } else if (BCValue.isConstant()) {
345 // Constant condition variables mean the branch can only go a single way
346 Succs[BCValue.getConstant() == ConstantBool::False] = true;
349 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
350 // Invoke instructions successors are always executable.
351 Succs[0] = Succs[1] = true;
352 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
353 InstVal &SCValue = getValueState(SI->getCondition());
354 if (SCValue.isOverdefined()) { // Overdefined condition?
355 // All destinations are executable!
356 Succs.assign(TI->getNumSuccessors(), true);
357 } else if (SCValue.isConstant()) {
358 Constant *CPV = SCValue.getConstant();
359 // Make sure to skip the "default value" which isn't a value
360 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
361 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
367 // Constant value not equal to any of the branches... must execute
368 // default branch then...
372 cerr << "SCCP: Don't know how to handle: " << TI;
373 Succs.assign(TI->getNumSuccessors(), true);
378 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
379 // block to the 'To' basic block is currently feasible...
381 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
382 assert(BBExecutable.count(To) && "Dest should always be alive!");
384 // Make sure the source basic block is executable!!
385 if (!BBExecutable.count(From)) return false;
387 // Check to make sure this edge itself is actually feasible now...
388 TerminatorInst *FT = From->getTerminator();
389 std::vector<bool> SuccFeasible(FT->getNumSuccessors());
390 getFeasibleSuccessors(FT, SuccFeasible);
392 // Check all edges from From to To. If any are feasible, return true.
393 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
394 if (FT->getSuccessor(i) == To && SuccFeasible[i])
397 // Otherwise, none of the edges are actually feasible at this time...
401 // visit Implementations - Something changed in this instruction... Either an
402 // operand made a transition, or the instruction is newly executable. Change
403 // the value type of I to reflect these changes if appropriate. This method
404 // makes sure to do the following actions:
406 // 1. If a phi node merges two constants in, and has conflicting value coming
407 // from different branches, or if the PHI node merges in an overdefined
408 // value, then the PHI node becomes overdefined.
409 // 2. If a phi node merges only constants in, and they all agree on value, the
410 // PHI node becomes a constant value equal to that.
411 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
412 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
413 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
414 // 6. If a conditional branch has a value that is constant, make the selected
415 // destination executable
416 // 7. If a conditional branch has a value that is overdefined, make all
417 // successors executable.
420 void SCCP::visitPHINode(PHINode *PN) {
421 unsigned NumValues = PN->getNumIncomingValues(), i;
422 InstVal *OperandIV = 0;
424 // Look at all of the executable operands of the PHI node. If any of them
425 // are overdefined, the PHI becomes overdefined as well. If they are all
426 // constant, and they agree with each other, the PHI becomes the identical
427 // constant. If they are constant and don't agree, the PHI is overdefined.
428 // If there are no executable operands, the PHI remains undefined.
430 for (i = 0; i < NumValues; ++i) {
431 if (isEdgeFeasible(PN->getIncomingBlock(i), PN->getParent())) {
432 InstVal &IV = getValueState(PN->getIncomingValue(i));
433 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
434 if (IV.isOverdefined()) { // PHI node becomes overdefined!
439 if (OperandIV == 0) { // Grab the first value...
441 } else { // Another value is being merged in!
442 // There is already a reachable operand. If we conflict with it,
443 // then the PHI node becomes overdefined. If we agree with it, we
446 // Check to see if there are two different constants merging...
447 if (IV.getConstant() != OperandIV->getConstant()) {
448 // Yes there is. This means the PHI node is not constant.
449 // You must be overdefined poor PHI.
451 markOverdefined(PN); // The PHI node now becomes overdefined
452 return; // I'm done analyzing you
458 // If we exited the loop, this means that the PHI node only has constant
459 // arguments that agree with each other(and OperandIV is a pointer to one
460 // of their InstVal's) or OperandIV is null because there are no defined
461 // incoming arguments. If this is the case, the PHI remains undefined.
464 assert(OperandIV->isConstant() && "Should only be here for constants!");
465 markConstant(PN, OperandIV->getConstant()); // Aquire operand value
469 void SCCP::visitTerminatorInst(TerminatorInst *TI) {
470 std::vector<bool> SuccFeasible(TI->getNumSuccessors());
471 getFeasibleSuccessors(TI, SuccFeasible);
473 // Mark all feasible successors executable...
474 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
476 markExecutable(TI->getSuccessor(i));
479 void SCCP::visitUnaryOperator(Instruction *I) {
480 Value *V = I->getOperand(0);
481 InstVal &VState = getValueState(V);
482 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
484 } else if (VState.isConstant()) { // Propogate constant value
485 Constant *Result = isa<CastInst>(I)
486 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
487 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
490 // This instruction constant folds!
491 markConstant(I, Result);
493 markOverdefined(I); // Don't know how to fold this instruction. :(
498 // Handle BinaryOperators and Shift Instructions...
499 void SCCP::visitBinaryOperator(Instruction *I) {
500 InstVal &V1State = getValueState(I->getOperand(0));
501 InstVal &V2State = getValueState(I->getOperand(1));
502 if (V1State.isOverdefined() || V2State.isOverdefined()) {
504 } else if (V1State.isConstant() && V2State.isConstant()) {
505 Constant *Result = 0;
506 if (isa<BinaryOperator>(I))
507 Result = ConstantFoldBinaryInstruction(I->getOpcode(),
508 V1State.getConstant(),
509 V2State.getConstant());
510 else if (isa<ShiftInst>(I))
511 Result = ConstantFoldShiftInstruction(I->getOpcode(),
512 V1State.getConstant(),
513 V2State.getConstant());
515 markConstant(I, Result); // This instruction constant folds!
517 markOverdefined(I); // Don't know how to fold this instruction. :(