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/Constants.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iMemory.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iOther.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/STLExtras.h"
36 // InstVal class - This class represents the different lattice values that an
37 // 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; }
80 //===----------------------------------------------------------------------===//
83 // This class does all of the work of Sparse Conditional Constant Propogation.
84 // It's public interface consists of a constructor and a doSCCP() function.
86 class SCCP : public InstVisitor<SCCP> {
87 Function *M; // The function that we are working on
89 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
90 std::map<Value*, InstVal> ValueState; // The state each value is in...
92 std::vector<Instruction*> InstWorkList;// The instruction work list
93 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
95 //===--------------------------------------------------------------------===//
96 // The public interface for this class
100 // SCCP Ctor - Save the function to operate on...
101 inline SCCP(Function *f) : M(f) {}
103 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
104 // return true if the function was modified.
107 //===--------------------------------------------------------------------===//
108 // The implementation of this class
111 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
113 // markValueOverdefined - Make a value be marked as "constant". If the value
114 // is not already a constant, add it to the instruction work list so that
115 // the users of the instruction are updated later.
117 inline bool markConstant(Instruction *I, Constant *V) {
118 //cerr << "markConstant: " << V << " = " << I;
119 if (ValueState[I].markConstant(V)) {
120 InstWorkList.push_back(I);
126 // markValueOverdefined - Make a value be marked as "overdefined". If the
127 // value is not already overdefined, add it to the instruction work list so
128 // that the users of the instruction are updated later.
130 inline bool markOverdefined(Value *V) {
131 if (ValueState[V].markOverdefined()) {
132 if (Instruction *I = dyn_cast<Instruction>(V)) {
133 //cerr << "markOverdefined: " << V;
134 InstWorkList.push_back(I); // Only instructions go on the work list
141 // getValueState - Return the InstVal object that corresponds to the value.
142 // This function is neccesary because not all values should start out in the
143 // underdefined state... Argument's should be overdefined, and
144 // constants should be marked as constants. If a value is not known to be an
145 // Instruction object, then use this accessor to get its value from the map.
147 inline InstVal &getValueState(Value *V) {
148 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
149 if (I != ValueState.end()) return I->second; // Common case, in the map
151 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
152 ValueState[CPV].markConstant(CPV);
153 } else if (isa<Argument>(V)) { // Arguments are overdefined
154 ValueState[V].markOverdefined();
156 // All others are underdefined by default...
157 return ValueState[V];
160 // markExecutable - Mark a basic block as executable, adding it to the BB
161 // work list if it is not already executable...
163 void markExecutable(BasicBlock *BB) {
164 if (BBExecutable.count(BB)) return;
165 //cerr << "Marking BB Executable: " << BB;
166 BBExecutable.insert(BB); // Basic block is executable!
167 BBWorkList.push_back(BB); // Add the block to the work list!
171 // visit implementations - Something changed in this instruction... Either an
172 // operand made a transition, or the instruction is newly executable. Change
173 // the value type of I to reflect these changes if appropriate.
175 void visitPHINode(PHINode *I);
178 void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
179 void visitBranchInst(BranchInst *I);
180 void visitSwitchInst(SwitchInst *I);
182 void visitUnaryOperator(Instruction *I);
183 void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
184 void visitBinaryOperator(Instruction *I);
185 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
187 // Instructions that cannot be folded away...
188 void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
189 void visitCallInst (Instruction *I) { markOverdefined(I); }
190 void visitInvokeInst (Instruction *I) { markOverdefined(I); }
191 void visitAllocationInst(Instruction *I) { markOverdefined(I); }
192 void visitFreeInst (Instruction *I) { markOverdefined(I); }
194 void visitInstruction(Instruction *I) {
195 // If a new instruction is added to LLVM that we don't handle...
196 cerr << "SCCP: Don't know how to handle: " << I;
197 markOverdefined(I); // Just in case
200 // OperandChangedState - This method is invoked on all of the users of an
201 // instruction that was just changed state somehow.... Based on this
202 // information, we need to update the specified user of this instruction.
204 void OperandChangedState(User *U);
208 //===----------------------------------------------------------------------===//
209 // SCCP Class Implementation
212 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
213 // return true if the function was modified.
215 bool SCCP::doSCCP() {
216 // Mark the first block of the function as being executable...
217 markExecutable(M->front());
219 // Process the work lists until their are empty!
220 while (!BBWorkList.empty() || !InstWorkList.empty()) {
221 // Process the instruction work list...
222 while (!InstWorkList.empty()) {
223 Instruction *I = InstWorkList.back();
224 InstWorkList.pop_back();
226 //cerr << "\nPopped off I-WL: " << I;
229 // "I" got into the work list because it either made the transition from
230 // bottom to constant, or to Overdefined.
232 // Update all of the users of this instruction's value...
234 for_each(I->use_begin(), I->use_end(),
235 bind_obj(this, &SCCP::OperandChangedState));
238 // Process the basic block work list...
239 while (!BBWorkList.empty()) {
240 BasicBlock *BB = BBWorkList.back();
241 BBWorkList.pop_back();
243 //cerr << "\nPopped off BBWL: " << BB;
245 // If this block only has a single successor, mark it as executable as
246 // well... if not, terminate the do loop.
248 if (BB->getTerminator()->getNumSuccessors() == 1)
249 markExecutable(BB->getTerminator()->getSuccessor(0));
251 // Notify all instructions in this basic block that they are newly
258 for (Function::iterator BBI = M->begin(), BBEnd = M->end();
260 if (!BBExecutable.count(*BBI))
261 cerr << "BasicBlock Dead:" << *BBI;
265 // Iterate over all of the instructions in a function, replacing them with
266 // constants if we have found them to be of constant values.
268 bool MadeChanges = false;
269 for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
270 BasicBlock *BB = *MI;
271 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
272 Instruction *Inst = *BI;
273 InstVal &IV = ValueState[Inst];
274 if (IV.isConstant()) {
275 Constant *Const = IV.getConstant();
276 // cerr << "Constant: " << Inst << " is: " << Const;
278 // Replaces all of the uses of a variable with uses of the constant.
279 Inst->replaceAllUsesWith(Const);
281 // Remove the operator from the list of definitions...
282 BB->getInstList().remove(BI);
284 // The new constant inherits the old name of the operator...
285 if (Inst->hasName() && !Const->hasName())
286 Const->setName(Inst->getName(), M->getSymbolTableSure());
288 // Delete the operator now...
291 // Hey, we just changed something!
293 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) {
294 MadeChanges |= ConstantFoldTerminator(BB, BI, TI);
301 // Merge identical constants last: this is important because we may have just
302 // introduced constants that already exist, and we don't want to pollute later
303 // stages with extraneous constants.
309 // visit Implementations - Something changed in this instruction... Either an
310 // operand made a transition, or the instruction is newly executable. Change
311 // the value type of I to reflect these changes if appropriate. This method
312 // makes sure to do the following actions:
314 // 1. If a phi node merges two constants in, and has conflicting value coming
315 // from different branches, or if the PHI node merges in an overdefined
316 // value, then the PHI node becomes overdefined.
317 // 2. If a phi node merges only constants in, and they all agree on value, the
318 // PHI node becomes a constant value equal to that.
319 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
320 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
321 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
322 // 6. If a conditional branch has a value that is constant, make the selected
323 // destination executable
324 // 7. If a conditional branch has a value that is overdefined, make all
325 // successors executable.
328 void SCCP::visitPHINode(PHINode *PN) {
329 unsigned NumValues = PN->getNumIncomingValues(), i;
330 InstVal *OperandIV = 0;
332 // Look at all of the executable operands of the PHI node. If any of them
333 // are overdefined, the PHI becomes overdefined as well. If they are all
334 // constant, and they agree with each other, the PHI becomes the identical
335 // constant. If they are constant and don't agree, the PHI is overdefined.
336 // If there are no executable operands, the PHI remains undefined.
338 for (i = 0; i < NumValues; ++i) {
339 if (BBExecutable.count(PN->getIncomingBlock(i))) {
340 InstVal &IV = getValueState(PN->getIncomingValue(i));
341 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
342 if (IV.isOverdefined()) { // PHI node becomes overdefined!
347 if (OperandIV == 0) { // Grab the first value...
349 } else { // Another value is being merged in!
350 // There is already a reachable operand. If we conflict with it,
351 // then the PHI node becomes overdefined. If we agree with it, we
354 // Check to see if there are two different constants merging...
355 if (IV.getConstant() != OperandIV->getConstant()) {
356 // Yes there is. This means the PHI node is not constant.
357 // You must be overdefined poor PHI.
359 markOverdefined(PN); // The PHI node now becomes overdefined
360 return; // I'm done analyzing you
366 // If we exited the loop, this means that the PHI node only has constant
367 // arguments that agree with each other(and OperandIV is a pointer to one
368 // of their InstVal's) or OperandIV is null because there are no defined
369 // incoming arguments. If this is the case, the PHI remains undefined.
372 assert(OperandIV->isConstant() && "Should only be here for constants!");
373 markConstant(PN, OperandIV->getConstant()); // Aquire operand value
377 void SCCP::visitBranchInst(BranchInst *BI) {
378 if (BI->isUnconditional())
379 return; // Unconditional branches are already handled!
381 InstVal &BCValue = getValueState(BI->getCondition());
382 if (BCValue.isOverdefined()) {
383 // Overdefined condition variables mean the branch could go either way.
384 markExecutable(BI->getSuccessor(0));
385 markExecutable(BI->getSuccessor(1));
386 } else if (BCValue.isConstant()) {
387 // Constant condition variables mean the branch can only go a single way.
388 if (BCValue.getConstant() == ConstantBool::True)
389 markExecutable(BI->getSuccessor(0));
391 markExecutable(BI->getSuccessor(1));
395 void SCCP::visitSwitchInst(SwitchInst *SI) {
396 InstVal &SCValue = getValueState(SI->getCondition());
397 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe
398 for(unsigned i = 0, E = SI->getNumSuccessors(); i != E; ++i)
399 markExecutable(SI->getSuccessor(i));
400 } else if (SCValue.isConstant()) {
401 Constant *CPV = SCValue.getConstant();
402 // Make sure to skip the "default value" which isn't a value
403 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
404 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
405 markExecutable(SI->getSuccessor(i));
410 // Constant value not equal to any of the branches... must execute
411 // default branch then...
412 markExecutable(SI->getDefaultDest());
416 void SCCP::visitUnaryOperator(Instruction *I) {
417 Value *V = I->getOperand(0);
418 InstVal &VState = getValueState(V);
419 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
421 } else if (VState.isConstant()) { // Propogate constant value
422 Constant *Result = isa<CastInst>(I)
423 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
424 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
427 // This instruction constant folds!
428 markConstant(I, Result);
430 markOverdefined(I); // Don't know how to fold this instruction. :(
435 // Handle BinaryOperators and Shift Instructions...
436 void SCCP::visitBinaryOperator(Instruction *I) {
437 InstVal &V1State = getValueState(I->getOperand(0));
438 InstVal &V2State = getValueState(I->getOperand(1));
439 if (V1State.isOverdefined() || V2State.isOverdefined()) {
441 } else if (V1State.isConstant() && V2State.isConstant()) {
442 Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(),
443 V1State.getConstant(),
444 V2State.getConstant());
446 markConstant(I, Result); // This instruction constant fold!s
448 markOverdefined(I); // Don't know how to fold this instruction. :(
452 // OperandChangedState - This method is invoked on all of the users of an
453 // instruction that was just changed state somehow.... Based on this
454 // information, we need to update the specified user of this instruction.
456 void SCCP::OperandChangedState(User *U) {
457 // Only instructions use other variable values!
458 Instruction *I = cast<Instruction>(U);
459 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet!
465 // SCCPPass - Use Sparse Conditional Constant Propogation
466 // to prove whether a value is constant and whether blocks are used.
468 struct SCCPPass : public FunctionPass {
469 inline bool runOnFunction(Function *F) {
473 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
474 // FIXME: SCCP does not preserve the CFG because it folds terminators!
480 Pass *createSCCPPass() {
481 return new SCCPPass();