1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements sparse conditional constant propagation and merging: 11 // 12 // Specifically, this: 13 // * Assumes values are constant unless proven otherwise 14 // * Assumes BasicBlocks are dead unless proven otherwise 15 // * Proves values to be constant, and replaces them with constants 16 // * Proves conditional branches to be unconditional 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Transforms/Scalar.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/DenseSet.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/Analysis/ConstantFolding.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/IR/CallSite.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/InstVisitor.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/Pass.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Transforms/IPO.h" 40 #include "llvm/Transforms/Utils/Local.h" 41 #include <algorithm> 42 using namespace llvm; 43 44 #define DEBUG_TYPE "sccp" 45 46 STATISTIC(NumInstRemoved, "Number of instructions removed"); 47 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable"); 48 49 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP"); 50 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP"); 51 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP"); 52 53 namespace { 54 /// LatticeVal class - This class represents the different lattice values that 55 /// an LLVM value may occupy. It is a simple class with value semantics. 56 /// 57 class LatticeVal { 58 enum LatticeValueTy { 59 /// undefined - This LLVM Value has no known value yet. 60 undefined, 61 62 /// constant - This LLVM Value has a specific constant value. 63 constant, 64 65 /// forcedconstant - This LLVM Value was thought to be undef until 66 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged 67 /// with another (different) constant, it goes to overdefined, instead of 68 /// asserting. 69 forcedconstant, 70 71 /// overdefined - This instruction is not known to be constant, and we know 72 /// it has a value. 73 overdefined 74 }; 75 76 /// Val: This stores the current lattice value along with the Constant* for 77 /// the constant if this is a 'constant' or 'forcedconstant' value. 78 PointerIntPair<Constant *, 2, LatticeValueTy> Val; 79 80 LatticeValueTy getLatticeValue() const { 81 return Val.getInt(); 82 } 83 84 public: 85 LatticeVal() : Val(nullptr, undefined) {} 86 87 bool isUndefined() const { return getLatticeValue() == undefined; } 88 bool isConstant() const { 89 return getLatticeValue() == constant || getLatticeValue() == forcedconstant; 90 } 91 bool isOverdefined() const { return getLatticeValue() == overdefined; } 92 93 Constant *getConstant() const { 94 assert(isConstant() && "Cannot get the constant of a non-constant!"); 95 return Val.getPointer(); 96 } 97 98 /// markOverdefined - Return true if this is a change in status. 99 bool markOverdefined() { 100 if (isOverdefined()) 101 return false; 102 103 Val.setInt(overdefined); 104 return true; 105 } 106 107 /// markConstant - Return true if this is a change in status. 108 bool markConstant(Constant *V) { 109 if (getLatticeValue() == constant) { // Constant but not forcedconstant. 110 assert(getConstant() == V && "Marking constant with different value"); 111 return false; 112 } 113 114 if (isUndefined()) { 115 Val.setInt(constant); 116 assert(V && "Marking constant with NULL"); 117 Val.setPointer(V); 118 } else { 119 assert(getLatticeValue() == forcedconstant && 120 "Cannot move from overdefined to constant!"); 121 // Stay at forcedconstant if the constant is the same. 122 if (V == getConstant()) return false; 123 124 // Otherwise, we go to overdefined. Assumptions made based on the 125 // forced value are possibly wrong. Assuming this is another constant 126 // could expose a contradiction. 127 Val.setInt(overdefined); 128 } 129 return true; 130 } 131 132 /// getConstantInt - If this is a constant with a ConstantInt value, return it 133 /// otherwise return null. 134 ConstantInt *getConstantInt() const { 135 if (isConstant()) 136 return dyn_cast<ConstantInt>(getConstant()); 137 return nullptr; 138 } 139 140 void markForcedConstant(Constant *V) { 141 assert(isUndefined() && "Can't force a defined value!"); 142 Val.setInt(forcedconstant); 143 Val.setPointer(V); 144 } 145 }; 146 } // end anonymous namespace. 147 148 149 namespace { 150 151 //===----------------------------------------------------------------------===// 152 // 153 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional 154 /// Constant Propagation. 155 /// 156 class SCCPSolver : public InstVisitor<SCCPSolver> { 157 const DataLayout &DL; 158 const TargetLibraryInfo *TLI; 159 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable. 160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in. 161 162 /// StructValueState - This maintains ValueState for values that have 163 /// StructType, for example for formal arguments, calls, insertelement, etc. 164 /// 165 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState; 166 167 /// GlobalValue - If we are tracking any values for the contents of a global 168 /// variable, we keep a mapping from the constant accessor to the element of 169 /// the global, to the currently known value. If the value becomes 170 /// overdefined, it's entry is simply removed from this map. 171 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals; 172 173 /// TrackedRetVals - If we are tracking arguments into and the return 174 /// value out of a function, it will have an entry in this map, indicating 175 /// what the known return value for the function is. 176 DenseMap<Function*, LatticeVal> TrackedRetVals; 177 178 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions 179 /// that return multiple values. 180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals; 181 182 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is 183 /// represented here for efficient lookup. 184 SmallPtrSet<Function*, 16> MRVFunctionsTracked; 185 186 /// TrackingIncomingArguments - This is the set of functions for whose 187 /// arguments we make optimistic assumptions about and try to prove as 188 /// constants. 189 SmallPtrSet<Function*, 16> TrackingIncomingArguments; 190 191 /// The reason for two worklists is that overdefined is the lowest state 192 /// on the lattice, and moving things to overdefined as fast as possible 193 /// makes SCCP converge much faster. 194 /// 195 /// By having a separate worklist, we accomplish this because everything 196 /// possibly overdefined will become overdefined at the soonest possible 197 /// point. 198 SmallVector<Value*, 64> OverdefinedInstWorkList; 199 SmallVector<Value*, 64> InstWorkList; 200 201 202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list 203 204 /// KnownFeasibleEdges - Entries in this set are edges which have already had 205 /// PHI nodes retriggered. 206 typedef std::pair<BasicBlock*, BasicBlock*> Edge; 207 DenseSet<Edge> KnownFeasibleEdges; 208 public: 209 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli) 210 : DL(DL), TLI(tli) {} 211 212 /// MarkBlockExecutable - This method can be used by clients to mark all of 213 /// the blocks that are known to be intrinsically live in the processed unit. 214 /// 215 /// This returns true if the block was not considered live before. 216 bool MarkBlockExecutable(BasicBlock *BB) { 217 if (!BBExecutable.insert(BB).second) 218 return false; 219 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n'); 220 BBWorkList.push_back(BB); // Add the block to the work list! 221 return true; 222 } 223 224 /// TrackValueOfGlobalVariable - Clients can use this method to 225 /// inform the SCCPSolver that it should track loads and stores to the 226 /// specified global variable if it can. This is only legal to call if 227 /// performing Interprocedural SCCP. 228 void TrackValueOfGlobalVariable(GlobalVariable *GV) { 229 // We only track the contents of scalar globals. 230 if (GV->getType()->getElementType()->isSingleValueType()) { 231 LatticeVal &IV = TrackedGlobals[GV]; 232 if (!isa<UndefValue>(GV->getInitializer())) 233 IV.markConstant(GV->getInitializer()); 234 } 235 } 236 237 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into 238 /// and out of the specified function (which cannot have its address taken), 239 /// this method must be called. 240 void AddTrackedFunction(Function *F) { 241 // Add an entry, F -> undef. 242 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) { 243 MRVFunctionsTracked.insert(F); 244 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 245 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i), 246 LatticeVal())); 247 } else 248 TrackedRetVals.insert(std::make_pair(F, LatticeVal())); 249 } 250 251 void AddArgumentTrackedFunction(Function *F) { 252 TrackingIncomingArguments.insert(F); 253 } 254 255 /// Solve - Solve for constants and executable blocks. 256 /// 257 void Solve(); 258 259 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 260 /// that branches on undef values cannot reach any of their successors. 261 /// However, this is not a safe assumption. After we solve dataflow, this 262 /// method should be use to handle this. If this returns true, the solver 263 /// should be rerun. 264 bool ResolvedUndefsIn(Function &F); 265 266 bool isBlockExecutable(BasicBlock *BB) const { 267 return BBExecutable.count(BB); 268 } 269 270 LatticeVal getLatticeValueFor(Value *V) const { 271 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V); 272 assert(I != ValueState.end() && "V is not in valuemap!"); 273 return I->second; 274 } 275 276 /// getTrackedRetVals - Get the inferred return value map. 277 /// 278 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() { 279 return TrackedRetVals; 280 } 281 282 /// getTrackedGlobals - Get and return the set of inferred initializers for 283 /// global variables. 284 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() { 285 return TrackedGlobals; 286 } 287 288 void markOverdefined(Value *V) { 289 assert(!V->getType()->isStructTy() && "Should use other method"); 290 markOverdefined(ValueState[V], V); 291 } 292 293 /// markAnythingOverdefined - Mark the specified value overdefined. This 294 /// works with both scalars and structs. 295 void markAnythingOverdefined(Value *V) { 296 if (StructType *STy = dyn_cast<StructType>(V->getType())) 297 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 298 markOverdefined(getStructValueState(V, i), V); 299 else 300 markOverdefined(V); 301 } 302 303 private: 304 // markConstant - Make a value be marked as "constant". If the value 305 // is not already a constant, add it to the instruction work list so that 306 // the users of the instruction are updated later. 307 // 308 void markConstant(LatticeVal &IV, Value *V, Constant *C) { 309 if (!IV.markConstant(C)) return; 310 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n'); 311 if (IV.isOverdefined()) 312 OverdefinedInstWorkList.push_back(V); 313 else 314 InstWorkList.push_back(V); 315 } 316 317 void markConstant(Value *V, Constant *C) { 318 assert(!V->getType()->isStructTy() && "Should use other method"); 319 markConstant(ValueState[V], V, C); 320 } 321 322 void markForcedConstant(Value *V, Constant *C) { 323 assert(!V->getType()->isStructTy() && "Should use other method"); 324 LatticeVal &IV = ValueState[V]; 325 IV.markForcedConstant(C); 326 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n'); 327 if (IV.isOverdefined()) 328 OverdefinedInstWorkList.push_back(V); 329 else 330 InstWorkList.push_back(V); 331 } 332 333 334 // markOverdefined - Make a value be marked as "overdefined". If the 335 // value is not already overdefined, add it to the overdefined instruction 336 // work list so that the users of the instruction are updated later. 337 void markOverdefined(LatticeVal &IV, Value *V) { 338 if (!IV.markOverdefined()) return; 339 340 DEBUG(dbgs() << "markOverdefined: "; 341 if (Function *F = dyn_cast<Function>(V)) 342 dbgs() << "Function '" << F->getName() << "'\n"; 343 else 344 dbgs() << *V << '\n'); 345 // Only instructions go on the work list 346 OverdefinedInstWorkList.push_back(V); 347 } 348 349 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) { 350 if (IV.isOverdefined() || MergeWithV.isUndefined()) 351 return; // Noop. 352 if (MergeWithV.isOverdefined()) 353 markOverdefined(IV, V); 354 else if (IV.isUndefined()) 355 markConstant(IV, V, MergeWithV.getConstant()); 356 else if (IV.getConstant() != MergeWithV.getConstant()) 357 markOverdefined(IV, V); 358 } 359 360 void mergeInValue(Value *V, LatticeVal MergeWithV) { 361 assert(!V->getType()->isStructTy() && "Should use other method"); 362 mergeInValue(ValueState[V], V, MergeWithV); 363 } 364 365 366 /// getValueState - Return the LatticeVal object that corresponds to the 367 /// value. This function handles the case when the value hasn't been seen yet 368 /// by properly seeding constants etc. 369 LatticeVal &getValueState(Value *V) { 370 assert(!V->getType()->isStructTy() && "Should use getStructValueState"); 371 372 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I = 373 ValueState.insert(std::make_pair(V, LatticeVal())); 374 LatticeVal &LV = I.first->second; 375 376 if (!I.second) 377 return LV; // Common case, already in the map. 378 379 if (Constant *C = dyn_cast<Constant>(V)) { 380 // Undef values remain undefined. 381 if (!isa<UndefValue>(V)) 382 LV.markConstant(C); // Constants are constant 383 } 384 385 // All others are underdefined by default. 386 return LV; 387 } 388 389 /// getStructValueState - Return the LatticeVal object that corresponds to the 390 /// value/field pair. This function handles the case when the value hasn't 391 /// been seen yet by properly seeding constants etc. 392 LatticeVal &getStructValueState(Value *V, unsigned i) { 393 assert(V->getType()->isStructTy() && "Should use getValueState"); 394 assert(i < cast<StructType>(V->getType())->getNumElements() && 395 "Invalid element #"); 396 397 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator, 398 bool> I = StructValueState.insert( 399 std::make_pair(std::make_pair(V, i), LatticeVal())); 400 LatticeVal &LV = I.first->second; 401 402 if (!I.second) 403 return LV; // Common case, already in the map. 404 405 if (Constant *C = dyn_cast<Constant>(V)) { 406 Constant *Elt = C->getAggregateElement(i); 407 408 if (!Elt) 409 LV.markOverdefined(); // Unknown sort of constant. 410 else if (isa<UndefValue>(Elt)) 411 ; // Undef values remain undefined. 412 else 413 LV.markConstant(Elt); // Constants are constant. 414 } 415 416 // All others are underdefined by default. 417 return LV; 418 } 419 420 421 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB 422 /// work list if it is not already executable. 423 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { 424 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) 425 return; // This edge is already known to be executable! 426 427 if (!MarkBlockExecutable(Dest)) { 428 // If the destination is already executable, we just made an *edge* 429 // feasible that wasn't before. Revisit the PHI nodes in the block 430 // because they have potentially new operands. 431 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName() 432 << " -> " << Dest->getName() << '\n'); 433 434 PHINode *PN; 435 for (BasicBlock::iterator I = Dest->begin(); 436 (PN = dyn_cast<PHINode>(I)); ++I) 437 visitPHINode(*PN); 438 } 439 } 440 441 // getFeasibleSuccessors - Return a vector of booleans to indicate which 442 // successors are reachable from a given terminator instruction. 443 // 444 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs); 445 446 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 447 // block to the 'To' basic block is currently feasible. 448 // 449 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To); 450 451 // OperandChangedState - This method is invoked on all of the users of an 452 // instruction that was just changed state somehow. Based on this 453 // information, we need to update the specified user of this instruction. 454 // 455 void OperandChangedState(Instruction *I) { 456 if (BBExecutable.count(I->getParent())) // Inst is executable? 457 visit(*I); 458 } 459 460 private: 461 friend class InstVisitor<SCCPSolver>; 462 463 // visit implementations - Something changed in this instruction. Either an 464 // operand made a transition, or the instruction is newly executable. Change 465 // the value type of I to reflect these changes if appropriate. 466 void visitPHINode(PHINode &I); 467 468 // Terminators 469 void visitReturnInst(ReturnInst &I); 470 void visitTerminatorInst(TerminatorInst &TI); 471 472 void visitCastInst(CastInst &I); 473 void visitSelectInst(SelectInst &I); 474 void visitBinaryOperator(Instruction &I); 475 void visitCmpInst(CmpInst &I); 476 void visitExtractElementInst(ExtractElementInst &I); 477 void visitInsertElementInst(InsertElementInst &I); 478 void visitShuffleVectorInst(ShuffleVectorInst &I); 479 void visitExtractValueInst(ExtractValueInst &EVI); 480 void visitInsertValueInst(InsertValueInst &IVI); 481 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); } 482 void visitCleanupPadInst(CleanupPadInst &CPI) { markAnythingOverdefined(&CPI); } 483 void visitCatchPadInst(CatchPadInst &CPI) { 484 markAnythingOverdefined(&CPI); 485 visitTerminatorInst(CPI); 486 } 487 488 // Instructions that cannot be folded away. 489 void visitStoreInst (StoreInst &I); 490 void visitLoadInst (LoadInst &I); 491 void visitGetElementPtrInst(GetElementPtrInst &I); 492 void visitCallInst (CallInst &I) { 493 visitCallSite(&I); 494 } 495 void visitInvokeInst (InvokeInst &II) { 496 visitCallSite(&II); 497 visitTerminatorInst(II); 498 } 499 void visitCallSite (CallSite CS); 500 void visitResumeInst (TerminatorInst &I) { /*returns void*/ } 501 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ } 502 void visitFenceInst (FenceInst &I) { /*returns void*/ } 503 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { 504 markAnythingOverdefined(&I); 505 } 506 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); } 507 void visitAllocaInst (Instruction &I) { markOverdefined(&I); } 508 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); } 509 510 void visitInstruction(Instruction &I) { 511 // If a new instruction is added to LLVM that we don't handle. 512 dbgs() << "SCCP: Don't know how to handle: " << I << '\n'; 513 markAnythingOverdefined(&I); // Just in case 514 } 515 }; 516 517 } // end anonymous namespace 518 519 520 // getFeasibleSuccessors - Return a vector of booleans to indicate which 521 // successors are reachable from a given terminator instruction. 522 // 523 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI, 524 SmallVectorImpl<bool> &Succs) { 525 Succs.resize(TI.getNumSuccessors()); 526 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) { 527 if (BI->isUnconditional()) { 528 Succs[0] = true; 529 return; 530 } 531 532 LatticeVal BCValue = getValueState(BI->getCondition()); 533 ConstantInt *CI = BCValue.getConstantInt(); 534 if (!CI) { 535 // Overdefined condition variables, and branches on unfoldable constant 536 // conditions, mean the branch could go either way. 537 if (!BCValue.isUndefined()) 538 Succs[0] = Succs[1] = true; 539 return; 540 } 541 542 // Constant condition variables mean the branch can only go a single way. 543 Succs[CI->isZero()] = true; 544 return; 545 } 546 547 // Unwinding instructions successors are always executable. 548 if (TI.isExceptional()) { 549 Succs.assign(TI.getNumSuccessors(), true); 550 return; 551 } 552 553 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) { 554 if (!SI->getNumCases()) { 555 Succs[0] = true; 556 return; 557 } 558 LatticeVal SCValue = getValueState(SI->getCondition()); 559 ConstantInt *CI = SCValue.getConstantInt(); 560 561 if (!CI) { // Overdefined or undefined condition? 562 // All destinations are executable! 563 if (!SCValue.isUndefined()) 564 Succs.assign(TI.getNumSuccessors(), true); 565 return; 566 } 567 568 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true; 569 return; 570 } 571 572 // TODO: This could be improved if the operand is a [cast of a] BlockAddress. 573 if (isa<IndirectBrInst>(&TI)) { 574 // Just mark all destinations executable! 575 Succs.assign(TI.getNumSuccessors(), true); 576 return; 577 } 578 579 #ifndef NDEBUG 580 dbgs() << "Unknown terminator instruction: " << TI << '\n'; 581 #endif 582 llvm_unreachable("SCCP: Don't know how to handle this terminator!"); 583 } 584 585 586 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 587 // block to the 'To' basic block is currently feasible. 588 // 589 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) { 590 assert(BBExecutable.count(To) && "Dest should always be alive!"); 591 592 // Make sure the source basic block is executable!! 593 if (!BBExecutable.count(From)) return false; 594 595 // Check to make sure this edge itself is actually feasible now. 596 TerminatorInst *TI = From->getTerminator(); 597 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 598 if (BI->isUnconditional()) 599 return true; 600 601 LatticeVal BCValue = getValueState(BI->getCondition()); 602 603 // Overdefined condition variables mean the branch could go either way, 604 // undef conditions mean that neither edge is feasible yet. 605 ConstantInt *CI = BCValue.getConstantInt(); 606 if (!CI) 607 return !BCValue.isUndefined(); 608 609 // Constant condition variables mean the branch can only go a single way. 610 return BI->getSuccessor(CI->isZero()) == To; 611 } 612 613 // Unwinding instructions successors are always executable. 614 if (TI->isExceptional()) 615 return true; 616 617 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 618 if (SI->getNumCases() < 1) 619 return true; 620 621 LatticeVal SCValue = getValueState(SI->getCondition()); 622 ConstantInt *CI = SCValue.getConstantInt(); 623 624 if (!CI) 625 return !SCValue.isUndefined(); 626 627 return SI->findCaseValue(CI).getCaseSuccessor() == To; 628 } 629 630 // Just mark all destinations executable! 631 // TODO: This could be improved if the operand is a [cast of a] BlockAddress. 632 if (isa<IndirectBrInst>(TI)) 633 return true; 634 635 #ifndef NDEBUG 636 dbgs() << "Unknown terminator instruction: " << *TI << '\n'; 637 #endif 638 llvm_unreachable(nullptr); 639 } 640 641 // visit Implementations - Something changed in this instruction, either an 642 // operand made a transition, or the instruction is newly executable. Change 643 // the value type of I to reflect these changes if appropriate. This method 644 // makes sure to do the following actions: 645 // 646 // 1. If a phi node merges two constants in, and has conflicting value coming 647 // from different branches, or if the PHI node merges in an overdefined 648 // value, then the PHI node becomes overdefined. 649 // 2. If a phi node merges only constants in, and they all agree on value, the 650 // PHI node becomes a constant value equal to that. 651 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 652 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 653 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 654 // 6. If a conditional branch has a value that is constant, make the selected 655 // destination executable 656 // 7. If a conditional branch has a value that is overdefined, make all 657 // successors executable. 658 // 659 void SCCPSolver::visitPHINode(PHINode &PN) { 660 // If this PN returns a struct, just mark the result overdefined. 661 // TODO: We could do a lot better than this if code actually uses this. 662 if (PN.getType()->isStructTy()) 663 return markAnythingOverdefined(&PN); 664 665 if (getValueState(&PN).isOverdefined()) 666 return; // Quick exit 667 668 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, 669 // and slow us down a lot. Just mark them overdefined. 670 if (PN.getNumIncomingValues() > 64) 671 return markOverdefined(&PN); 672 673 // Look at all of the executable operands of the PHI node. If any of them 674 // are overdefined, the PHI becomes overdefined as well. If they are all 675 // constant, and they agree with each other, the PHI becomes the identical 676 // constant. If they are constant and don't agree, the PHI is overdefined. 677 // If there are no executable operands, the PHI remains undefined. 678 // 679 Constant *OperandVal = nullptr; 680 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 681 LatticeVal IV = getValueState(PN.getIncomingValue(i)); 682 if (IV.isUndefined()) continue; // Doesn't influence PHI node. 683 684 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) 685 continue; 686 687 if (IV.isOverdefined()) // PHI node becomes overdefined! 688 return markOverdefined(&PN); 689 690 if (!OperandVal) { // Grab the first value. 691 OperandVal = IV.getConstant(); 692 continue; 693 } 694 695 // There is already a reachable operand. If we conflict with it, 696 // then the PHI node becomes overdefined. If we agree with it, we 697 // can continue on. 698 699 // Check to see if there are two different constants merging, if so, the PHI 700 // node is overdefined. 701 if (IV.getConstant() != OperandVal) 702 return markOverdefined(&PN); 703 } 704 705 // If we exited the loop, this means that the PHI node only has constant 706 // arguments that agree with each other(and OperandVal is the constant) or 707 // OperandVal is null because there are no defined incoming arguments. If 708 // this is the case, the PHI remains undefined. 709 // 710 if (OperandVal) 711 markConstant(&PN, OperandVal); // Acquire operand value 712 } 713 714 void SCCPSolver::visitReturnInst(ReturnInst &I) { 715 if (I.getNumOperands() == 0) return; // ret void 716 717 Function *F = I.getParent()->getParent(); 718 Value *ResultOp = I.getOperand(0); 719 720 // If we are tracking the return value of this function, merge it in. 721 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) { 722 DenseMap<Function*, LatticeVal>::iterator TFRVI = 723 TrackedRetVals.find(F); 724 if (TFRVI != TrackedRetVals.end()) { 725 mergeInValue(TFRVI->second, F, getValueState(ResultOp)); 726 return; 727 } 728 } 729 730 // Handle functions that return multiple values. 731 if (!TrackedMultipleRetVals.empty()) { 732 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType())) 733 if (MRVFunctionsTracked.count(F)) 734 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 735 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F, 736 getStructValueState(ResultOp, i)); 737 738 } 739 } 740 741 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) { 742 SmallVector<bool, 16> SuccFeasible; 743 getFeasibleSuccessors(TI, SuccFeasible); 744 745 BasicBlock *BB = TI.getParent(); 746 747 // Mark all feasible successors executable. 748 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) 749 if (SuccFeasible[i]) 750 markEdgeExecutable(BB, TI.getSuccessor(i)); 751 } 752 753 void SCCPSolver::visitCastInst(CastInst &I) { 754 LatticeVal OpSt = getValueState(I.getOperand(0)); 755 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand 756 markOverdefined(&I); 757 else if (OpSt.isConstant()) // Propagate constant value 758 markConstant(&I, ConstantExpr::getCast(I.getOpcode(), 759 OpSt.getConstant(), I.getType())); 760 } 761 762 763 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) { 764 // If this returns a struct, mark all elements over defined, we don't track 765 // structs in structs. 766 if (EVI.getType()->isStructTy()) 767 return markAnythingOverdefined(&EVI); 768 769 // If this is extracting from more than one level of struct, we don't know. 770 if (EVI.getNumIndices() != 1) 771 return markOverdefined(&EVI); 772 773 Value *AggVal = EVI.getAggregateOperand(); 774 if (AggVal->getType()->isStructTy()) { 775 unsigned i = *EVI.idx_begin(); 776 LatticeVal EltVal = getStructValueState(AggVal, i); 777 mergeInValue(getValueState(&EVI), &EVI, EltVal); 778 } else { 779 // Otherwise, must be extracting from an array. 780 return markOverdefined(&EVI); 781 } 782 } 783 784 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) { 785 StructType *STy = dyn_cast<StructType>(IVI.getType()); 786 if (!STy) 787 return markOverdefined(&IVI); 788 789 // If this has more than one index, we can't handle it, drive all results to 790 // undef. 791 if (IVI.getNumIndices() != 1) 792 return markAnythingOverdefined(&IVI); 793 794 Value *Aggr = IVI.getAggregateOperand(); 795 unsigned Idx = *IVI.idx_begin(); 796 797 // Compute the result based on what we're inserting. 798 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 799 // This passes through all values that aren't the inserted element. 800 if (i != Idx) { 801 LatticeVal EltVal = getStructValueState(Aggr, i); 802 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal); 803 continue; 804 } 805 806 Value *Val = IVI.getInsertedValueOperand(); 807 if (Val->getType()->isStructTy()) 808 // We don't track structs in structs. 809 markOverdefined(getStructValueState(&IVI, i), &IVI); 810 else { 811 LatticeVal InVal = getValueState(Val); 812 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal); 813 } 814 } 815 } 816 817 void SCCPSolver::visitSelectInst(SelectInst &I) { 818 // If this select returns a struct, just mark the result overdefined. 819 // TODO: We could do a lot better than this if code actually uses this. 820 if (I.getType()->isStructTy()) 821 return markAnythingOverdefined(&I); 822 823 LatticeVal CondValue = getValueState(I.getCondition()); 824 if (CondValue.isUndefined()) 825 return; 826 827 if (ConstantInt *CondCB = CondValue.getConstantInt()) { 828 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue(); 829 mergeInValue(&I, getValueState(OpVal)); 830 return; 831 } 832 833 // Otherwise, the condition is overdefined or a constant we can't evaluate. 834 // See if we can produce something better than overdefined based on the T/F 835 // value. 836 LatticeVal TVal = getValueState(I.getTrueValue()); 837 LatticeVal FVal = getValueState(I.getFalseValue()); 838 839 // select ?, C, C -> C. 840 if (TVal.isConstant() && FVal.isConstant() && 841 TVal.getConstant() == FVal.getConstant()) 842 return markConstant(&I, FVal.getConstant()); 843 844 if (TVal.isUndefined()) // select ?, undef, X -> X. 845 return mergeInValue(&I, FVal); 846 if (FVal.isUndefined()) // select ?, X, undef -> X. 847 return mergeInValue(&I, TVal); 848 markOverdefined(&I); 849 } 850 851 // Handle Binary Operators. 852 void SCCPSolver::visitBinaryOperator(Instruction &I) { 853 LatticeVal V1State = getValueState(I.getOperand(0)); 854 LatticeVal V2State = getValueState(I.getOperand(1)); 855 856 LatticeVal &IV = ValueState[&I]; 857 if (IV.isOverdefined()) return; 858 859 if (V1State.isConstant() && V2State.isConstant()) 860 return markConstant(IV, &I, 861 ConstantExpr::get(I.getOpcode(), V1State.getConstant(), 862 V2State.getConstant())); 863 864 // If something is undef, wait for it to resolve. 865 if (!V1State.isOverdefined() && !V2State.isOverdefined()) 866 return; 867 868 // Otherwise, one of our operands is overdefined. Try to produce something 869 // better than overdefined with some tricks. 870 871 // If this is an AND or OR with 0 or -1, it doesn't matter that the other 872 // operand is overdefined. 873 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) { 874 LatticeVal *NonOverdefVal = nullptr; 875 if (!V1State.isOverdefined()) 876 NonOverdefVal = &V1State; 877 else if (!V2State.isOverdefined()) 878 NonOverdefVal = &V2State; 879 880 if (NonOverdefVal) { 881 if (NonOverdefVal->isUndefined()) { 882 // Could annihilate value. 883 if (I.getOpcode() == Instruction::And) 884 markConstant(IV, &I, Constant::getNullValue(I.getType())); 885 else if (VectorType *PT = dyn_cast<VectorType>(I.getType())) 886 markConstant(IV, &I, Constant::getAllOnesValue(PT)); 887 else 888 markConstant(IV, &I, 889 Constant::getAllOnesValue(I.getType())); 890 return; 891 } 892 893 if (I.getOpcode() == Instruction::And) { 894 // X and 0 = 0 895 if (NonOverdefVal->getConstant()->isNullValue()) 896 return markConstant(IV, &I, NonOverdefVal->getConstant()); 897 } else { 898 if (ConstantInt *CI = NonOverdefVal->getConstantInt()) 899 if (CI->isAllOnesValue()) // X or -1 = -1 900 return markConstant(IV, &I, NonOverdefVal->getConstant()); 901 } 902 } 903 } 904 905 906 markOverdefined(&I); 907 } 908 909 // Handle ICmpInst instruction. 910 void SCCPSolver::visitCmpInst(CmpInst &I) { 911 LatticeVal V1State = getValueState(I.getOperand(0)); 912 LatticeVal V2State = getValueState(I.getOperand(1)); 913 914 LatticeVal &IV = ValueState[&I]; 915 if (IV.isOverdefined()) return; 916 917 if (V1State.isConstant() && V2State.isConstant()) 918 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(), 919 V1State.getConstant(), 920 V2State.getConstant())); 921 922 // If operands are still undefined, wait for it to resolve. 923 if (!V1State.isOverdefined() && !V2State.isOverdefined()) 924 return; 925 926 markOverdefined(&I); 927 } 928 929 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) { 930 // TODO : SCCP does not handle vectors properly. 931 return markOverdefined(&I); 932 933 #if 0 934 LatticeVal &ValState = getValueState(I.getOperand(0)); 935 LatticeVal &IdxState = getValueState(I.getOperand(1)); 936 937 if (ValState.isOverdefined() || IdxState.isOverdefined()) 938 markOverdefined(&I); 939 else if(ValState.isConstant() && IdxState.isConstant()) 940 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(), 941 IdxState.getConstant())); 942 #endif 943 } 944 945 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) { 946 // TODO : SCCP does not handle vectors properly. 947 return markOverdefined(&I); 948 #if 0 949 LatticeVal &ValState = getValueState(I.getOperand(0)); 950 LatticeVal &EltState = getValueState(I.getOperand(1)); 951 LatticeVal &IdxState = getValueState(I.getOperand(2)); 952 953 if (ValState.isOverdefined() || EltState.isOverdefined() || 954 IdxState.isOverdefined()) 955 markOverdefined(&I); 956 else if(ValState.isConstant() && EltState.isConstant() && 957 IdxState.isConstant()) 958 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(), 959 EltState.getConstant(), 960 IdxState.getConstant())); 961 else if (ValState.isUndefined() && EltState.isConstant() && 962 IdxState.isConstant()) 963 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()), 964 EltState.getConstant(), 965 IdxState.getConstant())); 966 #endif 967 } 968 969 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) { 970 // TODO : SCCP does not handle vectors properly. 971 return markOverdefined(&I); 972 #if 0 973 LatticeVal &V1State = getValueState(I.getOperand(0)); 974 LatticeVal &V2State = getValueState(I.getOperand(1)); 975 LatticeVal &MaskState = getValueState(I.getOperand(2)); 976 977 if (MaskState.isUndefined() || 978 (V1State.isUndefined() && V2State.isUndefined())) 979 return; // Undefined output if mask or both inputs undefined. 980 981 if (V1State.isOverdefined() || V2State.isOverdefined() || 982 MaskState.isOverdefined()) { 983 markOverdefined(&I); 984 } else { 985 // A mix of constant/undef inputs. 986 Constant *V1 = V1State.isConstant() ? 987 V1State.getConstant() : UndefValue::get(I.getType()); 988 Constant *V2 = V2State.isConstant() ? 989 V2State.getConstant() : UndefValue::get(I.getType()); 990 Constant *Mask = MaskState.isConstant() ? 991 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType()); 992 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask)); 993 } 994 #endif 995 } 996 997 // Handle getelementptr instructions. If all operands are constants then we 998 // can turn this into a getelementptr ConstantExpr. 999 // 1000 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) { 1001 if (ValueState[&I].isOverdefined()) return; 1002 1003 SmallVector<Constant*, 8> Operands; 1004 Operands.reserve(I.getNumOperands()); 1005 1006 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 1007 LatticeVal State = getValueState(I.getOperand(i)); 1008 if (State.isUndefined()) 1009 return; // Operands are not resolved yet. 1010 1011 if (State.isOverdefined()) 1012 return markOverdefined(&I); 1013 1014 assert(State.isConstant() && "Unknown state!"); 1015 Operands.push_back(State.getConstant()); 1016 } 1017 1018 Constant *Ptr = Operands[0]; 1019 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end()); 1020 markConstant(&I, ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, 1021 Indices)); 1022 } 1023 1024 void SCCPSolver::visitStoreInst(StoreInst &SI) { 1025 // If this store is of a struct, ignore it. 1026 if (SI.getOperand(0)->getType()->isStructTy()) 1027 return; 1028 1029 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1))) 1030 return; 1031 1032 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1)); 1033 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV); 1034 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return; 1035 1036 // Get the value we are storing into the global, then merge it. 1037 mergeInValue(I->second, GV, getValueState(SI.getOperand(0))); 1038 if (I->second.isOverdefined()) 1039 TrackedGlobals.erase(I); // No need to keep tracking this! 1040 } 1041 1042 1043 // Handle load instructions. If the operand is a constant pointer to a constant 1044 // global, we can replace the load with the loaded constant value! 1045 void SCCPSolver::visitLoadInst(LoadInst &I) { 1046 // If this load is of a struct, just mark the result overdefined. 1047 if (I.getType()->isStructTy()) 1048 return markAnythingOverdefined(&I); 1049 1050 LatticeVal PtrVal = getValueState(I.getOperand(0)); 1051 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet! 1052 1053 LatticeVal &IV = ValueState[&I]; 1054 if (IV.isOverdefined()) return; 1055 1056 if (!PtrVal.isConstant() || I.isVolatile()) 1057 return markOverdefined(IV, &I); 1058 1059 Constant *Ptr = PtrVal.getConstant(); 1060 1061 // load null -> null 1062 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) 1063 return markConstant(IV, &I, UndefValue::get(I.getType())); 1064 1065 // Transform load (constant global) into the value loaded. 1066 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) { 1067 if (!TrackedGlobals.empty()) { 1068 // If we are tracking this global, merge in the known value for it. 1069 DenseMap<GlobalVariable*, LatticeVal>::iterator It = 1070 TrackedGlobals.find(GV); 1071 if (It != TrackedGlobals.end()) { 1072 mergeInValue(IV, &I, It->second); 1073 return; 1074 } 1075 } 1076 } 1077 1078 // Transform load from a constant into a constant if possible. 1079 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL)) 1080 return markConstant(IV, &I, C); 1081 1082 // Otherwise we cannot say for certain what value this load will produce. 1083 // Bail out. 1084 markOverdefined(IV, &I); 1085 } 1086 1087 void SCCPSolver::visitCallSite(CallSite CS) { 1088 Function *F = CS.getCalledFunction(); 1089 Instruction *I = CS.getInstruction(); 1090 1091 // The common case is that we aren't tracking the callee, either because we 1092 // are not doing interprocedural analysis or the callee is indirect, or is 1093 // external. Handle these cases first. 1094 if (!F || F->isDeclaration()) { 1095 CallOverdefined: 1096 // Void return and not tracking callee, just bail. 1097 if (I->getType()->isVoidTy()) return; 1098 1099 // Otherwise, if we have a single return value case, and if the function is 1100 // a declaration, maybe we can constant fold it. 1101 if (F && F->isDeclaration() && !I->getType()->isStructTy() && 1102 canConstantFoldCallTo(F)) { 1103 1104 SmallVector<Constant*, 8> Operands; 1105 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); 1106 AI != E; ++AI) { 1107 LatticeVal State = getValueState(*AI); 1108 1109 if (State.isUndefined()) 1110 return; // Operands are not resolved yet. 1111 if (State.isOverdefined()) 1112 return markOverdefined(I); 1113 assert(State.isConstant() && "Unknown state!"); 1114 Operands.push_back(State.getConstant()); 1115 } 1116 1117 if (getValueState(I).isOverdefined()) 1118 return; 1119 1120 // If we can constant fold this, mark the result of the call as a 1121 // constant. 1122 if (Constant *C = ConstantFoldCall(F, Operands, TLI)) 1123 return markConstant(I, C); 1124 } 1125 1126 // Otherwise, we don't know anything about this call, mark it overdefined. 1127 return markAnythingOverdefined(I); 1128 } 1129 1130 // If this is a local function that doesn't have its address taken, mark its 1131 // entry block executable and merge in the actual arguments to the call into 1132 // the formal arguments of the function. 1133 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){ 1134 MarkBlockExecutable(F->begin()); 1135 1136 // Propagate information from this call site into the callee. 1137 CallSite::arg_iterator CAI = CS.arg_begin(); 1138 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1139 AI != E; ++AI, ++CAI) { 1140 // If this argument is byval, and if the function is not readonly, there 1141 // will be an implicit copy formed of the input aggregate. 1142 if (AI->hasByValAttr() && !F->onlyReadsMemory()) { 1143 markOverdefined(AI); 1144 continue; 1145 } 1146 1147 if (StructType *STy = dyn_cast<StructType>(AI->getType())) { 1148 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1149 LatticeVal CallArg = getStructValueState(*CAI, i); 1150 mergeInValue(getStructValueState(AI, i), AI, CallArg); 1151 } 1152 } else { 1153 mergeInValue(AI, getValueState(*CAI)); 1154 } 1155 } 1156 } 1157 1158 // If this is a single/zero retval case, see if we're tracking the function. 1159 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) { 1160 if (!MRVFunctionsTracked.count(F)) 1161 goto CallOverdefined; // Not tracking this callee. 1162 1163 // If we are tracking this callee, propagate the result of the function 1164 // into this call site. 1165 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1166 mergeInValue(getStructValueState(I, i), I, 1167 TrackedMultipleRetVals[std::make_pair(F, i)]); 1168 } else { 1169 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F); 1170 if (TFRVI == TrackedRetVals.end()) 1171 goto CallOverdefined; // Not tracking this callee. 1172 1173 // If so, propagate the return value of the callee into this call result. 1174 mergeInValue(I, TFRVI->second); 1175 } 1176 } 1177 1178 void SCCPSolver::Solve() { 1179 // Process the work lists until they are empty! 1180 while (!BBWorkList.empty() || !InstWorkList.empty() || 1181 !OverdefinedInstWorkList.empty()) { 1182 // Process the overdefined instruction's work list first, which drives other 1183 // things to overdefined more quickly. 1184 while (!OverdefinedInstWorkList.empty()) { 1185 Value *I = OverdefinedInstWorkList.pop_back_val(); 1186 1187 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n'); 1188 1189 // "I" got into the work list because it either made the transition from 1190 // bottom to constant, or to overdefined. 1191 // 1192 // Anything on this worklist that is overdefined need not be visited 1193 // since all of its users will have already been marked as overdefined 1194 // Update all of the users of this instruction's value. 1195 // 1196 for (User *U : I->users()) 1197 if (Instruction *UI = dyn_cast<Instruction>(U)) 1198 OperandChangedState(UI); 1199 } 1200 1201 // Process the instruction work list. 1202 while (!InstWorkList.empty()) { 1203 Value *I = InstWorkList.pop_back_val(); 1204 1205 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n'); 1206 1207 // "I" got into the work list because it made the transition from undef to 1208 // constant. 1209 // 1210 // Anything on this worklist that is overdefined need not be visited 1211 // since all of its users will have already been marked as overdefined. 1212 // Update all of the users of this instruction's value. 1213 // 1214 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined()) 1215 for (User *U : I->users()) 1216 if (Instruction *UI = dyn_cast<Instruction>(U)) 1217 OperandChangedState(UI); 1218 } 1219 1220 // Process the basic block work list. 1221 while (!BBWorkList.empty()) { 1222 BasicBlock *BB = BBWorkList.back(); 1223 BBWorkList.pop_back(); 1224 1225 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n'); 1226 1227 // Notify all instructions in this basic block that they are newly 1228 // executable. 1229 visit(BB); 1230 } 1231 } 1232 } 1233 1234 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 1235 /// that branches on undef values cannot reach any of their successors. 1236 /// However, this is not a safe assumption. After we solve dataflow, this 1237 /// method should be use to handle this. If this returns true, the solver 1238 /// should be rerun. 1239 /// 1240 /// This method handles this by finding an unresolved branch and marking it one 1241 /// of the edges from the block as being feasible, even though the condition 1242 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the 1243 /// CFG and only slightly pessimizes the analysis results (by marking one, 1244 /// potentially infeasible, edge feasible). This cannot usefully modify the 1245 /// constraints on the condition of the branch, as that would impact other users 1246 /// of the value. 1247 /// 1248 /// This scan also checks for values that use undefs, whose results are actually 1249 /// defined. For example, 'zext i8 undef to i32' should produce all zeros 1250 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero, 1251 /// even if X isn't defined. 1252 bool SCCPSolver::ResolvedUndefsIn(Function &F) { 1253 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 1254 if (!BBExecutable.count(BB)) 1255 continue; 1256 1257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1258 // Look for instructions which produce undef values. 1259 if (I->getType()->isVoidTy()) continue; 1260 1261 if (StructType *STy = dyn_cast<StructType>(I->getType())) { 1262 // Only a few things that can be structs matter for undef. 1263 1264 // Tracked calls must never be marked overdefined in ResolvedUndefsIn. 1265 if (CallSite CS = CallSite(I)) 1266 if (Function *F = CS.getCalledFunction()) 1267 if (MRVFunctionsTracked.count(F)) 1268 continue; 1269 1270 // extractvalue and insertvalue don't need to be marked; they are 1271 // tracked as precisely as their operands. 1272 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I)) 1273 continue; 1274 1275 // Send the results of everything else to overdefined. We could be 1276 // more precise than this but it isn't worth bothering. 1277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1278 LatticeVal &LV = getStructValueState(I, i); 1279 if (LV.isUndefined()) 1280 markOverdefined(LV, I); 1281 } 1282 continue; 1283 } 1284 1285 LatticeVal &LV = getValueState(I); 1286 if (!LV.isUndefined()) continue; 1287 1288 // extractvalue is safe; check here because the argument is a struct. 1289 if (isa<ExtractValueInst>(I)) 1290 continue; 1291 1292 // Compute the operand LatticeVals, for convenience below. 1293 // Anything taking a struct is conservatively assumed to require 1294 // overdefined markings. 1295 if (I->getOperand(0)->getType()->isStructTy()) { 1296 markOverdefined(I); 1297 return true; 1298 } 1299 LatticeVal Op0LV = getValueState(I->getOperand(0)); 1300 LatticeVal Op1LV; 1301 if (I->getNumOperands() == 2) { 1302 if (I->getOperand(1)->getType()->isStructTy()) { 1303 markOverdefined(I); 1304 return true; 1305 } 1306 1307 Op1LV = getValueState(I->getOperand(1)); 1308 } 1309 // If this is an instructions whose result is defined even if the input is 1310 // not fully defined, propagate the information. 1311 Type *ITy = I->getType(); 1312 switch (I->getOpcode()) { 1313 case Instruction::Add: 1314 case Instruction::Sub: 1315 case Instruction::Trunc: 1316 case Instruction::FPTrunc: 1317 case Instruction::BitCast: 1318 break; // Any undef -> undef 1319 case Instruction::FSub: 1320 case Instruction::FAdd: 1321 case Instruction::FMul: 1322 case Instruction::FDiv: 1323 case Instruction::FRem: 1324 // Floating-point binary operation: be conservative. 1325 if (Op0LV.isUndefined() && Op1LV.isUndefined()) 1326 markForcedConstant(I, Constant::getNullValue(ITy)); 1327 else 1328 markOverdefined(I); 1329 return true; 1330 case Instruction::ZExt: 1331 case Instruction::SExt: 1332 case Instruction::FPToUI: 1333 case Instruction::FPToSI: 1334 case Instruction::FPExt: 1335 case Instruction::PtrToInt: 1336 case Instruction::IntToPtr: 1337 case Instruction::SIToFP: 1338 case Instruction::UIToFP: 1339 // undef -> 0; some outputs are impossible 1340 markForcedConstant(I, Constant::getNullValue(ITy)); 1341 return true; 1342 case Instruction::Mul: 1343 case Instruction::And: 1344 // Both operands undef -> undef 1345 if (Op0LV.isUndefined() && Op1LV.isUndefined()) 1346 break; 1347 // undef * X -> 0. X could be zero. 1348 // undef & X -> 0. X could be zero. 1349 markForcedConstant(I, Constant::getNullValue(ITy)); 1350 return true; 1351 1352 case Instruction::Or: 1353 // Both operands undef -> undef 1354 if (Op0LV.isUndefined() && Op1LV.isUndefined()) 1355 break; 1356 // undef | X -> -1. X could be -1. 1357 markForcedConstant(I, Constant::getAllOnesValue(ITy)); 1358 return true; 1359 1360 case Instruction::Xor: 1361 // undef ^ undef -> 0; strictly speaking, this is not strictly 1362 // necessary, but we try to be nice to people who expect this 1363 // behavior in simple cases 1364 if (Op0LV.isUndefined() && Op1LV.isUndefined()) { 1365 markForcedConstant(I, Constant::getNullValue(ITy)); 1366 return true; 1367 } 1368 // undef ^ X -> undef 1369 break; 1370 1371 case Instruction::SDiv: 1372 case Instruction::UDiv: 1373 case Instruction::SRem: 1374 case Instruction::URem: 1375 // X / undef -> undef. No change. 1376 // X % undef -> undef. No change. 1377 if (Op1LV.isUndefined()) break; 1378 1379 // undef / X -> 0. X could be maxint. 1380 // undef % X -> 0. X could be 1. 1381 markForcedConstant(I, Constant::getNullValue(ITy)); 1382 return true; 1383 1384 case Instruction::AShr: 1385 // X >>a undef -> undef. 1386 if (Op1LV.isUndefined()) break; 1387 1388 // undef >>a X -> all ones 1389 markForcedConstant(I, Constant::getAllOnesValue(ITy)); 1390 return true; 1391 case Instruction::LShr: 1392 case Instruction::Shl: 1393 // X << undef -> undef. 1394 // X >> undef -> undef. 1395 if (Op1LV.isUndefined()) break; 1396 1397 // undef << X -> 0 1398 // undef >> X -> 0 1399 markForcedConstant(I, Constant::getNullValue(ITy)); 1400 return true; 1401 case Instruction::Select: 1402 Op1LV = getValueState(I->getOperand(1)); 1403 // undef ? X : Y -> X or Y. There could be commonality between X/Y. 1404 if (Op0LV.isUndefined()) { 1405 if (!Op1LV.isConstant()) // Pick the constant one if there is any. 1406 Op1LV = getValueState(I->getOperand(2)); 1407 } else if (Op1LV.isUndefined()) { 1408 // c ? undef : undef -> undef. No change. 1409 Op1LV = getValueState(I->getOperand(2)); 1410 if (Op1LV.isUndefined()) 1411 break; 1412 // Otherwise, c ? undef : x -> x. 1413 } else { 1414 // Leave Op1LV as Operand(1)'s LatticeValue. 1415 } 1416 1417 if (Op1LV.isConstant()) 1418 markForcedConstant(I, Op1LV.getConstant()); 1419 else 1420 markOverdefined(I); 1421 return true; 1422 case Instruction::Load: 1423 // A load here means one of two things: a load of undef from a global, 1424 // a load from an unknown pointer. Either way, having it return undef 1425 // is okay. 1426 break; 1427 case Instruction::ICmp: 1428 // X == undef -> undef. Other comparisons get more complicated. 1429 if (cast<ICmpInst>(I)->isEquality()) 1430 break; 1431 markOverdefined(I); 1432 return true; 1433 case Instruction::Call: 1434 case Instruction::Invoke: { 1435 // There are two reasons a call can have an undef result 1436 // 1. It could be tracked. 1437 // 2. It could be constant-foldable. 1438 // Because of the way we solve return values, tracked calls must 1439 // never be marked overdefined in ResolvedUndefsIn. 1440 if (Function *F = CallSite(I).getCalledFunction()) 1441 if (TrackedRetVals.count(F)) 1442 break; 1443 1444 // If the call is constant-foldable, we mark it overdefined because 1445 // we do not know what return values are valid. 1446 markOverdefined(I); 1447 return true; 1448 } 1449 default: 1450 // If we don't know what should happen here, conservatively mark it 1451 // overdefined. 1452 markOverdefined(I); 1453 return true; 1454 } 1455 } 1456 1457 // Check to see if we have a branch or switch on an undefined value. If so 1458 // we force the branch to go one way or the other to make the successor 1459 // values live. It doesn't really matter which way we force it. 1460 TerminatorInst *TI = BB->getTerminator(); 1461 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1462 if (!BI->isConditional()) continue; 1463 if (!getValueState(BI->getCondition()).isUndefined()) 1464 continue; 1465 1466 // If the input to SCCP is actually branch on undef, fix the undef to 1467 // false. 1468 if (isa<UndefValue>(BI->getCondition())) { 1469 BI->setCondition(ConstantInt::getFalse(BI->getContext())); 1470 markEdgeExecutable(BB, TI->getSuccessor(1)); 1471 return true; 1472 } 1473 1474 // Otherwise, it is a branch on a symbolic value which is currently 1475 // considered to be undef. Handle this by forcing the input value to the 1476 // branch to false. 1477 markForcedConstant(BI->getCondition(), 1478 ConstantInt::getFalse(TI->getContext())); 1479 return true; 1480 } 1481 1482 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 1483 if (!SI->getNumCases()) 1484 continue; 1485 if (!getValueState(SI->getCondition()).isUndefined()) 1486 continue; 1487 1488 // If the input to SCCP is actually switch on undef, fix the undef to 1489 // the first constant. 1490 if (isa<UndefValue>(SI->getCondition())) { 1491 SI->setCondition(SI->case_begin().getCaseValue()); 1492 markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor()); 1493 return true; 1494 } 1495 1496 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue()); 1497 return true; 1498 } 1499 } 1500 1501 return false; 1502 } 1503 1504 1505 namespace { 1506 //===--------------------------------------------------------------------===// 1507 // 1508 /// SCCP Class - This class uses the SCCPSolver to implement a per-function 1509 /// Sparse Conditional Constant Propagator. 1510 /// 1511 struct SCCP : public FunctionPass { 1512 void getAnalysisUsage(AnalysisUsage &AU) const override { 1513 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1514 } 1515 static char ID; // Pass identification, replacement for typeid 1516 SCCP() : FunctionPass(ID) { 1517 initializeSCCPPass(*PassRegistry::getPassRegistry()); 1518 } 1519 1520 // runOnFunction - Run the Sparse Conditional Constant Propagation 1521 // algorithm, and return true if the function was modified. 1522 // 1523 bool runOnFunction(Function &F) override; 1524 }; 1525 } // end anonymous namespace 1526 1527 char SCCP::ID = 0; 1528 INITIALIZE_PASS(SCCP, "sccp", 1529 "Sparse Conditional Constant Propagation", false, false) 1530 1531 // createSCCPPass - This is the public interface to this file. 1532 FunctionPass *llvm::createSCCPPass() { 1533 return new SCCP(); 1534 } 1535 1536 static void DeleteInstructionInBlock(BasicBlock *BB) { 1537 DEBUG(dbgs() << " BasicBlock Dead:" << *BB); 1538 ++NumDeadBlocks; 1539 1540 // Check to see if there are non-terminating instructions to delete. 1541 if (isa<TerminatorInst>(BB->begin())) 1542 return; 1543 1544 // Delete the instructions backwards, as it has a reduced likelihood of having 1545 // to update as many def-use and use-def chains. 1546 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted. 1547 while (EndInst != BB->begin()) { 1548 // Delete the next to last instruction. 1549 BasicBlock::iterator I = EndInst; 1550 Instruction *Inst = --I; 1551 if (!Inst->use_empty()) 1552 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); 1553 if (Inst->isEHPad()) { 1554 EndInst = Inst; 1555 continue; 1556 } 1557 BB->getInstList().erase(Inst); 1558 ++NumInstRemoved; 1559 } 1560 } 1561 1562 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm, 1563 // and return true if the function was modified. 1564 // 1565 bool SCCP::runOnFunction(Function &F) { 1566 if (skipOptnoneFunction(F)) 1567 return false; 1568 1569 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n"); 1570 const DataLayout &DL = F.getParent()->getDataLayout(); 1571 const TargetLibraryInfo *TLI = 1572 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1573 SCCPSolver Solver(DL, TLI); 1574 1575 // Mark the first block of the function as being executable. 1576 Solver.MarkBlockExecutable(F.begin()); 1577 1578 // Mark all arguments to the function as being overdefined. 1579 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI) 1580 Solver.markAnythingOverdefined(AI); 1581 1582 // Solve for constants. 1583 bool ResolvedUndefs = true; 1584 while (ResolvedUndefs) { 1585 Solver.Solve(); 1586 DEBUG(dbgs() << "RESOLVING UNDEFs\n"); 1587 ResolvedUndefs = Solver.ResolvedUndefsIn(F); 1588 } 1589 1590 bool MadeChanges = false; 1591 1592 // If we decided that there are basic blocks that are dead in this function, 1593 // delete their contents now. Note that we cannot actually delete the blocks, 1594 // as we cannot modify the CFG of the function. 1595 1596 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 1597 if (!Solver.isBlockExecutable(BB)) { 1598 DeleteInstructionInBlock(BB); 1599 MadeChanges = true; 1600 continue; 1601 } 1602 1603 // Iterate over all of the instructions in a function, replacing them with 1604 // constants if we have found them to be of constant values. 1605 // 1606 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1607 Instruction *Inst = BI++; 1608 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst)) 1609 continue; 1610 1611 // TODO: Reconstruct structs from their elements. 1612 if (Inst->getType()->isStructTy()) 1613 continue; 1614 1615 LatticeVal IV = Solver.getLatticeValueFor(Inst); 1616 if (IV.isOverdefined()) 1617 continue; 1618 1619 Constant *Const = IV.isConstant() 1620 ? IV.getConstant() : UndefValue::get(Inst->getType()); 1621 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n'); 1622 1623 // Replaces all of the uses of a variable with uses of the constant. 1624 Inst->replaceAllUsesWith(Const); 1625 1626 // Delete the instruction. 1627 Inst->eraseFromParent(); 1628 1629 // Hey, we just changed something! 1630 MadeChanges = true; 1631 ++NumInstRemoved; 1632 } 1633 } 1634 1635 return MadeChanges; 1636 } 1637 1638 namespace { 1639 //===--------------------------------------------------------------------===// 1640 // 1641 /// IPSCCP Class - This class implements interprocedural Sparse Conditional 1642 /// Constant Propagation. 1643 /// 1644 struct IPSCCP : public ModulePass { 1645 void getAnalysisUsage(AnalysisUsage &AU) const override { 1646 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1647 } 1648 static char ID; 1649 IPSCCP() : ModulePass(ID) { 1650 initializeIPSCCPPass(*PassRegistry::getPassRegistry()); 1651 } 1652 bool runOnModule(Module &M) override; 1653 }; 1654 } // end anonymous namespace 1655 1656 char IPSCCP::ID = 0; 1657 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp", 1658 "Interprocedural Sparse Conditional Constant Propagation", 1659 false, false) 1660 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1661 INITIALIZE_PASS_END(IPSCCP, "ipsccp", 1662 "Interprocedural Sparse Conditional Constant Propagation", 1663 false, false) 1664 1665 // createIPSCCPPass - This is the public interface to this file. 1666 ModulePass *llvm::createIPSCCPPass() { 1667 return new IPSCCP(); 1668 } 1669 1670 1671 static bool AddressIsTaken(const GlobalValue *GV) { 1672 // Delete any dead constantexpr klingons. 1673 GV->removeDeadConstantUsers(); 1674 1675 for (const Use &U : GV->uses()) { 1676 const User *UR = U.getUser(); 1677 if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) { 1678 if (SI->getOperand(0) == GV || SI->isVolatile()) 1679 return true; // Storing addr of GV. 1680 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) { 1681 // Make sure we are calling the function, not passing the address. 1682 ImmutableCallSite CS(cast<Instruction>(UR)); 1683 if (!CS.isCallee(&U)) 1684 return true; 1685 } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) { 1686 if (LI->isVolatile()) 1687 return true; 1688 } else if (isa<BlockAddress>(UR)) { 1689 // blockaddress doesn't take the address of the function, it takes addr 1690 // of label. 1691 } else { 1692 return true; 1693 } 1694 } 1695 return false; 1696 } 1697 1698 bool IPSCCP::runOnModule(Module &M) { 1699 const DataLayout &DL = M.getDataLayout(); 1700 const TargetLibraryInfo *TLI = 1701 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1702 SCCPSolver Solver(DL, TLI); 1703 1704 // AddressTakenFunctions - This set keeps track of the address-taken functions 1705 // that are in the input. As IPSCCP runs through and simplifies code, 1706 // functions that were address taken can end up losing their 1707 // address-taken-ness. Because of this, we keep track of their addresses from 1708 // the first pass so we can use them for the later simplification pass. 1709 SmallPtrSet<Function*, 32> AddressTakenFunctions; 1710 1711 // Loop over all functions, marking arguments to those with their addresses 1712 // taken or that are external as overdefined. 1713 // 1714 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 1715 if (F->isDeclaration()) 1716 continue; 1717 1718 // If this is a strong or ODR definition of this function, then we can 1719 // propagate information about its result into callsites of it. 1720 if (!F->mayBeOverridden()) 1721 Solver.AddTrackedFunction(F); 1722 1723 // If this function only has direct calls that we can see, we can track its 1724 // arguments and return value aggressively, and can assume it is not called 1725 // unless we see evidence to the contrary. 1726 if (F->hasLocalLinkage()) { 1727 if (AddressIsTaken(F)) 1728 AddressTakenFunctions.insert(F); 1729 else { 1730 Solver.AddArgumentTrackedFunction(F); 1731 continue; 1732 } 1733 } 1734 1735 // Assume the function is called. 1736 Solver.MarkBlockExecutable(F->begin()); 1737 1738 // Assume nothing about the incoming arguments. 1739 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1740 AI != E; ++AI) 1741 Solver.markAnythingOverdefined(AI); 1742 } 1743 1744 // Loop over global variables. We inform the solver about any internal global 1745 // variables that do not have their 'addresses taken'. If they don't have 1746 // their addresses taken, we can propagate constants through them. 1747 for (Module::global_iterator G = M.global_begin(), E = M.global_end(); 1748 G != E; ++G) 1749 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G)) 1750 Solver.TrackValueOfGlobalVariable(G); 1751 1752 // Solve for constants. 1753 bool ResolvedUndefs = true; 1754 while (ResolvedUndefs) { 1755 Solver.Solve(); 1756 1757 DEBUG(dbgs() << "RESOLVING UNDEFS\n"); 1758 ResolvedUndefs = false; 1759 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 1760 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F); 1761 } 1762 1763 bool MadeChanges = false; 1764 1765 // Iterate over all of the instructions in the module, replacing them with 1766 // constants if we have found them to be of constant values. 1767 // 1768 SmallVector<BasicBlock*, 512> BlocksToErase; 1769 1770 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 1771 if (Solver.isBlockExecutable(F->begin())) { 1772 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1773 AI != E; ++AI) { 1774 if (AI->use_empty() || AI->getType()->isStructTy()) continue; 1775 1776 // TODO: Could use getStructLatticeValueFor to find out if the entire 1777 // result is a constant and replace it entirely if so. 1778 1779 LatticeVal IV = Solver.getLatticeValueFor(AI); 1780 if (IV.isOverdefined()) continue; 1781 1782 Constant *CST = IV.isConstant() ? 1783 IV.getConstant() : UndefValue::get(AI->getType()); 1784 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n"); 1785 1786 // Replaces all of the uses of a variable with uses of the 1787 // constant. 1788 AI->replaceAllUsesWith(CST); 1789 ++IPNumArgsElimed; 1790 } 1791 } 1792 1793 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) { 1794 if (!Solver.isBlockExecutable(BB)) { 1795 DeleteInstructionInBlock(BB); 1796 MadeChanges = true; 1797 1798 TerminatorInst *TI = BB->getTerminator(); 1799 for (BasicBlock *Succ : TI->successors()) { 1800 if (!Succ->empty() && isa<PHINode>(Succ->begin())) 1801 Succ->removePredecessor(BB); 1802 } 1803 if (!TI->use_empty()) 1804 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 1805 TI->eraseFromParent(); 1806 new UnreachableInst(M.getContext(), BB); 1807 1808 if (&*BB != &F->front()) 1809 BlocksToErase.push_back(BB); 1810 continue; 1811 } 1812 1813 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1814 Instruction *Inst = BI++; 1815 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy()) 1816 continue; 1817 1818 // TODO: Could use getStructLatticeValueFor to find out if the entire 1819 // result is a constant and replace it entirely if so. 1820 1821 LatticeVal IV = Solver.getLatticeValueFor(Inst); 1822 if (IV.isOverdefined()) 1823 continue; 1824 1825 Constant *Const = IV.isConstant() 1826 ? IV.getConstant() : UndefValue::get(Inst->getType()); 1827 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n'); 1828 1829 // Replaces all of the uses of a variable with uses of the 1830 // constant. 1831 Inst->replaceAllUsesWith(Const); 1832 1833 // Delete the instruction. 1834 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst)) 1835 Inst->eraseFromParent(); 1836 1837 // Hey, we just changed something! 1838 MadeChanges = true; 1839 ++IPNumInstRemoved; 1840 } 1841 } 1842 1843 // Now that all instructions in the function are constant folded, erase dead 1844 // blocks, because we can now use ConstantFoldTerminator to get rid of 1845 // in-edges. 1846 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) { 1847 // If there are any PHI nodes in this successor, drop entries for BB now. 1848 BasicBlock *DeadBB = BlocksToErase[i]; 1849 for (Value::user_iterator UI = DeadBB->user_begin(), 1850 UE = DeadBB->user_end(); 1851 UI != UE;) { 1852 // Grab the user and then increment the iterator early, as the user 1853 // will be deleted. Step past all adjacent uses from the same user. 1854 Instruction *I = dyn_cast<Instruction>(*UI); 1855 do { ++UI; } while (UI != UE && *UI == I); 1856 1857 // Ignore blockaddress users; BasicBlock's dtor will handle them. 1858 if (!I) continue; 1859 1860 bool Folded = ConstantFoldTerminator(I->getParent()); 1861 if (!Folded) { 1862 // The constant folder may not have been able to fold the terminator 1863 // if this is a branch or switch on undef. Fold it manually as a 1864 // branch to the first successor. 1865 #ifndef NDEBUG 1866 if (BranchInst *BI = dyn_cast<BranchInst>(I)) { 1867 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) && 1868 "Branch should be foldable!"); 1869 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 1870 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold"); 1871 } else { 1872 llvm_unreachable("Didn't fold away reference to block!"); 1873 } 1874 #endif 1875 1876 // Make this an uncond branch to the first successor. 1877 TerminatorInst *TI = I->getParent()->getTerminator(); 1878 BranchInst::Create(TI->getSuccessor(0), TI); 1879 1880 // Remove entries in successor phi nodes to remove edges. 1881 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i) 1882 TI->getSuccessor(i)->removePredecessor(TI->getParent()); 1883 1884 // Remove the old terminator. 1885 TI->eraseFromParent(); 1886 } 1887 } 1888 1889 // Finally, delete the basic block. 1890 F->getBasicBlockList().erase(DeadBB); 1891 } 1892 BlocksToErase.clear(); 1893 } 1894 1895 // If we inferred constant or undef return values for a function, we replaced 1896 // all call uses with the inferred value. This means we don't need to bother 1897 // actually returning anything from the function. Replace all return 1898 // instructions with return undef. 1899 // 1900 // Do this in two stages: first identify the functions we should process, then 1901 // actually zap their returns. This is important because we can only do this 1902 // if the address of the function isn't taken. In cases where a return is the 1903 // last use of a function, the order of processing functions would affect 1904 // whether other functions are optimizable. 1905 SmallVector<ReturnInst*, 8> ReturnsToZap; 1906 1907 // TODO: Process multiple value ret instructions also. 1908 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals(); 1909 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(), 1910 E = RV.end(); I != E; ++I) { 1911 Function *F = I->first; 1912 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy()) 1913 continue; 1914 1915 // We can only do this if we know that nothing else can call the function. 1916 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F)) 1917 continue; 1918 1919 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 1920 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) 1921 if (!isa<UndefValue>(RI->getOperand(0))) 1922 ReturnsToZap.push_back(RI); 1923 } 1924 1925 // Zap all returns which we've identified as zap to change. 1926 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) { 1927 Function *F = ReturnsToZap[i]->getParent()->getParent(); 1928 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType())); 1929 } 1930 1931 // If we inferred constant or undef values for globals variables, we can 1932 // delete the global and any stores that remain to it. 1933 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals(); 1934 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(), 1935 E = TG.end(); I != E; ++I) { 1936 GlobalVariable *GV = I->first; 1937 assert(!I->second.isOverdefined() && 1938 "Overdefined values should have been taken out of the map!"); 1939 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n"); 1940 while (!GV->use_empty()) { 1941 StoreInst *SI = cast<StoreInst>(GV->user_back()); 1942 SI->eraseFromParent(); 1943 } 1944 M.getGlobalList().erase(GV); 1945 ++IPNumGlobalConst; 1946 } 1947 1948 return MadeChanges; 1949 } 1950