1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // This file implements sparse conditional constant propagation 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 to be unconditional
12 // * This pass has a habit of making definitions be dead. It is a good idea
13 // to to run a DCE pass sometime after running this pass.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/ConstantHandling.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "Support/Debug.h"
24 #include "Support/Statistic.h"
25 #include "Support/STLExtras.h"
29 // InstVal class - This class represents the different lattice values that an
30 // instruction may occupy. It is a simple class with value semantics.
33 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
37 undefined, // This instruction has no known value
38 constant, // This instruction has a constant value
39 overdefined // This instruction has an unknown value
40 } LatticeValue; // The current lattice position
41 Constant *ConstantVal; // If Constant value, the current value
43 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
45 // markOverdefined - Return true if this is a new status to be in...
46 inline bool markOverdefined() {
47 if (LatticeValue != overdefined) {
48 LatticeValue = overdefined;
54 // markConstant - Return true if this is a new status for us...
55 inline bool markConstant(Constant *V) {
56 if (LatticeValue != constant) {
57 LatticeValue = constant;
61 assert(ConstantVal == V && "Marking constant with different value");
66 inline bool isUndefined() const { return LatticeValue == undefined; }
67 inline bool isConstant() const { return LatticeValue == constant; }
68 inline bool isOverdefined() const { return LatticeValue == overdefined; }
70 inline Constant *getConstant() const { return ConstantVal; }
73 } // end anonymous namespace
76 //===----------------------------------------------------------------------===//
79 // This class does all of the work of Sparse Conditional Constant Propagation.
82 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
83 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
84 std::map<Value*, InstVal> ValueState; // The state each value is in...
86 std::vector<Instruction*> InstWorkList;// The instruction work list
87 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
90 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
91 // and return true if the function was modified.
93 bool runOnFunction(Function &F);
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 //===--------------------------------------------------------------------===//
101 // The implementation of this class
104 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
106 // markValueOverdefined - Make a value be marked as "constant". If the value
107 // is not already a constant, add it to the instruction work list so that
108 // the users of the instruction are updated later.
110 inline bool markConstant(Instruction *I, Constant *V) {
111 if (ValueState[I].markConstant(V)) {
112 DEBUG(std::cerr << "markConstant: " << V << " = " << I);
113 InstWorkList.push_back(I);
119 // markValueOverdefined - Make a value be marked as "overdefined". If the
120 // value is not already overdefined, add it to the instruction work list so
121 // that the users of the instruction are updated later.
123 inline bool markOverdefined(Value *V) {
124 if (ValueState[V].markOverdefined()) {
125 if (Instruction *I = dyn_cast<Instruction>(V)) {
126 DEBUG(std::cerr << "markOverdefined: " << V);
127 InstWorkList.push_back(I); // Only instructions go on the work list
134 // getValueState - Return the InstVal object that corresponds to the value.
135 // This function is necessary because not all values should start out in the
136 // underdefined state... Argument's should be overdefined, and
137 // constants should be marked as constants. If a value is not known to be an
138 // Instruction object, then use this accessor to get its value from the map.
140 inline InstVal &getValueState(Value *V) {
141 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
142 if (I != ValueState.end()) return I->second; // Common case, in the map
144 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
145 ValueState[CPV].markConstant(CPV);
146 } else if (isa<Argument>(V)) { // Arguments are overdefined
147 ValueState[V].markOverdefined();
148 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
149 // The address of a global is a constant...
150 ValueState[V].markConstant(ConstantPointerRef::get(GV));
152 // All others are underdefined by default...
153 return ValueState[V];
156 // markExecutable - Mark a basic block as executable, adding it to the BB
157 // work list if it is not already executable...
159 void markExecutable(BasicBlock *BB) {
160 if (BBExecutable.count(BB)) {
161 // BB is already executable, but we may have just made an edge feasible
162 // that wasn't before. Add the PHI nodes to the work list so that they
164 for (BasicBlock::iterator I = BB->begin();
165 PHINode *PN = dyn_cast<PHINode>(I); ++I)
169 DEBUG(std::cerr << "Marking BB Executable: " << *BB);
170 BBExecutable.insert(BB); // Basic block is executable!
171 BBWorkList.push_back(BB); // Add the block to the work list!
176 // visit implementations - Something changed in this instruction... Either an
177 // operand made a transition, or the instruction is newly executable. Change
178 // the value type of I to reflect these changes if appropriate.
180 void visitPHINode(PHINode &I);
183 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
184 void visitTerminatorInst(TerminatorInst &TI);
186 void visitCastInst(CastInst &I);
187 void visitBinaryOperator(Instruction &I);
188 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
190 // Instructions that cannot be folded away...
191 void visitStoreInst (Instruction &I) { /*returns void*/ }
192 void visitLoadInst (Instruction &I) { markOverdefined(&I); }
193 void visitGetElementPtrInst(GetElementPtrInst &I);
194 void visitCallInst (Instruction &I) { markOverdefined(&I); }
195 void visitInvokeInst (TerminatorInst &I) {
197 visitTerminatorInst(I);
199 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
200 void visitVarArgInst (Instruction &I) { markOverdefined(&I); }
201 void visitFreeInst (Instruction &I) { /*returns void*/ }
203 void visitInstruction(Instruction &I) {
204 // If a new instruction is added to LLVM that we don't handle...
205 std::cerr << "SCCP: Don't know how to handle: " << I;
206 markOverdefined(&I); // Just in case
209 // getFeasibleSuccessors - Return a vector of booleans to indicate which
210 // successors are reachable from a given terminator instruction.
212 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
214 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
215 // block to the 'To' basic block is currently feasible...
217 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
219 // OperandChangedState - This method is invoked on all of the users of an
220 // instruction that was just changed state somehow.... Based on this
221 // information, we need to update the specified user of this instruction.
223 void OperandChangedState(User *U) {
224 // Only instructions use other variable values!
225 Instruction &I = cast<Instruction>(*U);
226 if (BBExecutable.count(I.getParent())) // Inst is executable?
231 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
232 } // end anonymous namespace
235 // createSCCPPass - This is the public interface to this file...
237 Pass *createSCCPPass() {
242 //===----------------------------------------------------------------------===//
243 // SCCP Class Implementation
246 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
247 // and return true if the function was modified.
249 bool SCCP::runOnFunction(Function &F) {
250 // Mark the first block of the function as being executable...
251 markExecutable(&F.front());
253 // Process the work lists until their are empty!
254 while (!BBWorkList.empty() || !InstWorkList.empty()) {
255 // Process the instruction work list...
256 while (!InstWorkList.empty()) {
257 Instruction *I = InstWorkList.back();
258 InstWorkList.pop_back();
260 DEBUG(std::cerr << "\nPopped off I-WL: " << I);
262 // "I" got into the work list because it either made the transition from
263 // bottom to constant, or to Overdefined.
265 // Update all of the users of this instruction's value...
267 for_each(I->use_begin(), I->use_end(),
268 bind_obj(this, &SCCP::OperandChangedState));
271 // Process the basic block work list...
272 while (!BBWorkList.empty()) {
273 BasicBlock *BB = BBWorkList.back();
274 BBWorkList.pop_back();
276 DEBUG(std::cerr << "\nPopped off BBWL: " << BB);
278 // Notify all instructions in this basic block that they are newly
285 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
286 if (!BBExecutable.count(I))
287 std::cerr << "BasicBlock Dead:" << *I;
290 // Iterate over all of the instructions in a function, replacing them with
291 // constants if we have found them to be of constant values.
293 bool MadeChanges = false;
294 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
295 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
296 Instruction &Inst = *BI;
297 InstVal &IV = ValueState[&Inst];
298 if (IV.isConstant()) {
299 Constant *Const = IV.getConstant();
300 DEBUG(std::cerr << "Constant: " << Const << " = " << Inst);
302 // Replaces all of the uses of a variable with uses of the constant.
303 Inst.replaceAllUsesWith(Const);
305 // Remove the operator from the list of definitions... and delete it.
306 BI = BB->getInstList().erase(BI);
308 // Hey, we just changed something!
316 // Reset state so that the next invocation will have empty data structures
317 BBExecutable.clear();
319 std::vector<Instruction*>().swap(InstWorkList);
320 std::vector<BasicBlock*>().swap(BBWorkList);
326 // getFeasibleSuccessors - Return a vector of booleans to indicate which
327 // successors are reachable from a given terminator instruction.
329 void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
330 Succs.resize(TI.getNumSuccessors());
331 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
332 if (BI->isUnconditional()) {
335 InstVal &BCValue = getValueState(BI->getCondition());
336 if (BCValue.isOverdefined()) {
337 // Overdefined condition variables mean the branch could go either way.
338 Succs[0] = Succs[1] = true;
339 } else if (BCValue.isConstant()) {
340 // Constant condition variables mean the branch can only go a single way
341 Succs[BCValue.getConstant() == ConstantBool::False] = true;
344 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
345 // Invoke instructions successors are always executable.
346 Succs[0] = Succs[1] = true;
347 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
348 InstVal &SCValue = getValueState(SI->getCondition());
349 if (SCValue.isOverdefined()) { // Overdefined condition?
350 // All destinations are executable!
351 Succs.assign(TI.getNumSuccessors(), true);
352 } else if (SCValue.isConstant()) {
353 Constant *CPV = SCValue.getConstant();
354 // Make sure to skip the "default value" which isn't a value
355 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
356 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
362 // Constant value not equal to any of the branches... must execute
363 // default branch then...
367 std::cerr << "SCCP: Don't know how to handle: " << TI;
368 Succs.assign(TI.getNumSuccessors(), true);
373 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
374 // block to the 'To' basic block is currently feasible...
376 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
377 assert(BBExecutable.count(To) && "Dest should always be alive!");
379 // Make sure the source basic block is executable!!
380 if (!BBExecutable.count(From)) return false;
382 // Check to make sure this edge itself is actually feasible now...
383 TerminatorInst *FT = From->getTerminator();
384 std::vector<bool> SuccFeasible;
385 getFeasibleSuccessors(*FT, SuccFeasible);
387 // Check all edges from From to To. If any are feasible, return true.
388 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
389 if (FT->getSuccessor(i) == To && SuccFeasible[i])
392 // Otherwise, none of the edges are actually feasible at this time...
396 // visit Implementations - Something changed in this instruction... Either an
397 // operand made a transition, or the instruction is newly executable. Change
398 // the value type of I to reflect these changes if appropriate. This method
399 // makes sure to do the following actions:
401 // 1. If a phi node merges two constants in, and has conflicting value coming
402 // from different branches, or if the PHI node merges in an overdefined
403 // value, then the PHI node becomes overdefined.
404 // 2. If a phi node merges only constants in, and they all agree on value, the
405 // PHI node becomes a constant value equal to that.
406 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
407 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
408 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
409 // 6. If a conditional branch has a value that is constant, make the selected
410 // destination executable
411 // 7. If a conditional branch has a value that is overdefined, make all
412 // successors executable.
414 void SCCP::visitPHINode(PHINode &PN) {
415 if (getValueState(&PN).isOverdefined()) return; // Quick exit
417 // Look at all of the executable operands of the PHI node. If any of them
418 // are overdefined, the PHI becomes overdefined as well. If they are all
419 // constant, and they agree with each other, the PHI becomes the identical
420 // constant. If they are constant and don't agree, the PHI is overdefined.
421 // If there are no executable operands, the PHI remains undefined.
423 Constant *OperandVal = 0;
424 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
425 InstVal &IV = getValueState(PN.getIncomingValue(i));
426 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
428 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
429 if (IV.isOverdefined()) { // PHI node becomes overdefined!
430 markOverdefined(&PN);
434 if (OperandVal == 0) { // Grab the first value...
435 OperandVal = IV.getConstant();
436 } else { // Another value is being merged in!
437 // There is already a reachable operand. If we conflict with it,
438 // then the PHI node becomes overdefined. If we agree with it, we
441 // Check to see if there are two different constants merging...
442 if (IV.getConstant() != OperandVal) {
443 // Yes there is. This means the PHI node is not constant.
444 // You must be overdefined poor PHI.
446 markOverdefined(&PN); // The PHI node now becomes overdefined
447 return; // I'm done analyzing you
453 // If we exited the loop, this means that the PHI node only has constant
454 // arguments that agree with each other(and OperandVal is the constant) or
455 // OperandVal is null because there are no defined incoming arguments. If
456 // this is the case, the PHI remains undefined.
459 markConstant(&PN, OperandVal); // Aquire operand value
462 void SCCP::visitTerminatorInst(TerminatorInst &TI) {
463 std::vector<bool> SuccFeasible;
464 getFeasibleSuccessors(TI, SuccFeasible);
466 // Mark all feasible successors executable...
467 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
468 if (SuccFeasible[i]) {
469 BasicBlock *Succ = TI.getSuccessor(i);
470 markExecutable(Succ);
474 void SCCP::visitCastInst(CastInst &I) {
475 Value *V = I.getOperand(0);
476 InstVal &VState = getValueState(V);
477 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
479 } else if (VState.isConstant()) { // Propagate constant value
481 ConstantFoldCastInstruction(VState.getConstant(), I.getType());
484 // This instruction constant folds!
485 markConstant(&I, Result);
487 markOverdefined(&I); // Don't know how to fold this instruction. :(
492 // Handle BinaryOperators and Shift Instructions...
493 void SCCP::visitBinaryOperator(Instruction &I) {
494 InstVal &V1State = getValueState(I.getOperand(0));
495 InstVal &V2State = getValueState(I.getOperand(1));
496 if (V1State.isOverdefined() || V2State.isOverdefined()) {
498 } else if (V1State.isConstant() && V2State.isConstant()) {
499 Constant *Result = 0;
500 if (isa<BinaryOperator>(I))
501 Result = ConstantFoldBinaryInstruction(I.getOpcode(),
502 V1State.getConstant(),
503 V2State.getConstant());
504 else if (isa<ShiftInst>(I))
505 Result = ConstantFoldShiftInstruction(I.getOpcode(),
506 V1State.getConstant(),
507 V2State.getConstant());
509 markConstant(&I, Result); // This instruction constant folds!
511 markOverdefined(&I); // Don't know how to fold this instruction. :(
515 // Handle getelementptr instructions... if all operands are constants then we
516 // can turn this into a getelementptr ConstantExpr.
518 void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
519 std::vector<Constant*> Operands;
520 Operands.reserve(I.getNumOperands());
522 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
523 InstVal &State = getValueState(I.getOperand(i));
524 if (State.isUndefined())
525 return; // Operands are not resolved yet...
526 else if (State.isOverdefined()) {
530 assert(State.isConstant() && "Unknown state!");
531 Operands.push_back(State.getConstant());
534 Constant *Ptr = Operands[0];
535 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
537 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Operands));