SCCP.cpp revision 6428a27ee3d54660a315c864d98b821d0607dfca
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/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" 29#include <algorithm> 30#include <map> 31#include <set> 32#include <iostream> 33using std::cerr; 34 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. 39// 40class InstVal { 41 enum { 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 48public: 49 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {} 50 51 // markOverdefined - Return true if this is a new status to be in... 52 inline bool markOverdefined() { 53 if (LatticeValue != overdefined) { 54 LatticeValue = overdefined; 55 return true; 56 } 57 return false; 58 } 59 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; 64 ConstantVal = V; 65 return true; 66 } else { 67 assert(ConstantVal == V && "Marking constant with different value"); 68 } 69 return false; 70 } 71 72 inline bool isUndefined() const { return LatticeValue == undefined; } 73 inline bool isConstant() const { return LatticeValue == constant; } 74 inline bool isOverdefined() const { return LatticeValue == overdefined; } 75 76 inline Constant *getConstant() const { return ConstantVal; } 77}; 78 79 80 81//===----------------------------------------------------------------------===// 82// SCCP Class 83// 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. 86// 87class SCCP { 88 Function *M; // The function that we are working on 89 90 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable 91 std::map<Value*, InstVal> ValueState; // The state each value is in... 92 93 std::vector<Instruction*> InstWorkList;// The instruction work list 94 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list 95 96 //===--------------------------------------------------------------------===// 97 // The public interface for this class 98 // 99public: 100 101 // SCCP Ctor - Save the method to operate on... 102 inline SCCP(Function *f) : M(f) {} 103 104 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 105 // return true if the method was modified. 106 bool doSCCP(); 107 108 //===--------------------------------------------------------------------===// 109 // The implementation of this class 110 // 111private: 112 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. 116 // 117 inline bool markConstant(Instruction *I, Constant *V) { 118 //cerr << "markConstant: " << V << " = " << I; 119 if (ValueState[I].markConstant(V)) { 120 InstWorkList.push_back(I); 121 return true; 122 } 123 return false; 124 } 125 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. 129 // 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 135 } 136 return true; 137 } 138 return false; 139 } 140 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. 146 // 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 150 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(); 155 } 156 // All others are underdefined by default... 157 return ValueState[V]; 158 } 159 160 // markExecutable - Mark a basic block as executable, adding it to the BB 161 // work list if it is not already executable... 162 // 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! 168 } 169 170 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. 174 // 175 void UpdateInstruction(Instruction *I); 176 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. 180 // 181 void OperandChangedState(User *U); 182}; 183 184 185//===----------------------------------------------------------------------===// 186// SCCP Class Implementation 187 188 189// doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 190// return true if the method was modified. 191// 192bool SCCP::doSCCP() { 193 // Mark the first block of the method as being executable... 194 markExecutable(M->front()); 195 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(); 202 203 //cerr << "\nPopped off I-WL: " << I; 204 205 206 // "I" got into the work list because it either made the transition from 207 // bottom to constant, or to Overdefined. 208 // 209 // Update all of the users of this instruction's value... 210 // 211 for_each(I->use_begin(), I->use_end(), 212 bind_obj(this, &SCCP::OperandChangedState)); 213 } 214 215 // Process the basic block work list... 216 while (!BBWorkList.empty()) { 217 BasicBlock *BB = BBWorkList.back(); 218 BBWorkList.pop_back(); 219 220 //cerr << "\nPopped off BBWL: " << BB; 221 222 // If this block only has a single successor, mark it as executable as 223 // well... if not, terminate the do loop. 224 // 225 if (BB->getTerminator()->getNumSuccessors() == 1) 226 markExecutable(BB->getTerminator()->getSuccessor(0)); 227 228 // Loop over all of the instructions and notify them that they are newly 229 // executable... 230 for_each(BB->begin(), BB->end(), 231 bind_obj(this, &SCCP::UpdateInstruction)); 232 } 233 } 234 235#if 0 236 for (Function::iterator BBI = M->begin(), BBEnd = M->end(); 237 BBI != BBEnd; ++BBI) 238 if (!BBExecutable.count(*BBI)) 239 cerr << "BasicBlock Dead:" << *BBI; 240#endif 241 242 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. 245 // 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; 255 256 // Replaces all of the uses of a variable with uses of the constant. 257 Inst->replaceAllUsesWith(Const); 258 259 // Remove the operator from the list of definitions... 260 BB->getInstList().remove(BI); 261 262 // The new constant inherits the old name of the operator... 263 if (Inst->hasName() && !Const->hasName()) 264 Const->setName(Inst->getName(), M->getSymbolTableSure()); 265 266 // Delete the operator now... 267 delete Inst; 268 269 // Hey, we just changed something! 270 MadeChanges = true; 271 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) { 272 MadeChanges |= ConstantFoldTerminator(BB, BI, TI); 273 } 274 275 ++BI; 276 } 277 } 278 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. 282 // 283 return MadeChanges; 284} 285 286 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: 291// 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. 304// 305void 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 309 310 switch (I->getOpcode()) { 311 //===-----------------------------------------------------------------===// 312 // Handle PHI nodes... 313 // 314 case Instruction::PHINode: { 315 PHINode *PN = cast<PHINode>(I); 316 unsigned NumValues = PN->getNumIncomingValues(), i; 317 InstVal *OperandIV = 0; 318 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. 324 // 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! 330 markOverdefined(PN); 331 return; 332 } 333 334 if (OperandIV == 0) { // Grab the first value... 335 OperandIV = &IV; 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 339 // can continue on. 340 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. 345 // 346 markOverdefined(I); // The PHI node now becomes overdefined 347 return; // I'm done analyzing you 348 } 349 } 350 } 351 } 352 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. 357 // 358 if (OperandIV) { 359 assert(OperandIV->isConstant() && "Should only be here for constants!"); 360 markConstant(I, OperandIV->getConstant()); // Aquire operand value 361 } 362 return; 363 } 364 365 //===-----------------------------------------------------------------===// 366 // Handle instructions that unconditionally provide overdefined values... 367 // 368 case Instruction::Malloc: 369 case Instruction::Free: 370 case Instruction::Alloca: 371 case Instruction::Load: 372 case Instruction::Store: 373 // TODO: getfield 374 case Instruction::Call: 375 case Instruction::Invoke: 376 markOverdefined(I); // Memory and call's are all overdefined 377 return; 378 379 //===-----------------------------------------------------------------===// 380 // Handle Terminator instructions... 381 // 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! 387 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)); 400 } 401 return; 402 } 403 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)); 416 return; 417 } 418 } 419 420 // Constant value not equal to any of the branches... must execute 421 // default branch then... 422 markExecutable(SI->getDefaultDest()); 423 } 424 return; 425 } 426 427 default: break; // Handle math operators as groups. 428 } // end switch(I->getOpcode()) 429 430 431 //===-------------------------------------------------------------------===// 432 // Handle Unary and cast instructions... 433 // 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 438 markOverdefined(I); 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()); 443 444 if (Result) { 445 // This instruction constant folds! 446 markConstant(I, Result); 447 } else { 448 markOverdefined(I); // Don't know how to fold this instruction. :( 449 } 450 } 451 return; 452 } 453 454 455 //===-----------------------------------------------------------------===// 456 // Handle GetElementPtr instructions... 457 // 458 if (isa<GetElementPtrInst>(I)) { 459 markOverdefined(I); 460 return; 461 } 462 463 464 //===-----------------------------------------------------------------===// 465 // Handle Binary instructions... 466 // 467 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) { 468 Value *V1 = I->getOperand(0); 469 Value *V2 = I->getOperand(1); 470 471 InstVal &V1State = getValueState(V1); 472 InstVal &V2State = getValueState(V2); 473 if (V1State.isOverdefined() || V2State.isOverdefined()) { 474 markOverdefined(I); 475 } else if (V1State.isConstant() && V2State.isConstant()) { 476 Constant *Result = 477 ConstantFoldBinaryInstruction(I->getOpcode(), 478 V1State.getConstant(), 479 V2State.getConstant()); 480 if (Result) { 481 // This instruction constant folds! 482 markConstant(I, Result); 483 } else { 484 markOverdefined(I); // Don't know how to fold this instruction. :( 485 } 486 } 487 return; 488 } 489 490 // Shouldn't get here... either the switch statement or one of the group 491 // handlers should have kicked in... 492 // 493 cerr << "SCCP: Don't know how to handle: " << I; 494 markOverdefined(I); // Just in case 495} 496 497 498 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. 502// 503void 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! 507 508 UpdateInstruction(I); 509} 510 511namespace { 512 // SCCPPass - Use Sparse Conditional Constant Propogation 513 // to prove whether a value is constant and whether blocks are used. 514 // 515 struct SCCPPass : public MethodPass { 516 inline bool runOnMethod(Function *F) { 517 SCCP S(F); 518 return S.doSCCP(); 519 } 520 }; 521} 522 523Pass *createSCCPPass() { 524 return new SCCPPass(); 525} 526