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