SCCP.cpp revision 0dbfc05a2aed61cdb1f83f74474749eb66e0856f
1//===- SCCP.cpp - Sparse Conditional Constant Propogation -----------------===// 2// 3// This file implements sparse conditional constant propogation and merging: 4// 5// Specifically, this: 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 11// 12// Notice that: 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. 15// 16//===----------------------------------------------------------------------===// 17 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" 28#include <algorithm> 29#include <set> 30#include <iostream> 31using std::cerr; 32 33// InstVal class - This class represents the different lattice values that an 34// instruction may occupy. It is a simple class with value semantics. 35// 36namespace { 37class InstVal { 38 enum { 39 undefined, // This instruction has no known value 40 constant, // This instruction has a constant value 41 // Range, // This instruction is known to fall within a range 42 overdefined // This instruction has an unknown value 43 } LatticeValue; // The current lattice position 44 Constant *ConstantVal; // If Constant value, the current value 45public: 46 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {} 47 48 // markOverdefined - Return true if this is a new status to be in... 49 inline bool markOverdefined() { 50 if (LatticeValue != overdefined) { 51 LatticeValue = overdefined; 52 return true; 53 } 54 return false; 55 } 56 57 // markConstant - Return true if this is a new status for us... 58 inline bool markConstant(Constant *V) { 59 if (LatticeValue != constant) { 60 LatticeValue = constant; 61 ConstantVal = V; 62 return true; 63 } else { 64 assert(ConstantVal == V && "Marking constant with different value"); 65 } 66 return false; 67 } 68 69 inline bool isUndefined() const { return LatticeValue == undefined; } 70 inline bool isConstant() const { return LatticeValue == constant; } 71 inline bool isOverdefined() const { return LatticeValue == overdefined; } 72 73 inline Constant *getConstant() const { return ConstantVal; } 74}; 75 76} // end anonymous namespace 77 78 79//===----------------------------------------------------------------------===// 80// SCCP Class 81// 82// This class does all of the work of Sparse Conditional Constant Propogation. 83// 84namespace { 85class SCCP : public FunctionPass, public InstVisitor<SCCP> { 86 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable 87 std::map<Value*, InstVal> ValueState; // The state each value is in... 88 89 std::vector<Instruction*> InstWorkList;// The instruction work list 90 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list 91public: 92 93 const char *getPassName() const { 94 return "Sparse Conditional Constant Propogation"; 95 } 96 97 // runOnFunction - Run the Sparse Conditional Constant Propogation algorithm, 98 // and return true if the function was modified. 99 // 100 bool runOnFunction(Function *F); 101 102 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 103 // FIXME: SCCP does not preserve the CFG because it folds terminators! 104 //AU.preservesCFG(); 105 } 106 107 108 //===--------------------------------------------------------------------===// 109 // The implementation of this class 110 // 111private: 112 friend class InstVisitor<SCCP>; // Allow callbacks from visitor 113 114 // markValueOverdefined - Make a value be marked as "constant". If the value 115 // is not already a constant, add it to the instruction work list so that 116 // the users of the instruction are updated later. 117 // 118 inline bool markConstant(Instruction *I, Constant *V) { 119 //cerr << "markConstant: " << V << " = " << I; 120 if (ValueState[I].markConstant(V)) { 121 InstWorkList.push_back(I); 122 return true; 123 } 124 return false; 125 } 126 127 // markValueOverdefined - Make a value be marked as "overdefined". If the 128 // value is not already overdefined, add it to the instruction work list so 129 // that the users of the instruction are updated later. 130 // 131 inline bool markOverdefined(Value *V) { 132 if (ValueState[V].markOverdefined()) { 133 if (Instruction *I = dyn_cast<Instruction>(V)) { 134 //cerr << "markOverdefined: " << V; 135 InstWorkList.push_back(I); // Only instructions go on the work list 136 } 137 return true; 138 } 139 return false; 140 } 141 142 // getValueState - Return the InstVal object that corresponds to the value. 143 // This function is neccesary because not all values should start out in the 144 // underdefined state... Argument's should be overdefined, and 145 // constants should be marked as constants. If a value is not known to be an 146 // Instruction object, then use this accessor to get its value from the map. 147 // 148 inline InstVal &getValueState(Value *V) { 149 std::map<Value*, InstVal>::iterator I = ValueState.find(V); 150 if (I != ValueState.end()) return I->second; // Common case, in the map 151 152 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant 153 ValueState[CPV].markConstant(CPV); 154 } else if (isa<Argument>(V)) { // Arguments are overdefined 155 ValueState[V].markOverdefined(); 156 } 157 // All others are underdefined by default... 158 return ValueState[V]; 159 } 160 161 // markExecutable - Mark a basic block as executable, adding it to the BB 162 // work list if it is not already executable... 163 // 164 void markExecutable(BasicBlock *BB) { 165 if (BBExecutable.count(BB)) return; 166 //cerr << "Marking BB Executable: " << BB; 167 BBExecutable.insert(BB); // Basic block is executable! 168 BBWorkList.push_back(BB); // Add the block to the work list! 169 } 170 171 172 // visit implementations - Something changed in this instruction... Either an 173 // operand made a transition, or the instruction is newly executable. Change 174 // the value type of I to reflect these changes if appropriate. 175 // 176 void visitPHINode(PHINode *I); 177 178 // Terminators 179 void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ } 180 void visitBranchInst(BranchInst *I); 181 void visitSwitchInst(SwitchInst *I); 182 183 void visitUnaryOperator(Instruction *I); 184 void visitCastInst(CastInst *I) { visitUnaryOperator(I); } 185 void visitBinaryOperator(Instruction *I); 186 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); } 187 188 // Instructions that cannot be folded away... 189 void visitMemAccessInst (Instruction *I) { markOverdefined(I); } 190 void visitCallInst (Instruction *I) { markOverdefined(I); } 191 void visitInvokeInst (Instruction *I) { markOverdefined(I); } 192 void visitAllocationInst(Instruction *I) { markOverdefined(I); } 193 void visitFreeInst (Instruction *I) { markOverdefined(I); } 194 195 void visitInstruction(Instruction *I) { 196 // If a new instruction is added to LLVM that we don't handle... 197 cerr << "SCCP: Don't know how to handle: " << I; 198 markOverdefined(I); // Just in case 199 } 200 201 // OperandChangedState - This method is invoked on all of the users of an 202 // instruction that was just changed state somehow.... Based on this 203 // information, we need to update the specified user of this instruction. 204 // 205 void OperandChangedState(User *U); 206}; 207} // end anonymous namespace 208 209 210// createSCCPPass - This is the public interface to this file... 211// 212Pass *createSCCPPass() { 213 return new SCCP(); 214} 215 216 217 218//===----------------------------------------------------------------------===// 219// SCCP Class Implementation 220 221 222// runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm, 223// and return true if the function was modified. 224// 225bool SCCP::runOnFunction(Function *F) { 226 // Mark the first block of the function as being executable... 227 markExecutable(F->front()); 228 229 // Process the work lists until their are empty! 230 while (!BBWorkList.empty() || !InstWorkList.empty()) { 231 // Process the instruction work list... 232 while (!InstWorkList.empty()) { 233 Instruction *I = InstWorkList.back(); 234 InstWorkList.pop_back(); 235 236 //cerr << "\nPopped off I-WL: " << I; 237 238 239 // "I" got into the work list because it either made the transition from 240 // bottom to constant, or to Overdefined. 241 // 242 // Update all of the users of this instruction's value... 243 // 244 for_each(I->use_begin(), I->use_end(), 245 bind_obj(this, &SCCP::OperandChangedState)); 246 } 247 248 // Process the basic block work list... 249 while (!BBWorkList.empty()) { 250 BasicBlock *BB = BBWorkList.back(); 251 BBWorkList.pop_back(); 252 253 //cerr << "\nPopped off BBWL: " << BB; 254 255 // If this block only has a single successor, mark it as executable as 256 // well... if not, terminate the do loop. 257 // 258 if (BB->getTerminator()->getNumSuccessors() == 1) 259 markExecutable(BB->getTerminator()->getSuccessor(0)); 260 261 // Notify all instructions in this basic block that they are newly 262 // executable. 263 visit(BB); 264 } 265 } 266 267#if 0 268 for (Function::iterator BBI = F->begin(), BBEnd = F->end(); 269 BBI != BBEnd; ++BBI) 270 if (!BBExecutable.count(*BBI)) 271 cerr << "BasicBlock Dead:" << *BBI; 272#endif 273 274 275 // Iterate over all of the instructions in a function, replacing them with 276 // constants if we have found them to be of constant values. 277 // 278 bool MadeChanges = false; 279 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) { 280 BasicBlock *BB = *FI; 281 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) { 282 Instruction *Inst = *BI; 283 InstVal &IV = ValueState[Inst]; 284 if (IV.isConstant()) { 285 Constant *Const = IV.getConstant(); 286 // cerr << "Constant: " << Inst << " is: " << Const; 287 288 // Replaces all of the uses of a variable with uses of the constant. 289 Inst->replaceAllUsesWith(Const); 290 291 // Remove the operator from the list of definitions... 292 BB->getInstList().remove(BI); 293 294 // The new constant inherits the old name of the operator... 295 if (Inst->hasName() && !Const->hasName()) 296 Const->setName(Inst->getName(), F->getSymbolTableSure()); 297 298 // Delete the operator now... 299 delete Inst; 300 301 // Hey, we just changed something! 302 MadeChanges = true; 303 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) { 304 MadeChanges |= ConstantFoldTerminator(BB, BI, TI); 305 } 306 307 ++BI; 308 } 309 } 310 311 // Reset state so that the next invokation will have empty data structures 312 BBExecutable.clear(); 313 ValueState.clear(); 314 315 // Merge identical constants last: this is important because we may have just 316 // introduced constants that already exist, and we don't want to pollute later 317 // stages with extraneous constants. 318 // 319 return MadeChanges; 320} 321 322 323// visit Implementations - Something changed in this instruction... Either an 324// operand made a transition, or the instruction is newly executable. Change 325// the value type of I to reflect these changes if appropriate. This method 326// makes sure to do the following actions: 327// 328// 1. If a phi node merges two constants in, and has conflicting value coming 329// from different branches, or if the PHI node merges in an overdefined 330// value, then the PHI node becomes overdefined. 331// 2. If a phi node merges only constants in, and they all agree on value, the 332// PHI node becomes a constant value equal to that. 333// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 334// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 335// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 336// 6. If a conditional branch has a value that is constant, make the selected 337// destination executable 338// 7. If a conditional branch has a value that is overdefined, make all 339// successors executable. 340// 341 342void SCCP::visitPHINode(PHINode *PN) { 343 unsigned NumValues = PN->getNumIncomingValues(), i; 344 InstVal *OperandIV = 0; 345 346 // Look at all of the executable operands of the PHI node. If any of them 347 // are overdefined, the PHI becomes overdefined as well. If they are all 348 // constant, and they agree with each other, the PHI becomes the identical 349 // constant. If they are constant and don't agree, the PHI is overdefined. 350 // If there are no executable operands, the PHI remains undefined. 351 // 352 for (i = 0; i < NumValues; ++i) { 353 if (BBExecutable.count(PN->getIncomingBlock(i))) { 354 InstVal &IV = getValueState(PN->getIncomingValue(i)); 355 if (IV.isUndefined()) continue; // Doesn't influence PHI node. 356 if (IV.isOverdefined()) { // PHI node becomes overdefined! 357 markOverdefined(PN); 358 return; 359 } 360 361 if (OperandIV == 0) { // Grab the first value... 362 OperandIV = &IV; 363 } else { // Another value is being merged in! 364 // There is already a reachable operand. If we conflict with it, 365 // then the PHI node becomes overdefined. If we agree with it, we 366 // can continue on. 367 368 // Check to see if there are two different constants merging... 369 if (IV.getConstant() != OperandIV->getConstant()) { 370 // Yes there is. This means the PHI node is not constant. 371 // You must be overdefined poor PHI. 372 // 373 markOverdefined(PN); // The PHI node now becomes overdefined 374 return; // I'm done analyzing you 375 } 376 } 377 } 378 } 379 380 // If we exited the loop, this means that the PHI node only has constant 381 // arguments that agree with each other(and OperandIV is a pointer to one 382 // of their InstVal's) or OperandIV is null because there are no defined 383 // incoming arguments. If this is the case, the PHI remains undefined. 384 // 385 if (OperandIV) { 386 assert(OperandIV->isConstant() && "Should only be here for constants!"); 387 markConstant(PN, OperandIV->getConstant()); // Aquire operand value 388 } 389} 390 391void SCCP::visitBranchInst(BranchInst *BI) { 392 if (BI->isUnconditional()) 393 return; // Unconditional branches are already handled! 394 395 InstVal &BCValue = getValueState(BI->getCondition()); 396 if (BCValue.isOverdefined()) { 397 // Overdefined condition variables mean the branch could go either way. 398 markExecutable(BI->getSuccessor(0)); 399 markExecutable(BI->getSuccessor(1)); 400 } else if (BCValue.isConstant()) { 401 // Constant condition variables mean the branch can only go a single way. 402 if (BCValue.getConstant() == ConstantBool::True) 403 markExecutable(BI->getSuccessor(0)); 404 else 405 markExecutable(BI->getSuccessor(1)); 406 } 407} 408 409void SCCP::visitSwitchInst(SwitchInst *SI) { 410 InstVal &SCValue = getValueState(SI->getCondition()); 411 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe 412 for(unsigned i = 0, E = SI->getNumSuccessors(); i != E; ++i) 413 markExecutable(SI->getSuccessor(i)); 414 } else if (SCValue.isConstant()) { 415 Constant *CPV = SCValue.getConstant(); 416 // Make sure to skip the "default value" which isn't a value 417 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) { 418 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch... 419 markExecutable(SI->getSuccessor(i)); 420 return; 421 } 422 } 423 424 // Constant value not equal to any of the branches... must execute 425 // default branch then... 426 markExecutable(SI->getDefaultDest()); 427 } 428} 429 430void SCCP::visitUnaryOperator(Instruction *I) { 431 Value *V = I->getOperand(0); 432 InstVal &VState = getValueState(V); 433 if (VState.isOverdefined()) { // Inherit overdefinedness of operand 434 markOverdefined(I); 435 } else if (VState.isConstant()) { // Propogate constant value 436 Constant *Result = isa<CastInst>(I) 437 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType()) 438 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant()); 439 440 if (Result) { 441 // This instruction constant folds! 442 markConstant(I, Result); 443 } else { 444 markOverdefined(I); // Don't know how to fold this instruction. :( 445 } 446 } 447} 448 449// Handle BinaryOperators and Shift Instructions... 450void SCCP::visitBinaryOperator(Instruction *I) { 451 InstVal &V1State = getValueState(I->getOperand(0)); 452 InstVal &V2State = getValueState(I->getOperand(1)); 453 if (V1State.isOverdefined() || V2State.isOverdefined()) { 454 markOverdefined(I); 455 } else if (V1State.isConstant() && V2State.isConstant()) { 456 Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(), 457 V1State.getConstant(), 458 V2State.getConstant()); 459 if (Result) 460 markConstant(I, Result); // This instruction constant fold!s 461 else 462 markOverdefined(I); // Don't know how to fold this instruction. :( 463 } 464} 465 466// OperandChangedState - This method is invoked on all of the users of an 467// instruction that was just changed state somehow.... Based on this 468// information, we need to update the specified user of this instruction. 469// 470void SCCP::OperandChangedState(User *U) { 471 // Only instructions use other variable values! 472 Instruction *I = cast<Instruction>(U); 473 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet! 474 475 visit(I); 476} 477