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