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/ConstantVals.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 "Support/STLExtras.h"
35 // InstVal class - This class represents the different lattice values that an
36 // instruction may occupy. It is a simple class with value semantics. The
37 // potential constant value that is pointed to is owned by the constant pool
38 // for the method being optimized.
42 undefined, // This instruction has no known value
43 constant, // This instruction has a constant value
44 // Range, // This instruction is known to fall within a range
45 overdefined // This instruction has an unknown value
46 } LatticeValue; // The current lattice position
47 Constant *ConstantVal; // If Constant value, the current value
49 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
51 // markOverdefined - Return true if this is a new status to be in...
52 inline bool markOverdefined() {
53 if (LatticeValue != overdefined) {
54 LatticeValue = overdefined;
60 // markConstant - Return true if this is a new status for us...
61 inline bool markConstant(Constant *V) {
62 if (LatticeValue != constant) {
63 LatticeValue = constant;
67 assert(ConstantVal == V && "Marking constant with different value");
72 inline bool isUndefined() const { return LatticeValue == undefined; }
73 inline bool isConstant() const { return LatticeValue == constant; }
74 inline bool isOverdefined() const { return LatticeValue == overdefined; }
76 inline Constant *getConstant() const { return ConstantVal; }
81 //===----------------------------------------------------------------------===//
84 // This class does all of the work of Sparse Conditional Constant Propogation.
85 // It's public interface consists of a constructor and a doSCCP() method.
88 Function *M; // The function that we are working on
90 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
91 std::map<Value*, InstVal> ValueState; // The state each value is in...
93 std::vector<Instruction*> InstWorkList;// The instruction work list
94 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
96 //===--------------------------------------------------------------------===//
97 // The public interface for this class
101 // SCCP Ctor - Save the method to operate on...
102 inline SCCP(Function *f) : M(f) {}
104 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
105 // return true if the method was modified.
108 //===--------------------------------------------------------------------===//
109 // The implementation of this class
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 // UpdateInstruction - 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 UpdateInstruction(Instruction *I);
177 // OperandChangedState - This method is invoked on all of the users of an
178 // instruction that was just changed state somehow.... Based on this
179 // information, we need to update the specified user of this instruction.
181 void OperandChangedState(User *U);
185 //===----------------------------------------------------------------------===//
186 // SCCP Class Implementation
189 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
190 // return true if the method was modified.
192 bool SCCP::doSCCP() {
193 // Mark the first block of the method as being executable...
194 markExecutable(M->front());
196 // Process the work lists until their are empty!
197 while (!BBWorkList.empty() || !InstWorkList.empty()) {
198 // Process the instruction work list...
199 while (!InstWorkList.empty()) {
200 Instruction *I = InstWorkList.back();
201 InstWorkList.pop_back();
203 //cerr << "\nPopped off I-WL: " << I;
206 // "I" got into the work list because it either made the transition from
207 // bottom to constant, or to Overdefined.
209 // Update all of the users of this instruction's value...
211 for_each(I->use_begin(), I->use_end(),
212 bind_obj(this, &SCCP::OperandChangedState));
215 // Process the basic block work list...
216 while (!BBWorkList.empty()) {
217 BasicBlock *BB = BBWorkList.back();
218 BBWorkList.pop_back();
220 //cerr << "\nPopped off BBWL: " << BB;
222 // If this block only has a single successor, mark it as executable as
223 // well... if not, terminate the do loop.
225 if (BB->getTerminator()->getNumSuccessors() == 1)
226 markExecutable(BB->getTerminator()->getSuccessor(0));
228 // Loop over all of the instructions and notify them that they are newly
230 for_each(BB->begin(), BB->end(),
231 bind_obj(this, &SCCP::UpdateInstruction));
236 for (Function::iterator BBI = M->begin(), BBEnd = M->end();
238 if (!BBExecutable.count(*BBI))
239 cerr << "BasicBlock Dead:" << *BBI;
243 // Iterate over all of the instructions in a method, replacing them with
244 // constants if we have found them to be of constant values.
246 bool MadeChanges = false;
247 for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
248 BasicBlock *BB = *MI;
249 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
250 Instruction *Inst = *BI;
251 InstVal &IV = ValueState[Inst];
252 if (IV.isConstant()) {
253 Constant *Const = IV.getConstant();
254 // cerr << "Constant: " << Inst << " is: " << Const;
256 // Replaces all of the uses of a variable with uses of the constant.
257 Inst->replaceAllUsesWith(Const);
259 // Remove the operator from the list of definitions...
260 BB->getInstList().remove(BI);
262 // The new constant inherits the old name of the operator...
263 if (Inst->hasName() && !Const->hasName())
264 Const->setName(Inst->getName(), M->getSymbolTableSure());
266 // Delete the operator now...
269 // Hey, we just changed something!
271 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) {
272 MadeChanges |= ConstantFoldTerminator(BB, BI, TI);
279 // Merge identical constants last: this is important because we may have just
280 // introduced constants that already exist, and we don't want to pollute later
281 // stages with extraneous constants.
287 // UpdateInstruction - Something changed in this instruction... Either an
288 // operand made a transition, or the instruction is newly executable. Change
289 // the value type of I to reflect these changes if appropriate. This method
290 // makes sure to do the following actions:
292 // 1. If a phi node merges two constants in, and has conflicting value coming
293 // from different branches, or if the PHI node merges in an overdefined
294 // value, then the PHI node becomes overdefined.
295 // 2. If a phi node merges only constants in, and they all agree on value, the
296 // PHI node becomes a constant value equal to that.
297 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
298 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
299 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
300 // 6. If a conditional branch has a value that is constant, make the selected
301 // destination executable
302 // 7. If a conditional branch has a value that is overdefined, make all
303 // successors executable.
305 void SCCP::UpdateInstruction(Instruction *I) {
306 InstVal &IValue = ValueState[I];
307 if (IValue.isOverdefined())
308 return; // If already overdefined, we aren't going to effect anything
310 switch (I->getOpcode()) {
311 //===-----------------------------------------------------------------===//
312 // Handle PHI nodes...
314 case Instruction::PHINode: {
315 PHINode *PN = cast<PHINode>(I);
316 unsigned NumValues = PN->getNumIncomingValues(), i;
317 InstVal *OperandIV = 0;
319 // Look at all of the executable operands of the PHI node. If any of them
320 // are overdefined, the PHI becomes overdefined as well. If they are all
321 // constant, and they agree with each other, the PHI becomes the identical
322 // constant. If they are constant and don't agree, the PHI is overdefined.
323 // If there are no executable operands, the PHI remains undefined.
325 for (i = 0; i < NumValues; ++i) {
326 if (BBExecutable.count(PN->getIncomingBlock(i))) {
327 InstVal &IV = getValueState(PN->getIncomingValue(i));
328 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
329 if (IV.isOverdefined()) { // PHI node becomes overdefined!
334 if (OperandIV == 0) { // Grab the first value...
336 } else { // Another value is being merged in!
337 // There is already a reachable operand. If we conflict with it,
338 // then the PHI node becomes overdefined. If we agree with it, we
341 // Check to see if there are two different constants merging...
342 if (IV.getConstant() != OperandIV->getConstant()) {
343 // Yes there is. This means the PHI node is not constant.
344 // You must be overdefined poor PHI.
346 markOverdefined(I); // The PHI node now becomes overdefined
347 return; // I'm done analyzing you
353 // If we exited the loop, this means that the PHI node only has constant
354 // arguments that agree with each other(and OperandIV is a pointer to one
355 // of their InstVal's) or OperandIV is null because there are no defined
356 // incoming arguments. If this is the case, the PHI remains undefined.
359 assert(OperandIV->isConstant() && "Should only be here for constants!");
360 markConstant(I, OperandIV->getConstant()); // Aquire operand value
365 //===-----------------------------------------------------------------===//
366 // Handle instructions that unconditionally provide overdefined values...
368 case Instruction::Malloc:
369 case Instruction::Free:
370 case Instruction::Alloca:
371 case Instruction::Load:
372 case Instruction::Store:
374 case Instruction::Call:
375 case Instruction::Invoke:
376 markOverdefined(I); // Memory and call's are all overdefined
379 //===-----------------------------------------------------------------===//
380 // Handle Terminator instructions...
382 case Instruction::Ret: return; // Function return doesn't affect anything
383 case Instruction::Br: { // Handle conditional branches...
384 BranchInst *BI = cast<BranchInst>(I);
385 if (BI->isUnconditional())
386 return; // Unconditional branches are already handled!
388 InstVal &BCValue = getValueState(BI->getCondition());
389 if (BCValue.isOverdefined()) {
390 // Overdefined condition variables mean the branch could go either way.
391 markExecutable(BI->getSuccessor(0));
392 markExecutable(BI->getSuccessor(1));
393 } else if (BCValue.isConstant()) {
394 // Constant condition variables mean the branch can only go a single way.
395 ConstantBool *CPB = cast<ConstantBool>(BCValue.getConstant());
396 if (CPB->getValue()) // If the branch condition is TRUE...
397 markExecutable(BI->getSuccessor(0));
398 else // Else if the br cond is FALSE...
399 markExecutable(BI->getSuccessor(1));
404 case Instruction::Switch: {
405 SwitchInst *SI = cast<SwitchInst>(I);
406 InstVal &SCValue = getValueState(SI->getCondition());
407 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe
408 for(unsigned i = 0; BasicBlock *Succ = SI->getSuccessor(i); ++i)
409 markExecutable(Succ);
410 } else if (SCValue.isConstant()) {
411 Constant *CPV = SCValue.getConstant();
412 // Make sure to skip the "default value" which isn't a value
413 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
414 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
415 markExecutable(SI->getSuccessor(i));
420 // Constant value not equal to any of the branches... must execute
421 // default branch then...
422 markExecutable(SI->getDefaultDest());
427 default: break; // Handle math operators as groups.
428 } // end switch(I->getOpcode())
431 //===-------------------------------------------------------------------===//
432 // Handle Unary and cast instructions...
434 if (isa<UnaryOperator>(I) || isa<CastInst>(I)) {
435 Value *V = I->getOperand(0);
436 InstVal &VState = getValueState(V);
437 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
439 } else if (VState.isConstant()) { // Propogate constant value
440 Constant *Result = isa<CastInst>(I)
441 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
442 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
445 // This instruction constant folds!
446 markConstant(I, Result);
448 markOverdefined(I); // Don't know how to fold this instruction. :(
455 //===-----------------------------------------------------------------===//
456 // Handle GetElementPtr instructions...
458 if (isa<GetElementPtrInst>(I)) {
464 //===-----------------------------------------------------------------===//
465 // Handle Binary instructions...
467 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) {
468 Value *V1 = I->getOperand(0);
469 Value *V2 = I->getOperand(1);
471 InstVal &V1State = getValueState(V1);
472 InstVal &V2State = getValueState(V2);
473 if (V1State.isOverdefined() || V2State.isOverdefined()) {
475 } else if (V1State.isConstant() && V2State.isConstant()) {
477 ConstantFoldBinaryInstruction(I->getOpcode(),
478 V1State.getConstant(),
479 V2State.getConstant());
481 // This instruction constant folds!
482 markConstant(I, Result);
484 markOverdefined(I); // Don't know how to fold this instruction. :(
490 // Shouldn't get here... either the switch statement or one of the group
491 // handlers should have kicked in...
493 cerr << "SCCP: Don't know how to handle: " << I;
494 markOverdefined(I); // Just in case
499 // OperandChangedState - This method is invoked on all of the users of an
500 // instruction that was just changed state somehow.... Based on this
501 // information, we need to update the specified user of this instruction.
503 void SCCP::OperandChangedState(User *U) {
504 // Only instructions use other variable values!
505 Instruction *I = cast<Instruction>(U);
506 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet!
508 UpdateInstruction(I);
512 // SCCPPass - Use Sparse Conditional Constant Propogation
513 // to prove whether a value is constant and whether blocks are used.
515 struct SCCPPass : public MethodPass {
516 inline bool runOnMethod(Function *F) {
523 Pass *createSCCPPass() {
524 return new SCCPPass();