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.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"
28 #include "Support/StatisticReporter.h"
33 static Statistic<> NumInstRemoved("sccp\t\t- Number of instructions removed");
35 // InstVal class - This class represents the different lattice values that an
36 // instruction may occupy. It is a simple class with value semantics.
41 undefined, // This instruction has no known value
42 constant, // This instruction has a constant value
43 // Range, // This instruction is known to fall within a range
44 overdefined // This instruction has an unknown value
45 } LatticeValue; // The current lattice position
46 Constant *ConstantVal; // If Constant value, the current value
48 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
50 // markOverdefined - Return true if this is a new status to be in...
51 inline bool markOverdefined() {
52 if (LatticeValue != overdefined) {
53 LatticeValue = overdefined;
59 // markConstant - Return true if this is a new status for us...
60 inline bool markConstant(Constant *V) {
61 if (LatticeValue != constant) {
62 LatticeValue = constant;
66 assert(ConstantVal == V && "Marking constant with different value");
71 inline bool isUndefined() const { return LatticeValue == undefined; }
72 inline bool isConstant() const { return LatticeValue == constant; }
73 inline bool isOverdefined() const { return LatticeValue == overdefined; }
75 inline Constant *getConstant() const { return ConstantVal; }
78 } // end anonymous namespace
81 //===----------------------------------------------------------------------===//
84 // This class does all of the work of Sparse Conditional Constant Propogation.
87 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
88 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
89 std::map<Value*, InstVal> ValueState; // The state each value is in...
91 std::vector<Instruction*> InstWorkList;// The instruction work list
92 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
95 // runOnFunction - Run the Sparse Conditional Constant Propogation algorithm,
96 // and return true if the function was modified.
98 bool runOnFunction(Function &F);
100 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
105 //===--------------------------------------------------------------------===//
106 // The implementation of this class
109 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
111 // markValueOverdefined - Make a value be marked as "constant". If the value
112 // is not already a constant, add it to the instruction work list so that
113 // the users of the instruction are updated later.
115 inline bool markConstant(Instruction *I, Constant *V) {
116 DEBUG(cerr << "markConstant: " << V << " = " << I);
118 if (ValueState[I].markConstant(V)) {
119 InstWorkList.push_back(I);
125 // markValueOverdefined - Make a value be marked as "overdefined". If the
126 // value is not already overdefined, add it to the instruction work list so
127 // that the users of the instruction are updated later.
129 inline bool markOverdefined(Value *V) {
130 if (ValueState[V].markOverdefined()) {
131 if (Instruction *I = dyn_cast<Instruction>(V)) {
132 DEBUG(cerr << "markOverdefined: " << V);
133 InstWorkList.push_back(I); // Only instructions go on the work list
140 // getValueState - Return the InstVal object that corresponds to the value.
141 // This function is neccesary because not all values should start out in the
142 // underdefined state... Argument's should be overdefined, and
143 // constants should be marked as constants. If a value is not known to be an
144 // Instruction object, then use this accessor to get its value from the map.
146 inline InstVal &getValueState(Value *V) {
147 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
148 if (I != ValueState.end()) return I->second; // Common case, in the map
150 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
151 ValueState[CPV].markConstant(CPV);
152 } else if (isa<Argument>(V)) { // Arguments are overdefined
153 ValueState[V].markOverdefined();
155 // All others are underdefined by default...
156 return ValueState[V];
159 // markExecutable - Mark a basic block as executable, adding it to the BB
160 // work list if it is not already executable...
162 void markExecutable(BasicBlock *BB) {
163 if (BBExecutable.count(BB)) return;
164 DEBUG(cerr << "Marking BB Executable: " << *BB);
165 BBExecutable.insert(BB); // Basic block is executable!
166 BBWorkList.push_back(BB); // Add the block to the work list!
170 // visit implementations - Something changed in this instruction... Either an
171 // operand made a transition, or the instruction is newly executable. Change
172 // the value type of I to reflect these changes if appropriate.
174 void visitPHINode(PHINode &I);
177 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
178 void visitTerminatorInst(TerminatorInst &TI);
180 void visitCastInst(CastInst &I);
181 void visitBinaryOperator(Instruction &I);
182 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
184 // Instructions that cannot be folded away...
185 void visitStoreInst (Instruction &I) { /*returns void*/ }
186 void visitLoadInst (Instruction &I) { markOverdefined(&I); }
187 void visitGetElementPtrInst(Instruction &I) { markOverdefined(&I); } // FIXME
188 void visitCallInst (Instruction &I) { markOverdefined(&I); }
189 void visitInvokeInst (Instruction &I) { markOverdefined(&I); }
190 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
191 void visitFreeInst (Instruction &I) { /*returns void*/ }
193 void visitInstruction(Instruction &I) {
194 // If a new instruction is added to LLVM that we don't handle...
195 cerr << "SCCP: Don't know how to handle: " << I;
196 markOverdefined(&I); // Just in case
199 // getFeasibleSuccessors - Return a vector of booleans to indicate which
200 // successors are reachable from a given terminator instruction.
202 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
204 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
205 // block to the 'To' basic block is currently feasible...
207 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
209 // OperandChangedState - This method is invoked on all of the users of an
210 // instruction that was just changed state somehow.... Based on this
211 // information, we need to update the specified user of this instruction.
213 void OperandChangedState(User *U) {
214 // Only instructions use other variable values!
215 Instruction &I = cast<Instruction>(*U);
216 if (!BBExecutable.count(I.getParent())) return;// Inst not executable yet!
221 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propogation");
222 } // end anonymous namespace
225 // createSCCPPass - This is the public interface to this file...
227 Pass *createSCCPPass() {
232 //===----------------------------------------------------------------------===//
233 // SCCP Class Implementation
236 // runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm,
237 // and return true if the function was modified.
239 bool SCCP::runOnFunction(Function &F) {
240 // Mark the first block of the function as being executable...
241 markExecutable(&F.front());
243 // Process the work lists until their are empty!
244 while (!BBWorkList.empty() || !InstWorkList.empty()) {
245 // Process the instruction work list...
246 while (!InstWorkList.empty()) {
247 Instruction *I = InstWorkList.back();
248 InstWorkList.pop_back();
250 DEBUG(cerr << "\nPopped off I-WL: " << I);
253 // "I" got into the work list because it either made the transition from
254 // bottom to constant, or to Overdefined.
256 // Update all of the users of this instruction's value...
258 for_each(I->use_begin(), I->use_end(),
259 bind_obj(this, &SCCP::OperandChangedState));
262 // Process the basic block work list...
263 while (!BBWorkList.empty()) {
264 BasicBlock *BB = BBWorkList.back();
265 BBWorkList.pop_back();
267 DEBUG(cerr << "\nPopped off BBWL: " << BB);
269 // If this block only has a single successor, mark it as executable as
270 // well... if not, terminate the do loop.
272 if (BB->getTerminator()->getNumSuccessors() == 1)
273 markExecutable(BB->getTerminator()->getSuccessor(0));
275 // Notify all instructions in this basic block that they are newly
282 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
283 if (!BBExecutable.count(I))
284 cerr << "BasicBlock Dead:" << *I;
287 // Iterate over all of the instructions in a function, replacing them with
288 // constants if we have found them to be of constant values.
290 bool MadeChanges = false;
291 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
292 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
293 Instruction &Inst = *BI;
294 InstVal &IV = ValueState[&Inst];
295 if (IV.isConstant()) {
296 Constant *Const = IV.getConstant();
297 DEBUG(cerr << "Constant: " << Const << " = " << Inst);
299 // Replaces all of the uses of a variable with uses of the constant.
300 Inst.replaceAllUsesWith(Const);
302 // Remove the operator from the list of definitions... and delete it.
303 BI = BB->getInstList().erase(BI);
305 // Hey, we just changed something!
313 // Reset state so that the next invocation will have empty data structures
314 BBExecutable.clear();
321 // getFeasibleSuccessors - Return a vector of booleans to indicate which
322 // successors are reachable from a given terminator instruction.
324 void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
325 assert(Succs.size() == TI.getNumSuccessors() && "Succs vector wrong size!");
326 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
327 if (BI->isUnconditional()) {
330 InstVal &BCValue = getValueState(BI->getCondition());
331 if (BCValue.isOverdefined()) {
332 // Overdefined condition variables mean the branch could go either way.
333 Succs[0] = Succs[1] = true;
334 } else if (BCValue.isConstant()) {
335 // Constant condition variables mean the branch can only go a single way
336 Succs[BCValue.getConstant() == ConstantBool::False] = true;
339 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
340 // Invoke instructions successors are always executable.
341 Succs[0] = Succs[1] = true;
342 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
343 InstVal &SCValue = getValueState(SI->getCondition());
344 if (SCValue.isOverdefined()) { // Overdefined condition?
345 // All destinations are executable!
346 Succs.assign(TI.getNumSuccessors(), true);
347 } else if (SCValue.isConstant()) {
348 Constant *CPV = SCValue.getConstant();
349 // Make sure to skip the "default value" which isn't a value
350 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
351 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
357 // Constant value not equal to any of the branches... must execute
358 // default branch then...
362 cerr << "SCCP: Don't know how to handle: " << TI;
363 Succs.assign(TI.getNumSuccessors(), true);
368 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
369 // block to the 'To' basic block is currently feasible...
371 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
372 assert(BBExecutable.count(To) && "Dest should always be alive!");
374 // Make sure the source basic block is executable!!
375 if (!BBExecutable.count(From)) return false;
377 // Check to make sure this edge itself is actually feasible now...
378 TerminatorInst *FT = From->getTerminator();
379 std::vector<bool> SuccFeasible(FT->getNumSuccessors());
380 getFeasibleSuccessors(*FT, SuccFeasible);
382 // Check all edges from From to To. If any are feasible, return true.
383 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
384 if (FT->getSuccessor(i) == To && SuccFeasible[i])
387 // Otherwise, none of the edges are actually feasible at this time...
391 // visit Implementations - Something changed in this instruction... Either an
392 // operand made a transition, or the instruction is newly executable. Change
393 // the value type of I to reflect these changes if appropriate. This method
394 // makes sure to do the following actions:
396 // 1. If a phi node merges two constants in, and has conflicting value coming
397 // from different branches, or if the PHI node merges in an overdefined
398 // value, then the PHI node becomes overdefined.
399 // 2. If a phi node merges only constants in, and they all agree on value, the
400 // PHI node becomes a constant value equal to that.
401 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
402 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
403 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
404 // 6. If a conditional branch has a value that is constant, make the selected
405 // destination executable
406 // 7. If a conditional branch has a value that is overdefined, make all
407 // successors executable.
410 void SCCP::visitPHINode(PHINode &PN) {
411 unsigned NumValues = PN.getNumIncomingValues(), i;
412 InstVal *OperandIV = 0;
414 // Look at all of the executable operands of the PHI node. If any of them
415 // are overdefined, the PHI becomes overdefined as well. If they are all
416 // constant, and they agree with each other, the PHI becomes the identical
417 // constant. If they are constant and don't agree, the PHI is overdefined.
418 // If there are no executable operands, the PHI remains undefined.
420 for (i = 0; i < NumValues; ++i) {
421 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
422 InstVal &IV = getValueState(PN.getIncomingValue(i));
423 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
424 if (IV.isOverdefined()) { // PHI node becomes overdefined!
425 markOverdefined(&PN);
429 if (OperandIV == 0) { // Grab the first value...
431 } else { // Another value is being merged in!
432 // There is already a reachable operand. If we conflict with it,
433 // then the PHI node becomes overdefined. If we agree with it, we
436 // Check to see if there are two different constants merging...
437 if (IV.getConstant() != OperandIV->getConstant()) {
438 // Yes there is. This means the PHI node is not constant.
439 // You must be overdefined poor PHI.
441 markOverdefined(&PN); // The PHI node now becomes overdefined
442 return; // I'm done analyzing you
448 // If we exited the loop, this means that the PHI node only has constant
449 // arguments that agree with each other(and OperandIV is a pointer to one
450 // of their InstVal's) or OperandIV is null because there are no defined
451 // incoming arguments. If this is the case, the PHI remains undefined.
454 assert(OperandIV->isConstant() && "Should only be here for constants!");
455 markConstant(&PN, OperandIV->getConstant()); // Aquire operand value
459 void SCCP::visitTerminatorInst(TerminatorInst &TI) {
460 std::vector<bool> SuccFeasible(TI.getNumSuccessors());
461 getFeasibleSuccessors(TI, SuccFeasible);
463 // Mark all feasible successors executable...
464 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
465 if (SuccFeasible[i]) {
466 BasicBlock *Succ = TI.getSuccessor(i);
467 markExecutable(Succ);
469 // Visit all of the PHI nodes that merge values from this block...
470 // Because this edge may be new executable, and PHI nodes that used to be
471 // constant now may not be.
473 for (BasicBlock::iterator I = Succ->begin();
474 PHINode *PN = dyn_cast<PHINode>(&*I); ++I)
479 void SCCP::visitCastInst(CastInst &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
486 ConstantFoldCastInstruction(VState.getConstant(), I.getType());
489 // This instruction constant folds!
490 markConstant(&I, Result);
492 markOverdefined(&I); // Don't know how to fold this instruction. :(
497 // Handle BinaryOperators and Shift Instructions...
498 void SCCP::visitBinaryOperator(Instruction &I) {
499 InstVal &V1State = getValueState(I.getOperand(0));
500 InstVal &V2State = getValueState(I.getOperand(1));
501 if (V1State.isOverdefined() || V2State.isOverdefined()) {
503 } else if (V1State.isConstant() && V2State.isConstant()) {
504 Constant *Result = 0;
505 if (isa<BinaryOperator>(I))
506 Result = ConstantFoldBinaryInstruction(I.getOpcode(),
507 V1State.getConstant(),
508 V2State.getConstant());
509 else if (isa<ShiftInst>(I))
510 Result = ConstantFoldShiftInstruction(I.getOpcode(),
511 V1State.getConstant(),
512 V2State.getConstant());
514 markConstant(&I, Result); // This instruction constant folds!
516 markOverdefined(&I); // Don't know how to fold this instruction. :(