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 {
109 // FIXME: SCCP does not preserve the CFG because it folds terminators!
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.insert(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.insert(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 visitBranchInst(BranchInst *I);
188 void visitInvokeInst(InvokeInst *I);
189 void visitSwitchInst(SwitchInst *I);
191 void visitUnaryOperator(Instruction *I);
192 void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
193 void visitBinaryOperator(Instruction *I);
194 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
196 // Instructions that cannot be folded away...
197 void visitStoreInst (Instruction *I) { /*returns void*/ }
198 void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
199 void visitCallInst (Instruction *I) { markOverdefined(I); }
200 void visitInvokeInst (Instruction *I) { markOverdefined(I); }
201 void visitAllocationInst(Instruction *I) { markOverdefined(I); }
202 void visitFreeInst (Instruction *I) { /*returns void*/ }
204 void visitInstruction(Instruction *I) {
205 // If a new instruction is added to LLVM that we don't handle...
206 cerr << "SCCP: Don't know how to handle: " << I;
207 markOverdefined(I); // Just in case
210 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
211 // block to the 'To' basic block is currently feasible...
213 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
215 // OperandChangedState - This method is invoked on all of the users of an
216 // instruction that was just changed state somehow.... Based on this
217 // information, we need to update the specified user of this instruction.
219 void OperandChangedState(User *U) {
220 // Only instructions use other variable values!
221 Instruction *I = cast<Instruction>(U);
222 if (!BBExecutable.count(I->getParent())) return;// Inst not executable yet!
226 } // end anonymous namespace
229 // createSCCPPass - This is the public interface to this file...
231 Pass *createSCCPPass() {
237 //===----------------------------------------------------------------------===//
238 // SCCP Class Implementation
241 // runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm,
242 // and return true if the function was modified.
244 bool SCCP::runOnFunction(Function *F) {
245 // Mark the first block of the function as being executable...
246 markExecutable(F->front());
248 // Process the work lists until their are empty!
249 while (!BBWorkList.empty() || !InstWorkList.empty()) {
250 // Process the instruction work list...
251 while (!InstWorkList.empty()) {
252 Instruction *I = *InstWorkList.begin();
253 InstWorkList.erase(InstWorkList.begin());
255 DEBUG_SCCP(cerr << "\nPopped off I-WL: " << I);
258 // "I" got into the work list because it either made the transition from
259 // bottom to constant, or to Overdefined.
261 // Update all of the users of this instruction's value...
263 for_each(I->use_begin(), I->use_end(),
264 bind_obj(this, &SCCP::OperandChangedState));
267 // Process the basic block work list...
268 while (!BBWorkList.empty()) {
269 BasicBlock *BB = BBWorkList.back();
270 BBWorkList.pop_back();
272 DEBUG_SCCP(cerr << "\nPopped off BBWL: " << BB);
274 // If this block only has a single successor, mark it as executable as
275 // well... if not, terminate the do loop.
277 if (BB->getTerminator()->getNumSuccessors() == 1)
278 markExecutable(BB->getTerminator()->getSuccessor(0));
280 // Notify all instructions in this basic block that they are newly
287 for (Function::iterator BBI = F->begin(), BBEnd = F->end();
289 if (!BBExecutable.count(*BBI))
290 cerr << "BasicBlock Dead:" << *BBI;
294 // Iterate over all of the instructions in a function, replacing them with
295 // constants if we have found them to be of constant values.
297 bool MadeChanges = false;
298 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) {
299 BasicBlock *BB = *FI;
300 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
301 Instruction *Inst = *BI;
302 InstVal &IV = ValueState[Inst];
303 if (IV.isConstant()) {
304 Constant *Const = IV.getConstant();
305 DEBUG_SCCP(cerr << "Constant: " << Inst << " is: " << Const);
307 // Replaces all of the uses of a variable with uses of the constant.
308 Inst->replaceAllUsesWith(Const);
310 // Remove the operator from the list of definitions... and delete it.
311 delete BB->getInstList().remove(BI);
313 // Hey, we just changed something!
316 // Do NOT advance the iterator, skipping the next instruction...
319 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) {
320 MadeChanges |= ConstantFoldTerminator(BB, BI, TI);
327 // Reset state so that the next invocation will have empty data structures
328 BBExecutable.clear();
334 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
335 // block to the 'To' basic block is currently feasible...
337 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
338 assert(BBExecutable.count(To) && "Dest should always be alive!");
340 // Make sure the source basic block is executable!!
341 if (!BBExecutable.count(From)) return false;
343 // This should check the terminator in From!
347 // visit Implementations - Something changed in this instruction... Either an
348 // operand made a transition, or the instruction is newly executable. Change
349 // the value type of I to reflect these changes if appropriate. This method
350 // makes sure to do the following actions:
352 // 1. If a phi node merges two constants in, and has conflicting value coming
353 // from different branches, or if the PHI node merges in an overdefined
354 // value, then the PHI node becomes overdefined.
355 // 2. If a phi node merges only constants in, and they all agree on value, the
356 // PHI node becomes a constant value equal to that.
357 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
358 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
359 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
360 // 6. If a conditional branch has a value that is constant, make the selected
361 // destination executable
362 // 7. If a conditional branch has a value that is overdefined, make all
363 // successors executable.
366 void SCCP::visitPHINode(PHINode *PN) {
367 unsigned NumValues = PN->getNumIncomingValues(), i;
368 InstVal *OperandIV = 0;
370 // Look at all of the executable operands of the PHI node. If any of them
371 // are overdefined, the PHI becomes overdefined as well. If they are all
372 // constant, and they agree with each other, the PHI becomes the identical
373 // constant. If they are constant and don't agree, the PHI is overdefined.
374 // If there are no executable operands, the PHI remains undefined.
376 for (i = 0; i < NumValues; ++i) {
377 if (isEdgeFeasible(PN->getIncomingBlock(i), PN->getParent())) {
378 InstVal &IV = getValueState(PN->getIncomingValue(i));
379 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
380 if (IV.isOverdefined()) { // PHI node becomes overdefined!
385 if (OperandIV == 0) { // Grab the first value...
387 } else { // Another value is being merged in!
388 // There is already a reachable operand. If we conflict with it,
389 // then the PHI node becomes overdefined. If we agree with it, we
392 // Check to see if there are two different constants merging...
393 if (IV.getConstant() != OperandIV->getConstant()) {
394 // Yes there is. This means the PHI node is not constant.
395 // You must be overdefined poor PHI.
397 markOverdefined(PN); // The PHI node now becomes overdefined
398 return; // I'm done analyzing you
404 // If we exited the loop, this means that the PHI node only has constant
405 // arguments that agree with each other(and OperandIV is a pointer to one
406 // of their InstVal's) or OperandIV is null because there are no defined
407 // incoming arguments. If this is the case, the PHI remains undefined.
410 assert(OperandIV->isConstant() && "Should only be here for constants!");
411 markConstant(PN, OperandIV->getConstant()); // Aquire operand value
415 void SCCP::visitBranchInst(BranchInst *BI) {
416 if (BI->isUnconditional())
417 return; // Unconditional branches are already handled!
419 InstVal &BCValue = getValueState(BI->getCondition());
420 if (BCValue.isOverdefined()) {
421 // Overdefined condition variables mean the branch could go either way.
422 markExecutable(BI->getSuccessor(0));
423 markExecutable(BI->getSuccessor(1));
424 } else if (BCValue.isConstant()) {
425 // Constant condition variables mean the branch can only go a single way.
426 if (BCValue.getConstant() == ConstantBool::True)
427 markExecutable(BI->getSuccessor(0));
429 markExecutable(BI->getSuccessor(1));
433 void SCCP::visitInvokeInst(InvokeInst *II) {
434 markExecutable(II->getNormalDest());
435 markExecutable(II->getExceptionalDest());
438 void SCCP::visitSwitchInst(SwitchInst *SI) {
439 InstVal &SCValue = getValueState(SI->getCondition());
440 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe
441 for(unsigned i = 0, E = SI->getNumSuccessors(); i != E; ++i)
442 markExecutable(SI->getSuccessor(i));
443 } else if (SCValue.isConstant()) {
444 Constant *CPV = SCValue.getConstant();
445 // Make sure to skip the "default value" which isn't a value
446 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
447 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
448 markExecutable(SI->getSuccessor(i));
453 // Constant value not equal to any of the branches... must execute
454 // default branch then...
455 markExecutable(SI->getDefaultDest());
459 void SCCP::visitUnaryOperator(Instruction *I) {
460 Value *V = I->getOperand(0);
461 InstVal &VState = getValueState(V);
462 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
464 } else if (VState.isConstant()) { // Propogate constant value
465 Constant *Result = isa<CastInst>(I)
466 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
467 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
470 // This instruction constant folds!
471 markConstant(I, Result);
473 markOverdefined(I); // Don't know how to fold this instruction. :(
478 // Handle BinaryOperators and Shift Instructions...
479 void SCCP::visitBinaryOperator(Instruction *I) {
480 InstVal &V1State = getValueState(I->getOperand(0));
481 InstVal &V2State = getValueState(I->getOperand(1));
482 if (V1State.isOverdefined() || V2State.isOverdefined()) {
484 } else if (V1State.isConstant() && V2State.isConstant()) {
485 Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(),
486 V1State.getConstant(),
487 V2State.getConstant());
489 markConstant(I, Result); // This instruction constant folds!
491 markOverdefined(I); // Don't know how to fold this instruction. :(