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 // InstVal class - This class represents the different lattice values that an
34 // instruction may occupy. It is a simple class with value semantics.
38 undefined, // This instruction has no known value
39 constant, // This instruction has a constant value
40 // Range, // This instruction is known to fall within a range
41 overdefined // This instruction has an unknown value
42 } LatticeValue; // The current lattice position
43 Constant *ConstantVal; // If Constant value, the current value
45 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
47 // markOverdefined - Return true if this is a new status to be in...
48 inline bool markOverdefined() {
49 if (LatticeValue != overdefined) {
50 LatticeValue = overdefined;
56 // markConstant - Return true if this is a new status for us...
57 inline bool markConstant(Constant *V) {
58 if (LatticeValue != constant) {
59 LatticeValue = constant;
63 assert(ConstantVal == V && "Marking constant with different value");
68 inline bool isUndefined() const { return LatticeValue == undefined; }
69 inline bool isConstant() const { return LatticeValue == constant; }
70 inline bool isOverdefined() const { return LatticeValue == overdefined; }
72 inline Constant *getConstant() const { return ConstantVal; }
77 //===----------------------------------------------------------------------===//
80 // This class does all of the work of Sparse Conditional Constant Propogation.
81 // It's public interface consists of a constructor and a doSCCP() function.
83 class SCCP : public InstVisitor<SCCP> {
84 Function *M; // The function that we are working on
86 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
87 std::map<Value*, InstVal> ValueState; // The state each value is in...
89 std::vector<Instruction*> InstWorkList;// The instruction work list
90 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
92 //===--------------------------------------------------------------------===//
93 // The public interface for this class
97 // SCCP Ctor - Save the function to operate on...
98 inline SCCP(Function *f) : M(f) {}
100 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
101 // return true if the function was modified.
104 //===--------------------------------------------------------------------===//
105 // The implementation of this class
108 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
110 // markValueOverdefined - Make a value be marked as "constant". If the value
111 // is not already a constant, add it to the instruction work list so that
112 // the users of the instruction are updated later.
114 inline bool markConstant(Instruction *I, Constant *V) {
115 //cerr << "markConstant: " << V << " = " << I;
116 if (ValueState[I].markConstant(V)) {
117 InstWorkList.push_back(I);
123 // markValueOverdefined - Make a value be marked as "overdefined". If the
124 // value is not already overdefined, add it to the instruction work list so
125 // that the users of the instruction are updated later.
127 inline bool markOverdefined(Value *V) {
128 if (ValueState[V].markOverdefined()) {
129 if (Instruction *I = dyn_cast<Instruction>(V)) {
130 //cerr << "markOverdefined: " << V;
131 InstWorkList.push_back(I); // Only instructions go on the work list
138 // getValueState - Return the InstVal object that corresponds to the value.
139 // This function is neccesary because not all values should start out in the
140 // underdefined state... Argument's should be overdefined, and
141 // constants should be marked as constants. If a value is not known to be an
142 // Instruction object, then use this accessor to get its value from the map.
144 inline InstVal &getValueState(Value *V) {
145 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
146 if (I != ValueState.end()) return I->second; // Common case, in the map
148 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
149 ValueState[CPV].markConstant(CPV);
150 } else if (isa<Argument>(V)) { // Arguments are overdefined
151 ValueState[V].markOverdefined();
153 // All others are underdefined by default...
154 return ValueState[V];
157 // markExecutable - Mark a basic block as executable, adding it to the BB
158 // work list if it is not already executable...
160 void markExecutable(BasicBlock *BB) {
161 if (BBExecutable.count(BB)) return;
162 //cerr << "Marking BB Executable: " << BB;
163 BBExecutable.insert(BB); // Basic block is executable!
164 BBWorkList.push_back(BB); // Add the block to the work list!
168 // visit implementations - Something changed in this instruction... Either an
169 // operand made a transition, or the instruction is newly executable. Change
170 // the value type of I to reflect these changes if appropriate.
172 void visitPHINode(PHINode *I);
175 void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
176 void visitBranchInst(BranchInst *I);
177 void visitSwitchInst(SwitchInst *I);
179 void visitUnaryOperator(Instruction *I);
180 void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
181 void visitBinaryOperator(Instruction *I);
182 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
184 // Instructions that cannot be folded away...
185 void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
186 void visitCallInst (Instruction *I) { markOverdefined(I); }
187 void visitInvokeInst (Instruction *I) { markOverdefined(I); }
188 void visitAllocationInst(Instruction *I) { markOverdefined(I); }
189 void visitFreeInst (Instruction *I) { markOverdefined(I); }
191 void visitInstruction(Instruction *I) {
192 // If a new instruction is added to LLVM that we don't handle...
193 cerr << "SCCP: Don't know how to handle: " << I;
194 markOverdefined(I); // Just in case
197 // OperandChangedState - This method is invoked on all of the users of an
198 // instruction that was just changed state somehow.... Based on this
199 // information, we need to update the specified user of this instruction.
201 void OperandChangedState(User *U);
205 //===----------------------------------------------------------------------===//
206 // SCCP Class Implementation
209 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
210 // return true if the function was modified.
212 bool SCCP::doSCCP() {
213 // Mark the first block of the function as being executable...
214 markExecutable(M->front());
216 // Process the work lists until their are empty!
217 while (!BBWorkList.empty() || !InstWorkList.empty()) {
218 // Process the instruction work list...
219 while (!InstWorkList.empty()) {
220 Instruction *I = InstWorkList.back();
221 InstWorkList.pop_back();
223 //cerr << "\nPopped off I-WL: " << I;
226 // "I" got into the work list because it either made the transition from
227 // bottom to constant, or to Overdefined.
229 // Update all of the users of this instruction's value...
231 for_each(I->use_begin(), I->use_end(),
232 bind_obj(this, &SCCP::OperandChangedState));
235 // Process the basic block work list...
236 while (!BBWorkList.empty()) {
237 BasicBlock *BB = BBWorkList.back();
238 BBWorkList.pop_back();
240 //cerr << "\nPopped off BBWL: " << BB;
242 // If this block only has a single successor, mark it as executable as
243 // well... if not, terminate the do loop.
245 if (BB->getTerminator()->getNumSuccessors() == 1)
246 markExecutable(BB->getTerminator()->getSuccessor(0));
248 // Notify all instructions in this basic block that they are newly
255 for (Function::iterator BBI = M->begin(), BBEnd = M->end();
257 if (!BBExecutable.count(*BBI))
258 cerr << "BasicBlock Dead:" << *BBI;
262 // Iterate over all of the instructions in a function, replacing them with
263 // constants if we have found them to be of constant values.
265 bool MadeChanges = false;
266 for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
267 BasicBlock *BB = *MI;
268 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
269 Instruction *Inst = *BI;
270 InstVal &IV = ValueState[Inst];
271 if (IV.isConstant()) {
272 Constant *Const = IV.getConstant();
273 // cerr << "Constant: " << Inst << " is: " << Const;
275 // Replaces all of the uses of a variable with uses of the constant.
276 Inst->replaceAllUsesWith(Const);
278 // Remove the operator from the list of definitions...
279 BB->getInstList().remove(BI);
281 // The new constant inherits the old name of the operator...
282 if (Inst->hasName() && !Const->hasName())
283 Const->setName(Inst->getName(), M->getSymbolTableSure());
285 // Delete the operator now...
288 // Hey, we just changed something!
290 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) {
291 MadeChanges |= ConstantFoldTerminator(BB, BI, TI);
298 // Merge identical constants last: this is important because we may have just
299 // introduced constants that already exist, and we don't want to pollute later
300 // stages with extraneous constants.
306 // visit Implementations - Something changed in this instruction... Either an
307 // operand made a transition, or the instruction is newly executable. Change
308 // the value type of I to reflect these changes if appropriate. This method
309 // makes sure to do the following actions:
311 // 1. If a phi node merges two constants in, and has conflicting value coming
312 // from different branches, or if the PHI node merges in an overdefined
313 // value, then the PHI node becomes overdefined.
314 // 2. If a phi node merges only constants in, and they all agree on value, the
315 // PHI node becomes a constant value equal to that.
316 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
317 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
318 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
319 // 6. If a conditional branch has a value that is constant, make the selected
320 // destination executable
321 // 7. If a conditional branch has a value that is overdefined, make all
322 // successors executable.
325 void SCCP::visitPHINode(PHINode *PN) {
326 unsigned NumValues = PN->getNumIncomingValues(), i;
327 InstVal *OperandIV = 0;
329 // Look at all of the executable operands of the PHI node. If any of them
330 // are overdefined, the PHI becomes overdefined as well. If they are all
331 // constant, and they agree with each other, the PHI becomes the identical
332 // constant. If they are constant and don't agree, the PHI is overdefined.
333 // If there are no executable operands, the PHI remains undefined.
335 for (i = 0; i < NumValues; ++i) {
336 if (BBExecutable.count(PN->getIncomingBlock(i))) {
337 InstVal &IV = getValueState(PN->getIncomingValue(i));
338 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
339 if (IV.isOverdefined()) { // PHI node becomes overdefined!
344 if (OperandIV == 0) { // Grab the first value...
346 } else { // Another value is being merged in!
347 // There is already a reachable operand. If we conflict with it,
348 // then the PHI node becomes overdefined. If we agree with it, we
351 // Check to see if there are two different constants merging...
352 if (IV.getConstant() != OperandIV->getConstant()) {
353 // Yes there is. This means the PHI node is not constant.
354 // You must be overdefined poor PHI.
356 markOverdefined(PN); // The PHI node now becomes overdefined
357 return; // I'm done analyzing you
363 // If we exited the loop, this means that the PHI node only has constant
364 // arguments that agree with each other(and OperandIV is a pointer to one
365 // of their InstVal's) or OperandIV is null because there are no defined
366 // incoming arguments. If this is the case, the PHI remains undefined.
369 assert(OperandIV->isConstant() && "Should only be here for constants!");
370 markConstant(PN, OperandIV->getConstant()); // Aquire operand value
374 void SCCP::visitBranchInst(BranchInst *BI) {
375 if (BI->isUnconditional())
376 return; // Unconditional branches are already handled!
378 InstVal &BCValue = getValueState(BI->getCondition());
379 if (BCValue.isOverdefined()) {
380 // Overdefined condition variables mean the branch could go either way.
381 markExecutable(BI->getSuccessor(0));
382 markExecutable(BI->getSuccessor(1));
383 } else if (BCValue.isConstant()) {
384 // Constant condition variables mean the branch can only go a single way.
385 if (BCValue.getConstant() == ConstantBool::True)
386 markExecutable(BI->getSuccessor(0));
388 markExecutable(BI->getSuccessor(1));
392 void SCCP::visitSwitchInst(SwitchInst *SI) {
393 InstVal &SCValue = getValueState(SI->getCondition());
394 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe
395 for(unsigned i = 0, E = SI->getNumSuccessors(); i != E; ++i)
396 markExecutable(SI->getSuccessor(i));
397 } else if (SCValue.isConstant()) {
398 Constant *CPV = SCValue.getConstant();
399 // Make sure to skip the "default value" which isn't a value
400 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
401 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
402 markExecutable(SI->getSuccessor(i));
407 // Constant value not equal to any of the branches... must execute
408 // default branch then...
409 markExecutable(SI->getDefaultDest());
413 void SCCP::visitUnaryOperator(Instruction *I) {
414 Value *V = I->getOperand(0);
415 InstVal &VState = getValueState(V);
416 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
418 } else if (VState.isConstant()) { // Propogate constant value
419 Constant *Result = isa<CastInst>(I)
420 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
421 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
424 // This instruction constant folds!
425 markConstant(I, Result);
427 markOverdefined(I); // Don't know how to fold this instruction. :(
432 // Handle BinaryOperators and Shift Instructions...
433 void SCCP::visitBinaryOperator(Instruction *I) {
434 InstVal &V1State = getValueState(I->getOperand(0));
435 InstVal &V2State = getValueState(I->getOperand(1));
436 if (V1State.isOverdefined() || V2State.isOverdefined()) {
438 } else if (V1State.isConstant() && V2State.isConstant()) {
439 Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(),
440 V1State.getConstant(),
441 V2State.getConstant());
443 markConstant(I, Result); // This instruction constant fold!s
445 markOverdefined(I); // Don't know how to fold this instruction. :(
449 // OperandChangedState - This method is invoked on all of the users of an
450 // instruction that was just changed state somehow.... Based on this
451 // information, we need to update the specified user of this instruction.
453 void SCCP::OperandChangedState(User *U) {
454 // Only instructions use other variable values!
455 Instruction *I = cast<Instruction>(U);
456 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet!
462 // SCCPPass - Use Sparse Conditional Constant Propogation
463 // to prove whether a value is constant and whether blocks are used.
465 struct SCCPPass : public FunctionPass {
466 const char *getPassName() const {
467 return "Sparse Conditional Constant Propogation";
470 inline bool runOnFunction(Function *F) {
474 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
475 // FIXME: SCCP does not preserve the CFG because it folds terminators!
481 Pass *createSCCPPass() {
482 return new SCCPPass();