1 //===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===// 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 // \file 10 // This file implements the Sparse Conditional Constant Propagation (SCCP) 11 // utility. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/SCCPSolver.h" 16 #include "llvm/Analysis/ConstantFolding.h" 17 #include "llvm/Analysis/InstructionSimplify.h" 18 #include "llvm/Analysis/ValueLattice.h" 19 #include "llvm/IR/InstVisitor.h" 20 #include "llvm/Support/Casting.h" 21 #include "llvm/Support/Debug.h" 22 #include "llvm/Support/ErrorHandling.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include <cassert> 25 #include <utility> 26 #include <vector> 27 28 using namespace llvm; 29 30 #define DEBUG_TYPE "sccp" 31 32 // The maximum number of range extensions allowed for operations requiring 33 // widening. 34 static const unsigned MaxNumRangeExtensions = 10; 35 36 /// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions. 37 static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() { 38 return ValueLatticeElement::MergeOptions().setMaxWidenSteps( 39 MaxNumRangeExtensions); 40 } 41 42 namespace { 43 44 // Helper to check if \p LV is either a constant or a constant 45 // range with a single element. This should cover exactly the same cases as the 46 // old ValueLatticeElement::isConstant() and is intended to be used in the 47 // transition to ValueLatticeElement. 48 bool isConstant(const ValueLatticeElement &LV) { 49 return LV.isConstant() || 50 (LV.isConstantRange() && LV.getConstantRange().isSingleElement()); 51 } 52 53 // Helper to check if \p LV is either overdefined or a constant range with more 54 // than a single element. This should cover exactly the same cases as the old 55 // ValueLatticeElement::isOverdefined() and is intended to be used in the 56 // transition to ValueLatticeElement. 57 bool isOverdefined(const ValueLatticeElement &LV) { 58 return !LV.isUnknownOrUndef() && !isConstant(LV); 59 } 60 61 } // namespace 62 63 namespace llvm { 64 65 /// Helper class for SCCPSolver. This implements the instruction visitor and 66 /// holds all the state. 67 class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> { 68 const DataLayout &DL; 69 std::function<const TargetLibraryInfo &(Function &)> GetTLI; 70 SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable. 71 DenseMap<Value *, ValueLatticeElement> 72 ValueState; // The state each value is in. 73 74 /// StructValueState - This maintains ValueState for values that have 75 /// StructType, for example for formal arguments, calls, insertelement, etc. 76 DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState; 77 78 /// GlobalValue - If we are tracking any values for the contents of a global 79 /// variable, we keep a mapping from the constant accessor to the element of 80 /// the global, to the currently known value. If the value becomes 81 /// overdefined, it's entry is simply removed from this map. 82 DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals; 83 84 /// TrackedRetVals - If we are tracking arguments into and the return 85 /// value out of a function, it will have an entry in this map, indicating 86 /// what the known return value for the function is. 87 MapVector<Function *, ValueLatticeElement> TrackedRetVals; 88 89 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions 90 /// that return multiple values. 91 MapVector<std::pair<Function *, unsigned>, ValueLatticeElement> 92 TrackedMultipleRetVals; 93 94 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is 95 /// represented here for efficient lookup. 96 SmallPtrSet<Function *, 16> MRVFunctionsTracked; 97 98 /// A list of functions whose return cannot be modified. 99 SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions; 100 101 /// TrackingIncomingArguments - This is the set of functions for whose 102 /// arguments we make optimistic assumptions about and try to prove as 103 /// constants. 104 SmallPtrSet<Function *, 16> TrackingIncomingArguments; 105 106 /// The reason for two worklists is that overdefined is the lowest state 107 /// on the lattice, and moving things to overdefined as fast as possible 108 /// makes SCCP converge much faster. 109 /// 110 /// By having a separate worklist, we accomplish this because everything 111 /// possibly overdefined will become overdefined at the soonest possible 112 /// point. 113 SmallVector<Value *, 64> OverdefinedInstWorkList; 114 SmallVector<Value *, 64> InstWorkList; 115 116 // The BasicBlock work list 117 SmallVector<BasicBlock *, 64> BBWorkList; 118 119 /// KnownFeasibleEdges - Entries in this set are edges which have already had 120 /// PHI nodes retriggered. 121 using Edge = std::pair<BasicBlock *, BasicBlock *>; 122 DenseSet<Edge> KnownFeasibleEdges; 123 124 DenseMap<Function *, AnalysisResultsForFn> AnalysisResults; 125 DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers; 126 127 LLVMContext &Ctx; 128 129 private: 130 ConstantInt *getConstantInt(const ValueLatticeElement &IV) const { 131 return dyn_cast_or_null<ConstantInt>(getConstant(IV)); 132 } 133 134 // pushToWorkList - Helper for markConstant/markOverdefined 135 void pushToWorkList(ValueLatticeElement &IV, Value *V); 136 137 // Helper to push \p V to the worklist, after updating it to \p IV. Also 138 // prints a debug message with the updated value. 139 void pushToWorkListMsg(ValueLatticeElement &IV, Value *V); 140 141 // markConstant - Make a value be marked as "constant". If the value 142 // is not already a constant, add it to the instruction work list so that 143 // the users of the instruction are updated later. 144 bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C, 145 bool MayIncludeUndef = false); 146 147 bool markConstant(Value *V, Constant *C) { 148 assert(!V->getType()->isStructTy() && "structs should use mergeInValue"); 149 return markConstant(ValueState[V], V, C); 150 } 151 152 // markOverdefined - Make a value be marked as "overdefined". If the 153 // value is not already overdefined, add it to the overdefined instruction 154 // work list so that the users of the instruction are updated later. 155 bool markOverdefined(ValueLatticeElement &IV, Value *V); 156 157 /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV 158 /// changes. 159 bool mergeInValue(ValueLatticeElement &IV, Value *V, 160 ValueLatticeElement MergeWithV, 161 ValueLatticeElement::MergeOptions Opts = { 162 /*MayIncludeUndef=*/false, /*CheckWiden=*/false}); 163 164 bool mergeInValue(Value *V, ValueLatticeElement MergeWithV, 165 ValueLatticeElement::MergeOptions Opts = { 166 /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) { 167 assert(!V->getType()->isStructTy() && 168 "non-structs should use markConstant"); 169 return mergeInValue(ValueState[V], V, MergeWithV, Opts); 170 } 171 172 /// getValueState - Return the ValueLatticeElement object that corresponds to 173 /// the value. This function handles the case when the value hasn't been seen 174 /// yet by properly seeding constants etc. 175 ValueLatticeElement &getValueState(Value *V) { 176 assert(!V->getType()->isStructTy() && "Should use getStructValueState"); 177 178 auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement())); 179 ValueLatticeElement &LV = I.first->second; 180 181 if (!I.second) 182 return LV; // Common case, already in the map. 183 184 if (auto *C = dyn_cast<Constant>(V)) 185 LV.markConstant(C); // Constants are constant 186 187 // All others are unknown by default. 188 return LV; 189 } 190 191 /// getStructValueState - Return the ValueLatticeElement object that 192 /// corresponds to the value/field pair. This function handles the case when 193 /// the value hasn't been seen yet by properly seeding constants etc. 194 ValueLatticeElement &getStructValueState(Value *V, unsigned i) { 195 assert(V->getType()->isStructTy() && "Should use getValueState"); 196 assert(i < cast<StructType>(V->getType())->getNumElements() && 197 "Invalid element #"); 198 199 auto I = StructValueState.insert( 200 std::make_pair(std::make_pair(V, i), ValueLatticeElement())); 201 ValueLatticeElement &LV = I.first->second; 202 203 if (!I.second) 204 return LV; // Common case, already in the map. 205 206 if (auto *C = dyn_cast<Constant>(V)) { 207 Constant *Elt = C->getAggregateElement(i); 208 209 if (!Elt) 210 LV.markOverdefined(); // Unknown sort of constant. 211 else if (isa<UndefValue>(Elt)) 212 ; // Undef values remain unknown. 213 else 214 LV.markConstant(Elt); // Constants are constant. 215 } 216 217 // All others are underdefined by default. 218 return LV; 219 } 220 221 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB 222 /// work list if it is not already executable. 223 bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest); 224 225 // getFeasibleSuccessors - Return a vector of booleans to indicate which 226 // successors are reachable from a given terminator instruction. 227 void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs); 228 229 // OperandChangedState - This method is invoked on all of the users of an 230 // instruction that was just changed state somehow. Based on this 231 // information, we need to update the specified user of this instruction. 232 void operandChangedState(Instruction *I) { 233 if (BBExecutable.count(I->getParent())) // Inst is executable? 234 visit(*I); 235 } 236 237 // Add U as additional user of V. 238 void addAdditionalUser(Value *V, User *U) { 239 auto Iter = AdditionalUsers.insert({V, {}}); 240 Iter.first->second.insert(U); 241 } 242 243 // Mark I's users as changed, including AdditionalUsers. 244 void markUsersAsChanged(Value *I) { 245 // Functions include their arguments in the use-list. Changed function 246 // values mean that the result of the function changed. We only need to 247 // update the call sites with the new function result and do not have to 248 // propagate the call arguments. 249 if (isa<Function>(I)) { 250 for (User *U : I->users()) { 251 if (auto *CB = dyn_cast<CallBase>(U)) 252 handleCallResult(*CB); 253 } 254 } else { 255 for (User *U : I->users()) 256 if (auto *UI = dyn_cast<Instruction>(U)) 257 operandChangedState(UI); 258 } 259 260 auto Iter = AdditionalUsers.find(I); 261 if (Iter != AdditionalUsers.end()) { 262 // Copy additional users before notifying them of changes, because new 263 // users may be added, potentially invalidating the iterator. 264 SmallVector<Instruction *, 2> ToNotify; 265 for (User *U : Iter->second) 266 if (auto *UI = dyn_cast<Instruction>(U)) 267 ToNotify.push_back(UI); 268 for (Instruction *UI : ToNotify) 269 operandChangedState(UI); 270 } 271 } 272 void handleCallOverdefined(CallBase &CB); 273 void handleCallResult(CallBase &CB); 274 void handleCallArguments(CallBase &CB); 275 276 private: 277 friend class InstVisitor<SCCPInstVisitor>; 278 279 // visit implementations - Something changed in this instruction. Either an 280 // operand made a transition, or the instruction is newly executable. Change 281 // the value type of I to reflect these changes if appropriate. 282 void visitPHINode(PHINode &I); 283 284 // Terminators 285 286 void visitReturnInst(ReturnInst &I); 287 void visitTerminator(Instruction &TI); 288 289 void visitCastInst(CastInst &I); 290 void visitSelectInst(SelectInst &I); 291 void visitUnaryOperator(Instruction &I); 292 void visitBinaryOperator(Instruction &I); 293 void visitCmpInst(CmpInst &I); 294 void visitExtractValueInst(ExtractValueInst &EVI); 295 void visitInsertValueInst(InsertValueInst &IVI); 296 297 void visitCatchSwitchInst(CatchSwitchInst &CPI) { 298 markOverdefined(&CPI); 299 visitTerminator(CPI); 300 } 301 302 // Instructions that cannot be folded away. 303 304 void visitStoreInst(StoreInst &I); 305 void visitLoadInst(LoadInst &I); 306 void visitGetElementPtrInst(GetElementPtrInst &I); 307 308 void visitInvokeInst(InvokeInst &II) { 309 visitCallBase(II); 310 visitTerminator(II); 311 } 312 313 void visitCallBrInst(CallBrInst &CBI) { 314 visitCallBase(CBI); 315 visitTerminator(CBI); 316 } 317 318 void visitCallBase(CallBase &CB); 319 void visitResumeInst(ResumeInst &I) { /*returns void*/ 320 } 321 void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ 322 } 323 void visitFenceInst(FenceInst &I) { /*returns void*/ 324 } 325 326 void visitInstruction(Instruction &I); 327 328 public: 329 void addAnalysis(Function &F, AnalysisResultsForFn A) { 330 AnalysisResults.insert({&F, std::move(A)}); 331 } 332 333 void visitCallInst(CallInst &I) { visitCallBase(I); } 334 335 bool markBlockExecutable(BasicBlock *BB); 336 337 const PredicateBase *getPredicateInfoFor(Instruction *I) { 338 auto A = AnalysisResults.find(I->getParent()->getParent()); 339 if (A == AnalysisResults.end()) 340 return nullptr; 341 return A->second.PredInfo->getPredicateInfoFor(I); 342 } 343 344 DomTreeUpdater getDTU(Function &F) { 345 auto A = AnalysisResults.find(&F); 346 assert(A != AnalysisResults.end() && "Need analysis results for function."); 347 return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy}; 348 } 349 350 SCCPInstVisitor(const DataLayout &DL, 351 std::function<const TargetLibraryInfo &(Function &)> GetTLI, 352 LLVMContext &Ctx) 353 : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {} 354 355 void trackValueOfGlobalVariable(GlobalVariable *GV) { 356 // We only track the contents of scalar globals. 357 if (GV->getValueType()->isSingleValueType()) { 358 ValueLatticeElement &IV = TrackedGlobals[GV]; 359 if (!isa<UndefValue>(GV->getInitializer())) 360 IV.markConstant(GV->getInitializer()); 361 } 362 } 363 364 void addTrackedFunction(Function *F) { 365 // Add an entry, F -> undef. 366 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) { 367 MRVFunctionsTracked.insert(F); 368 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 369 TrackedMultipleRetVals.insert( 370 std::make_pair(std::make_pair(F, i), ValueLatticeElement())); 371 } else if (!F->getReturnType()->isVoidTy()) 372 TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement())); 373 } 374 375 void addToMustPreserveReturnsInFunctions(Function *F) { 376 MustPreserveReturnsInFunctions.insert(F); 377 } 378 379 bool mustPreserveReturn(Function *F) { 380 return MustPreserveReturnsInFunctions.count(F); 381 } 382 383 void addArgumentTrackedFunction(Function *F) { 384 TrackingIncomingArguments.insert(F); 385 } 386 387 bool isArgumentTrackedFunction(Function *F) { 388 return TrackingIncomingArguments.count(F); 389 } 390 391 void solve(); 392 393 bool resolvedUndefsIn(Function &F); 394 395 bool isBlockExecutable(BasicBlock *BB) const { 396 return BBExecutable.count(BB); 397 } 398 399 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const; 400 401 std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const { 402 std::vector<ValueLatticeElement> StructValues; 403 auto *STy = dyn_cast<StructType>(V->getType()); 404 assert(STy && "getStructLatticeValueFor() can be called only on structs"); 405 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 406 auto I = StructValueState.find(std::make_pair(V, i)); 407 assert(I != StructValueState.end() && "Value not in valuemap!"); 408 StructValues.push_back(I->second); 409 } 410 return StructValues; 411 } 412 413 void removeLatticeValueFor(Value *V) { ValueState.erase(V); } 414 415 const ValueLatticeElement &getLatticeValueFor(Value *V) const { 416 assert(!V->getType()->isStructTy() && 417 "Should use getStructLatticeValueFor"); 418 DenseMap<Value *, ValueLatticeElement>::const_iterator I = 419 ValueState.find(V); 420 assert(I != ValueState.end() && 421 "V not found in ValueState nor Paramstate map!"); 422 return I->second; 423 } 424 425 const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() { 426 return TrackedRetVals; 427 } 428 429 const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() { 430 return TrackedGlobals; 431 } 432 433 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() { 434 return MRVFunctionsTracked; 435 } 436 437 void markOverdefined(Value *V) { 438 if (auto *STy = dyn_cast<StructType>(V->getType())) 439 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 440 markOverdefined(getStructValueState(V, i), V); 441 else 442 markOverdefined(ValueState[V], V); 443 } 444 445 bool isStructLatticeConstant(Function *F, StructType *STy); 446 447 Constant *getConstant(const ValueLatticeElement &LV) const; 448 449 SmallPtrSetImpl<Function *> &getArgumentTrackedFunctions() { 450 return TrackingIncomingArguments; 451 } 452 453 void markArgInFuncSpecialization(Function *F, 454 const SmallVectorImpl<ArgInfo> &Args); 455 456 void markFunctionUnreachable(Function *F) { 457 for (auto &BB : *F) 458 BBExecutable.erase(&BB); 459 } 460 }; 461 462 } // namespace llvm 463 464 bool SCCPInstVisitor::markBlockExecutable(BasicBlock *BB) { 465 if (!BBExecutable.insert(BB).second) 466 return false; 467 LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n'); 468 BBWorkList.push_back(BB); // Add the block to the work list! 469 return true; 470 } 471 472 void SCCPInstVisitor::pushToWorkList(ValueLatticeElement &IV, Value *V) { 473 if (IV.isOverdefined()) 474 return OverdefinedInstWorkList.push_back(V); 475 InstWorkList.push_back(V); 476 } 477 478 void SCCPInstVisitor::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) { 479 LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n'); 480 pushToWorkList(IV, V); 481 } 482 483 bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V, 484 Constant *C, bool MayIncludeUndef) { 485 if (!IV.markConstant(C, MayIncludeUndef)) 486 return false; 487 LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n'); 488 pushToWorkList(IV, V); 489 return true; 490 } 491 492 bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) { 493 if (!IV.markOverdefined()) 494 return false; 495 496 LLVM_DEBUG(dbgs() << "markOverdefined: "; 497 if (auto *F = dyn_cast<Function>(V)) dbgs() 498 << "Function '" << F->getName() << "'\n"; 499 else dbgs() << *V << '\n'); 500 // Only instructions go on the work list 501 pushToWorkList(IV, V); 502 return true; 503 } 504 505 bool SCCPInstVisitor::isStructLatticeConstant(Function *F, StructType *STy) { 506 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 507 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i)); 508 assert(It != TrackedMultipleRetVals.end()); 509 ValueLatticeElement LV = It->second; 510 if (!isConstant(LV)) 511 return false; 512 } 513 return true; 514 } 515 516 Constant *SCCPInstVisitor::getConstant(const ValueLatticeElement &LV) const { 517 if (LV.isConstant()) 518 return LV.getConstant(); 519 520 if (LV.isConstantRange()) { 521 const auto &CR = LV.getConstantRange(); 522 if (CR.getSingleElement()) 523 return ConstantInt::get(Ctx, *CR.getSingleElement()); 524 } 525 return nullptr; 526 } 527 528 void SCCPInstVisitor::markArgInFuncSpecialization( 529 Function *F, const SmallVectorImpl<ArgInfo> &Args) { 530 assert(!Args.empty() && "Specialization without arguments"); 531 assert(F->arg_size() == Args[0].Formal->getParent()->arg_size() && 532 "Functions should have the same number of arguments"); 533 534 auto Iter = Args.begin(); 535 Argument *NewArg = F->arg_begin(); 536 Argument *OldArg = Args[0].Formal->getParent()->arg_begin(); 537 for (auto End = F->arg_end(); NewArg != End; ++NewArg, ++OldArg) { 538 539 LLVM_DEBUG(dbgs() << "SCCP: Marking argument " 540 << NewArg->getNameOrAsOperand() << "\n"); 541 542 if (Iter != Args.end() && OldArg == Iter->Formal) { 543 // Mark the argument constants in the new function. 544 markConstant(NewArg, Iter->Actual); 545 ++Iter; 546 } else if (ValueState.count(OldArg)) { 547 // For the remaining arguments in the new function, copy the lattice state 548 // over from the old function. 549 // 550 // Note: This previously looked like this: 551 // ValueState[NewArg] = ValueState[OldArg]; 552 // This is incorrect because the DenseMap class may resize the underlying 553 // memory when inserting `NewArg`, which will invalidate the reference to 554 // `OldArg`. Instead, we make sure `NewArg` exists before setting it. 555 auto &NewValue = ValueState[NewArg]; 556 NewValue = ValueState[OldArg]; 557 pushToWorkList(NewValue, NewArg); 558 } 559 } 560 } 561 562 void SCCPInstVisitor::visitInstruction(Instruction &I) { 563 // All the instructions we don't do any special handling for just 564 // go to overdefined. 565 LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n'); 566 markOverdefined(&I); 567 } 568 569 bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V, 570 ValueLatticeElement MergeWithV, 571 ValueLatticeElement::MergeOptions Opts) { 572 if (IV.mergeIn(MergeWithV, Opts)) { 573 pushToWorkList(IV, V); 574 LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : " 575 << IV << "\n"); 576 return true; 577 } 578 return false; 579 } 580 581 bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { 582 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) 583 return false; // This edge is already known to be executable! 584 585 if (!markBlockExecutable(Dest)) { 586 // If the destination is already executable, we just made an *edge* 587 // feasible that wasn't before. Revisit the PHI nodes in the block 588 // because they have potentially new operands. 589 LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName() 590 << " -> " << Dest->getName() << '\n'); 591 592 for (PHINode &PN : Dest->phis()) 593 visitPHINode(PN); 594 } 595 return true; 596 } 597 598 // getFeasibleSuccessors - Return a vector of booleans to indicate which 599 // successors are reachable from a given terminator instruction. 600 void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI, 601 SmallVectorImpl<bool> &Succs) { 602 Succs.resize(TI.getNumSuccessors()); 603 if (auto *BI = dyn_cast<BranchInst>(&TI)) { 604 if (BI->isUnconditional()) { 605 Succs[0] = true; 606 return; 607 } 608 609 ValueLatticeElement BCValue = getValueState(BI->getCondition()); 610 ConstantInt *CI = getConstantInt(BCValue); 611 if (!CI) { 612 // Overdefined condition variables, and branches on unfoldable constant 613 // conditions, mean the branch could go either way. 614 if (!BCValue.isUnknownOrUndef()) 615 Succs[0] = Succs[1] = true; 616 return; 617 } 618 619 // Constant condition variables mean the branch can only go a single way. 620 Succs[CI->isZero()] = true; 621 return; 622 } 623 624 // Unwinding instructions successors are always executable. 625 if (TI.isExceptionalTerminator()) { 626 Succs.assign(TI.getNumSuccessors(), true); 627 return; 628 } 629 630 if (auto *SI = dyn_cast<SwitchInst>(&TI)) { 631 if (!SI->getNumCases()) { 632 Succs[0] = true; 633 return; 634 } 635 const ValueLatticeElement &SCValue = getValueState(SI->getCondition()); 636 if (ConstantInt *CI = getConstantInt(SCValue)) { 637 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true; 638 return; 639 } 640 641 // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM 642 // is ready. 643 if (SCValue.isConstantRange(/*UndefAllowed=*/false)) { 644 const ConstantRange &Range = SCValue.getConstantRange(); 645 for (const auto &Case : SI->cases()) { 646 const APInt &CaseValue = Case.getCaseValue()->getValue(); 647 if (Range.contains(CaseValue)) 648 Succs[Case.getSuccessorIndex()] = true; 649 } 650 651 // TODO: Determine whether default case is reachable. 652 Succs[SI->case_default()->getSuccessorIndex()] = true; 653 return; 654 } 655 656 // Overdefined or unknown condition? All destinations are executable! 657 if (!SCValue.isUnknownOrUndef()) 658 Succs.assign(TI.getNumSuccessors(), true); 659 return; 660 } 661 662 // In case of indirect branch and its address is a blockaddress, we mark 663 // the target as executable. 664 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) { 665 // Casts are folded by visitCastInst. 666 ValueLatticeElement IBRValue = getValueState(IBR->getAddress()); 667 BlockAddress *Addr = dyn_cast_or_null<BlockAddress>(getConstant(IBRValue)); 668 if (!Addr) { // Overdefined or unknown condition? 669 // All destinations are executable! 670 if (!IBRValue.isUnknownOrUndef()) 671 Succs.assign(TI.getNumSuccessors(), true); 672 return; 673 } 674 675 BasicBlock *T = Addr->getBasicBlock(); 676 assert(Addr->getFunction() == T->getParent() && 677 "Block address of a different function ?"); 678 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) { 679 // This is the target. 680 if (IBR->getDestination(i) == T) { 681 Succs[i] = true; 682 return; 683 } 684 } 685 686 // If we didn't find our destination in the IBR successor list, then we 687 // have undefined behavior. Its ok to assume no successor is executable. 688 return; 689 } 690 691 // In case of callbr, we pessimistically assume that all successors are 692 // feasible. 693 if (isa<CallBrInst>(&TI)) { 694 Succs.assign(TI.getNumSuccessors(), true); 695 return; 696 } 697 698 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n'); 699 llvm_unreachable("SCCP: Don't know how to handle this terminator!"); 700 } 701 702 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 703 // block to the 'To' basic block is currently feasible. 704 bool SCCPInstVisitor::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const { 705 // Check if we've called markEdgeExecutable on the edge yet. (We could 706 // be more aggressive and try to consider edges which haven't been marked 707 // yet, but there isn't any need.) 708 return KnownFeasibleEdges.count(Edge(From, To)); 709 } 710 711 // visit Implementations - Something changed in this instruction, either an 712 // operand made a transition, or the instruction is newly executable. Change 713 // the value type of I to reflect these changes if appropriate. This method 714 // makes sure to do the following actions: 715 // 716 // 1. If a phi node merges two constants in, and has conflicting value coming 717 // from different branches, or if the PHI node merges in an overdefined 718 // value, then the PHI node becomes overdefined. 719 // 2. If a phi node merges only constants in, and they all agree on value, the 720 // PHI node becomes a constant value equal to that. 721 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 722 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 723 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 724 // 6. If a conditional branch has a value that is constant, make the selected 725 // destination executable 726 // 7. If a conditional branch has a value that is overdefined, make all 727 // successors executable. 728 void SCCPInstVisitor::visitPHINode(PHINode &PN) { 729 // If this PN returns a struct, just mark the result overdefined. 730 // TODO: We could do a lot better than this if code actually uses this. 731 if (PN.getType()->isStructTy()) 732 return (void)markOverdefined(&PN); 733 734 if (getValueState(&PN).isOverdefined()) 735 return; // Quick exit 736 737 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, 738 // and slow us down a lot. Just mark them overdefined. 739 if (PN.getNumIncomingValues() > 64) 740 return (void)markOverdefined(&PN); 741 742 unsigned NumActiveIncoming = 0; 743 744 // Look at all of the executable operands of the PHI node. If any of them 745 // are overdefined, the PHI becomes overdefined as well. If they are all 746 // constant, and they agree with each other, the PHI becomes the identical 747 // constant. If they are constant and don't agree, the PHI is a constant 748 // range. If there are no executable operands, the PHI remains unknown. 749 ValueLatticeElement PhiState = getValueState(&PN); 750 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 751 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) 752 continue; 753 754 ValueLatticeElement IV = getValueState(PN.getIncomingValue(i)); 755 PhiState.mergeIn(IV); 756 NumActiveIncoming++; 757 if (PhiState.isOverdefined()) 758 break; 759 } 760 761 // We allow up to 1 range extension per active incoming value and one 762 // additional extension. Note that we manually adjust the number of range 763 // extensions to match the number of active incoming values. This helps to 764 // limit multiple extensions caused by the same incoming value, if other 765 // incoming values are equal. 766 mergeInValue(&PN, PhiState, 767 ValueLatticeElement::MergeOptions().setMaxWidenSteps( 768 NumActiveIncoming + 1)); 769 ValueLatticeElement &PhiStateRef = getValueState(&PN); 770 PhiStateRef.setNumRangeExtensions( 771 std::max(NumActiveIncoming, PhiStateRef.getNumRangeExtensions())); 772 } 773 774 void SCCPInstVisitor::visitReturnInst(ReturnInst &I) { 775 if (I.getNumOperands() == 0) 776 return; // ret void 777 778 Function *F = I.getParent()->getParent(); 779 Value *ResultOp = I.getOperand(0); 780 781 // If we are tracking the return value of this function, merge it in. 782 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) { 783 auto TFRVI = TrackedRetVals.find(F); 784 if (TFRVI != TrackedRetVals.end()) { 785 mergeInValue(TFRVI->second, F, getValueState(ResultOp)); 786 return; 787 } 788 } 789 790 // Handle functions that return multiple values. 791 if (!TrackedMultipleRetVals.empty()) { 792 if (auto *STy = dyn_cast<StructType>(ResultOp->getType())) 793 if (MRVFunctionsTracked.count(F)) 794 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 795 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F, 796 getStructValueState(ResultOp, i)); 797 } 798 } 799 800 void SCCPInstVisitor::visitTerminator(Instruction &TI) { 801 SmallVector<bool, 16> SuccFeasible; 802 getFeasibleSuccessors(TI, SuccFeasible); 803 804 BasicBlock *BB = TI.getParent(); 805 806 // Mark all feasible successors executable. 807 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) 808 if (SuccFeasible[i]) 809 markEdgeExecutable(BB, TI.getSuccessor(i)); 810 } 811 812 void SCCPInstVisitor::visitCastInst(CastInst &I) { 813 // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would 814 // discover a concrete value later. 815 if (ValueState[&I].isOverdefined()) 816 return; 817 818 ValueLatticeElement OpSt = getValueState(I.getOperand(0)); 819 if (OpSt.isUnknownOrUndef()) 820 return; 821 822 if (Constant *OpC = getConstant(OpSt)) { 823 // Fold the constant as we build. 824 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL); 825 if (isa<UndefValue>(C)) 826 return; 827 // Propagate constant value 828 markConstant(&I, C); 829 } else if (I.getDestTy()->isIntegerTy()) { 830 auto &LV = getValueState(&I); 831 ConstantRange OpRange = 832 OpSt.isConstantRange() 833 ? OpSt.getConstantRange() 834 : ConstantRange::getFull( 835 I.getOperand(0)->getType()->getScalarSizeInBits()); 836 837 Type *DestTy = I.getDestTy(); 838 // Vectors where all elements have the same known constant range are treated 839 // as a single constant range in the lattice. When bitcasting such vectors, 840 // there is a mis-match between the width of the lattice value (single 841 // constant range) and the original operands (vector). Go to overdefined in 842 // that case. 843 if (I.getOpcode() == Instruction::BitCast && 844 I.getOperand(0)->getType()->isVectorTy() && 845 OpRange.getBitWidth() < DL.getTypeSizeInBits(DestTy)) 846 return (void)markOverdefined(&I); 847 848 ConstantRange Res = 849 OpRange.castOp(I.getOpcode(), DL.getTypeSizeInBits(DestTy)); 850 mergeInValue(LV, &I, ValueLatticeElement::getRange(Res)); 851 } else 852 markOverdefined(&I); 853 } 854 855 void SCCPInstVisitor::visitExtractValueInst(ExtractValueInst &EVI) { 856 // If this returns a struct, mark all elements over defined, we don't track 857 // structs in structs. 858 if (EVI.getType()->isStructTy()) 859 return (void)markOverdefined(&EVI); 860 861 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would 862 // discover a concrete value later. 863 if (ValueState[&EVI].isOverdefined()) 864 return (void)markOverdefined(&EVI); 865 866 // If this is extracting from more than one level of struct, we don't know. 867 if (EVI.getNumIndices() != 1) 868 return (void)markOverdefined(&EVI); 869 870 Value *AggVal = EVI.getAggregateOperand(); 871 if (AggVal->getType()->isStructTy()) { 872 unsigned i = *EVI.idx_begin(); 873 ValueLatticeElement EltVal = getStructValueState(AggVal, i); 874 mergeInValue(getValueState(&EVI), &EVI, EltVal); 875 } else { 876 // Otherwise, must be extracting from an array. 877 return (void)markOverdefined(&EVI); 878 } 879 } 880 881 void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) { 882 auto *STy = dyn_cast<StructType>(IVI.getType()); 883 if (!STy) 884 return (void)markOverdefined(&IVI); 885 886 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would 887 // discover a concrete value later. 888 if (isOverdefined(ValueState[&IVI])) 889 return (void)markOverdefined(&IVI); 890 891 // If this has more than one index, we can't handle it, drive all results to 892 // undef. 893 if (IVI.getNumIndices() != 1) 894 return (void)markOverdefined(&IVI); 895 896 Value *Aggr = IVI.getAggregateOperand(); 897 unsigned Idx = *IVI.idx_begin(); 898 899 // Compute the result based on what we're inserting. 900 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 901 // This passes through all values that aren't the inserted element. 902 if (i != Idx) { 903 ValueLatticeElement EltVal = getStructValueState(Aggr, i); 904 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal); 905 continue; 906 } 907 908 Value *Val = IVI.getInsertedValueOperand(); 909 if (Val->getType()->isStructTy()) 910 // We don't track structs in structs. 911 markOverdefined(getStructValueState(&IVI, i), &IVI); 912 else { 913 ValueLatticeElement InVal = getValueState(Val); 914 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal); 915 } 916 } 917 } 918 919 void SCCPInstVisitor::visitSelectInst(SelectInst &I) { 920 // If this select returns a struct, just mark the result overdefined. 921 // TODO: We could do a lot better than this if code actually uses this. 922 if (I.getType()->isStructTy()) 923 return (void)markOverdefined(&I); 924 925 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would 926 // discover a concrete value later. 927 if (ValueState[&I].isOverdefined()) 928 return (void)markOverdefined(&I); 929 930 ValueLatticeElement CondValue = getValueState(I.getCondition()); 931 if (CondValue.isUnknownOrUndef()) 932 return; 933 934 if (ConstantInt *CondCB = getConstantInt(CondValue)) { 935 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue(); 936 mergeInValue(&I, getValueState(OpVal)); 937 return; 938 } 939 940 // Otherwise, the condition is overdefined or a constant we can't evaluate. 941 // See if we can produce something better than overdefined based on the T/F 942 // value. 943 ValueLatticeElement TVal = getValueState(I.getTrueValue()); 944 ValueLatticeElement FVal = getValueState(I.getFalseValue()); 945 946 bool Changed = ValueState[&I].mergeIn(TVal); 947 Changed |= ValueState[&I].mergeIn(FVal); 948 if (Changed) 949 pushToWorkListMsg(ValueState[&I], &I); 950 } 951 952 // Handle Unary Operators. 953 void SCCPInstVisitor::visitUnaryOperator(Instruction &I) { 954 ValueLatticeElement V0State = getValueState(I.getOperand(0)); 955 956 ValueLatticeElement &IV = ValueState[&I]; 957 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would 958 // discover a concrete value later. 959 if (isOverdefined(IV)) 960 return (void)markOverdefined(&I); 961 962 if (isConstant(V0State)) { 963 if (Constant *C = ConstantFoldUnaryOpOperand(I.getOpcode(), 964 getConstant(V0State, DL))) { 965 // op Y -> undef. 966 if (isa<UndefValue>(C)) 967 return; 968 return (void)markConstant(IV, &I, C); 969 } 970 } 971 972 // If something is undef, wait for it to resolve. 973 if (!isOverdefined(V0State)) 974 return; 975 976 markOverdefined(&I); 977 } 978 979 // Handle Binary Operators. 980 void SCCPInstVisitor::visitBinaryOperator(Instruction &I) { 981 ValueLatticeElement V1State = getValueState(I.getOperand(0)); 982 ValueLatticeElement V2State = getValueState(I.getOperand(1)); 983 984 ValueLatticeElement &IV = ValueState[&I]; 985 if (IV.isOverdefined()) 986 return; 987 988 // If something is undef, wait for it to resolve. 989 if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) 990 return; 991 992 if (V1State.isOverdefined() && V2State.isOverdefined()) 993 return (void)markOverdefined(&I); 994 995 // If either of the operands is a constant, try to fold it to a constant. 996 // TODO: Use information from notconstant better. 997 if ((V1State.isConstant() || V2State.isConstant())) { 998 Value *V1 = isConstant(V1State) ? getConstant(V1State) : I.getOperand(0); 999 Value *V2 = isConstant(V2State) ? getConstant(V2State) : I.getOperand(1); 1000 Value *R = simplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL)); 1001 auto *C = dyn_cast_or_null<Constant>(R); 1002 if (C) { 1003 // X op Y -> undef. 1004 if (isa<UndefValue>(C)) 1005 return; 1006 // Conservatively assume that the result may be based on operands that may 1007 // be undef. Note that we use mergeInValue to combine the constant with 1008 // the existing lattice value for I, as different constants might be found 1009 // after one of the operands go to overdefined, e.g. due to one operand 1010 // being a special floating value. 1011 ValueLatticeElement NewV; 1012 NewV.markConstant(C, /*MayIncludeUndef=*/true); 1013 return (void)mergeInValue(&I, NewV); 1014 } 1015 } 1016 1017 // Only use ranges for binary operators on integers. 1018 if (!I.getType()->isIntegerTy()) 1019 return markOverdefined(&I); 1020 1021 // Try to simplify to a constant range. 1022 ConstantRange A = ConstantRange::getFull(I.getType()->getScalarSizeInBits()); 1023 ConstantRange B = ConstantRange::getFull(I.getType()->getScalarSizeInBits()); 1024 if (V1State.isConstantRange()) 1025 A = V1State.getConstantRange(); 1026 if (V2State.isConstantRange()) 1027 B = V2State.getConstantRange(); 1028 1029 ConstantRange R = A.binaryOp(cast<BinaryOperator>(&I)->getOpcode(), B); 1030 mergeInValue(&I, ValueLatticeElement::getRange(R)); 1031 1032 // TODO: Currently we do not exploit special values that produce something 1033 // better than overdefined with an overdefined operand for vector or floating 1034 // point types, like and <4 x i32> overdefined, zeroinitializer. 1035 } 1036 1037 // Handle ICmpInst instruction. 1038 void SCCPInstVisitor::visitCmpInst(CmpInst &I) { 1039 // Do not cache this lookup, getValueState calls later in the function might 1040 // invalidate the reference. 1041 if (isOverdefined(ValueState[&I])) 1042 return (void)markOverdefined(&I); 1043 1044 Value *Op1 = I.getOperand(0); 1045 Value *Op2 = I.getOperand(1); 1046 1047 // For parameters, use ParamState which includes constant range info if 1048 // available. 1049 auto V1State = getValueState(Op1); 1050 auto V2State = getValueState(Op2); 1051 1052 Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State); 1053 if (C) { 1054 if (isa<UndefValue>(C)) 1055 return; 1056 ValueLatticeElement CV; 1057 CV.markConstant(C); 1058 mergeInValue(&I, CV); 1059 return; 1060 } 1061 1062 // If operands are still unknown, wait for it to resolve. 1063 if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) && 1064 !isConstant(ValueState[&I])) 1065 return; 1066 1067 markOverdefined(&I); 1068 } 1069 1070 // Handle getelementptr instructions. If all operands are constants then we 1071 // can turn this into a getelementptr ConstantExpr. 1072 void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) { 1073 if (isOverdefined(ValueState[&I])) 1074 return (void)markOverdefined(&I); 1075 1076 SmallVector<Constant *, 8> Operands; 1077 Operands.reserve(I.getNumOperands()); 1078 1079 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 1080 ValueLatticeElement State = getValueState(I.getOperand(i)); 1081 if (State.isUnknownOrUndef()) 1082 return; // Operands are not resolved yet. 1083 1084 if (isOverdefined(State)) 1085 return (void)markOverdefined(&I); 1086 1087 if (Constant *C = getConstant(State)) { 1088 Operands.push_back(C); 1089 continue; 1090 } 1091 1092 return (void)markOverdefined(&I); 1093 } 1094 1095 Constant *Ptr = Operands[0]; 1096 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end()); 1097 Constant *C = 1098 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices); 1099 if (isa<UndefValue>(C)) 1100 return; 1101 markConstant(&I, C); 1102 } 1103 1104 void SCCPInstVisitor::visitStoreInst(StoreInst &SI) { 1105 // If this store is of a struct, ignore it. 1106 if (SI.getOperand(0)->getType()->isStructTy()) 1107 return; 1108 1109 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1))) 1110 return; 1111 1112 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1)); 1113 auto I = TrackedGlobals.find(GV); 1114 if (I == TrackedGlobals.end()) 1115 return; 1116 1117 // Get the value we are storing into the global, then merge it. 1118 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)), 1119 ValueLatticeElement::MergeOptions().setCheckWiden(false)); 1120 if (I->second.isOverdefined()) 1121 TrackedGlobals.erase(I); // No need to keep tracking this! 1122 } 1123 1124 static ValueLatticeElement getValueFromMetadata(const Instruction *I) { 1125 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) 1126 if (I->getType()->isIntegerTy()) 1127 return ValueLatticeElement::getRange( 1128 getConstantRangeFromMetadata(*Ranges)); 1129 if (I->hasMetadata(LLVMContext::MD_nonnull)) 1130 return ValueLatticeElement::getNot( 1131 ConstantPointerNull::get(cast<PointerType>(I->getType()))); 1132 return ValueLatticeElement::getOverdefined(); 1133 } 1134 1135 // Handle load instructions. If the operand is a constant pointer to a constant 1136 // global, we can replace the load with the loaded constant value! 1137 void SCCPInstVisitor::visitLoadInst(LoadInst &I) { 1138 // If this load is of a struct or the load is volatile, just mark the result 1139 // as overdefined. 1140 if (I.getType()->isStructTy() || I.isVolatile()) 1141 return (void)markOverdefined(&I); 1142 1143 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would 1144 // discover a concrete value later. 1145 if (ValueState[&I].isOverdefined()) 1146 return (void)markOverdefined(&I); 1147 1148 ValueLatticeElement PtrVal = getValueState(I.getOperand(0)); 1149 if (PtrVal.isUnknownOrUndef()) 1150 return; // The pointer is not resolved yet! 1151 1152 ValueLatticeElement &IV = ValueState[&I]; 1153 1154 if (isConstant(PtrVal)) { 1155 Constant *Ptr = getConstant(PtrVal); 1156 1157 // load null is undefined. 1158 if (isa<ConstantPointerNull>(Ptr)) { 1159 if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace())) 1160 return (void)markOverdefined(IV, &I); 1161 else 1162 return; 1163 } 1164 1165 // Transform load (constant global) into the value loaded. 1166 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) { 1167 if (!TrackedGlobals.empty()) { 1168 // If we are tracking this global, merge in the known value for it. 1169 auto It = TrackedGlobals.find(GV); 1170 if (It != TrackedGlobals.end()) { 1171 mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts()); 1172 return; 1173 } 1174 } 1175 } 1176 1177 // Transform load from a constant into a constant if possible. 1178 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) { 1179 if (isa<UndefValue>(C)) 1180 return; 1181 return (void)markConstant(IV, &I, C); 1182 } 1183 } 1184 1185 // Fall back to metadata. 1186 mergeInValue(&I, getValueFromMetadata(&I)); 1187 } 1188 1189 void SCCPInstVisitor::visitCallBase(CallBase &CB) { 1190 handleCallResult(CB); 1191 handleCallArguments(CB); 1192 } 1193 1194 void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) { 1195 Function *F = CB.getCalledFunction(); 1196 1197 // Void return and not tracking callee, just bail. 1198 if (CB.getType()->isVoidTy()) 1199 return; 1200 1201 // Always mark struct return as overdefined. 1202 if (CB.getType()->isStructTy()) 1203 return (void)markOverdefined(&CB); 1204 1205 // Otherwise, if we have a single return value case, and if the function is 1206 // a declaration, maybe we can constant fold it. 1207 if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) { 1208 SmallVector<Constant *, 8> Operands; 1209 for (const Use &A : CB.args()) { 1210 if (A.get()->getType()->isStructTy()) 1211 return markOverdefined(&CB); // Can't handle struct args. 1212 ValueLatticeElement State = getValueState(A); 1213 1214 if (State.isUnknownOrUndef()) 1215 return; // Operands are not resolved yet. 1216 if (isOverdefined(State)) 1217 return (void)markOverdefined(&CB); 1218 assert(isConstant(State) && "Unknown state!"); 1219 Operands.push_back(getConstant(State)); 1220 } 1221 1222 if (isOverdefined(getValueState(&CB))) 1223 return (void)markOverdefined(&CB); 1224 1225 // If we can constant fold this, mark the result of the call as a 1226 // constant. 1227 if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F))) { 1228 // call -> undef. 1229 if (isa<UndefValue>(C)) 1230 return; 1231 return (void)markConstant(&CB, C); 1232 } 1233 } 1234 1235 // Fall back to metadata. 1236 mergeInValue(&CB, getValueFromMetadata(&CB)); 1237 } 1238 1239 void SCCPInstVisitor::handleCallArguments(CallBase &CB) { 1240 Function *F = CB.getCalledFunction(); 1241 // If this is a local function that doesn't have its address taken, mark its 1242 // entry block executable and merge in the actual arguments to the call into 1243 // the formal arguments of the function. 1244 if (!TrackingIncomingArguments.empty() && 1245 TrackingIncomingArguments.count(F)) { 1246 markBlockExecutable(&F->front()); 1247 1248 // Propagate information from this call site into the callee. 1249 auto CAI = CB.arg_begin(); 1250 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; 1251 ++AI, ++CAI) { 1252 // If this argument is byval, and if the function is not readonly, there 1253 // will be an implicit copy formed of the input aggregate. 1254 if (AI->hasByValAttr() && !F->onlyReadsMemory()) { 1255 markOverdefined(&*AI); 1256 continue; 1257 } 1258 1259 if (auto *STy = dyn_cast<StructType>(AI->getType())) { 1260 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1261 ValueLatticeElement CallArg = getStructValueState(*CAI, i); 1262 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg, 1263 getMaxWidenStepsOpts()); 1264 } 1265 } else 1266 mergeInValue(&*AI, getValueState(*CAI), getMaxWidenStepsOpts()); 1267 } 1268 } 1269 } 1270 1271 void SCCPInstVisitor::handleCallResult(CallBase &CB) { 1272 Function *F = CB.getCalledFunction(); 1273 1274 if (auto *II = dyn_cast<IntrinsicInst>(&CB)) { 1275 if (II->getIntrinsicID() == Intrinsic::ssa_copy) { 1276 if (ValueState[&CB].isOverdefined()) 1277 return; 1278 1279 Value *CopyOf = CB.getOperand(0); 1280 ValueLatticeElement CopyOfVal = getValueState(CopyOf); 1281 const auto *PI = getPredicateInfoFor(&CB); 1282 assert(PI && "Missing predicate info for ssa.copy"); 1283 1284 const Optional<PredicateConstraint> &Constraint = PI->getConstraint(); 1285 if (!Constraint) { 1286 mergeInValue(ValueState[&CB], &CB, CopyOfVal); 1287 return; 1288 } 1289 1290 CmpInst::Predicate Pred = Constraint->Predicate; 1291 Value *OtherOp = Constraint->OtherOp; 1292 1293 // Wait until OtherOp is resolved. 1294 if (getValueState(OtherOp).isUnknown()) { 1295 addAdditionalUser(OtherOp, &CB); 1296 return; 1297 } 1298 1299 ValueLatticeElement CondVal = getValueState(OtherOp); 1300 ValueLatticeElement &IV = ValueState[&CB]; 1301 if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) { 1302 auto ImposedCR = 1303 ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType())); 1304 1305 // Get the range imposed by the condition. 1306 if (CondVal.isConstantRange()) 1307 ImposedCR = ConstantRange::makeAllowedICmpRegion( 1308 Pred, CondVal.getConstantRange()); 1309 1310 // Combine range info for the original value with the new range from the 1311 // condition. 1312 auto CopyOfCR = CopyOfVal.isConstantRange() 1313 ? CopyOfVal.getConstantRange() 1314 : ConstantRange::getFull( 1315 DL.getTypeSizeInBits(CopyOf->getType())); 1316 auto NewCR = ImposedCR.intersectWith(CopyOfCR); 1317 // If the existing information is != x, do not use the information from 1318 // a chained predicate, as the != x information is more likely to be 1319 // helpful in practice. 1320 if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement()) 1321 NewCR = CopyOfCR; 1322 1323 // The new range is based on a branch condition. That guarantees that 1324 // neither of the compare operands can be undef in the branch targets, 1325 // unless we have conditions that are always true/false (e.g. icmp ule 1326 // i32, %a, i32_max). For the latter overdefined/empty range will be 1327 // inferred, but the branch will get folded accordingly anyways. 1328 addAdditionalUser(OtherOp, &CB); 1329 mergeInValue( 1330 IV, &CB, 1331 ValueLatticeElement::getRange(NewCR, /*MayIncludeUndef*/ false)); 1332 return; 1333 } else if (Pred == CmpInst::ICMP_EQ && CondVal.isConstant()) { 1334 // For non-integer values or integer constant expressions, only 1335 // propagate equal constants. 1336 addAdditionalUser(OtherOp, &CB); 1337 mergeInValue(IV, &CB, CondVal); 1338 return; 1339 } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant()) { 1340 // Propagate inequalities. 1341 addAdditionalUser(OtherOp, &CB); 1342 mergeInValue(IV, &CB, 1343 ValueLatticeElement::getNot(CondVal.getConstant())); 1344 return; 1345 } 1346 1347 return (void)mergeInValue(IV, &CB, CopyOfVal); 1348 } 1349 1350 if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) { 1351 // Compute result range for intrinsics supported by ConstantRange. 1352 // Do this even if we don't know a range for all operands, as we may 1353 // still know something about the result range, e.g. of abs(x). 1354 SmallVector<ConstantRange, 2> OpRanges; 1355 for (Value *Op : II->args()) { 1356 const ValueLatticeElement &State = getValueState(Op); 1357 if (State.isConstantRange()) 1358 OpRanges.push_back(State.getConstantRange()); 1359 else 1360 OpRanges.push_back( 1361 ConstantRange::getFull(Op->getType()->getScalarSizeInBits())); 1362 } 1363 1364 ConstantRange Result = 1365 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges); 1366 return (void)mergeInValue(II, ValueLatticeElement::getRange(Result)); 1367 } 1368 } 1369 1370 // The common case is that we aren't tracking the callee, either because we 1371 // are not doing interprocedural analysis or the callee is indirect, or is 1372 // external. Handle these cases first. 1373 if (!F || F->isDeclaration()) 1374 return handleCallOverdefined(CB); 1375 1376 // If this is a single/zero retval case, see if we're tracking the function. 1377 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) { 1378 if (!MRVFunctionsTracked.count(F)) 1379 return handleCallOverdefined(CB); // Not tracking this callee. 1380 1381 // If we are tracking this callee, propagate the result of the function 1382 // into this call site. 1383 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1384 mergeInValue(getStructValueState(&CB, i), &CB, 1385 TrackedMultipleRetVals[std::make_pair(F, i)], 1386 getMaxWidenStepsOpts()); 1387 } else { 1388 auto TFRVI = TrackedRetVals.find(F); 1389 if (TFRVI == TrackedRetVals.end()) 1390 return handleCallOverdefined(CB); // Not tracking this callee. 1391 1392 // If so, propagate the return value of the callee into this call result. 1393 mergeInValue(&CB, TFRVI->second, getMaxWidenStepsOpts()); 1394 } 1395 } 1396 1397 void SCCPInstVisitor::solve() { 1398 // Process the work lists until they are empty! 1399 while (!BBWorkList.empty() || !InstWorkList.empty() || 1400 !OverdefinedInstWorkList.empty()) { 1401 // Process the overdefined instruction's work list first, which drives other 1402 // things to overdefined more quickly. 1403 while (!OverdefinedInstWorkList.empty()) { 1404 Value *I = OverdefinedInstWorkList.pop_back_val(); 1405 1406 LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n'); 1407 1408 // "I" got into the work list because it either made the transition from 1409 // bottom to constant, or to overdefined. 1410 // 1411 // Anything on this worklist that is overdefined need not be visited 1412 // since all of its users will have already been marked as overdefined 1413 // Update all of the users of this instruction's value. 1414 // 1415 markUsersAsChanged(I); 1416 } 1417 1418 // Process the instruction work list. 1419 while (!InstWorkList.empty()) { 1420 Value *I = InstWorkList.pop_back_val(); 1421 1422 LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n'); 1423 1424 // "I" got into the work list because it made the transition from undef to 1425 // constant. 1426 // 1427 // Anything on this worklist that is overdefined need not be visited 1428 // since all of its users will have already been marked as overdefined. 1429 // Update all of the users of this instruction's value. 1430 // 1431 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined()) 1432 markUsersAsChanged(I); 1433 } 1434 1435 // Process the basic block work list. 1436 while (!BBWorkList.empty()) { 1437 BasicBlock *BB = BBWorkList.pop_back_val(); 1438 1439 LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n'); 1440 1441 // Notify all instructions in this basic block that they are newly 1442 // executable. 1443 visit(BB); 1444 } 1445 } 1446 } 1447 1448 /// While solving the dataflow for a function, we don't compute a result for 1449 /// operations with an undef operand, to allow undef to be lowered to a 1450 /// constant later. For example, constant folding of "zext i8 undef to i16" 1451 /// would result in "i16 0", and if undef is later lowered to "i8 1", then the 1452 /// zext result would become "i16 1" and would result into an overdefined 1453 /// lattice value once merged with the previous result. Not computing the 1454 /// result of the zext (treating undef the same as unknown) allows us to handle 1455 /// a later undef->constant lowering more optimally. 1456 /// 1457 /// However, if the operand remains undef when the solver returns, we do need 1458 /// to assign some result to the instruction (otherwise we would treat it as 1459 /// unreachable). For simplicity, we mark any instructions that are still 1460 /// unknown as overdefined. 1461 bool SCCPInstVisitor::resolvedUndefsIn(Function &F) { 1462 bool MadeChange = false; 1463 for (BasicBlock &BB : F) { 1464 if (!BBExecutable.count(&BB)) 1465 continue; 1466 1467 for (Instruction &I : BB) { 1468 // Look for instructions which produce undef values. 1469 if (I.getType()->isVoidTy()) 1470 continue; 1471 1472 if (auto *STy = dyn_cast<StructType>(I.getType())) { 1473 // Only a few things that can be structs matter for undef. 1474 1475 // Tracked calls must never be marked overdefined in resolvedUndefsIn. 1476 if (auto *CB = dyn_cast<CallBase>(&I)) 1477 if (Function *F = CB->getCalledFunction()) 1478 if (MRVFunctionsTracked.count(F)) 1479 continue; 1480 1481 // extractvalue and insertvalue don't need to be marked; they are 1482 // tracked as precisely as their operands. 1483 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I)) 1484 continue; 1485 // Send the results of everything else to overdefined. We could be 1486 // more precise than this but it isn't worth bothering. 1487 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1488 ValueLatticeElement &LV = getStructValueState(&I, i); 1489 if (LV.isUnknown()) { 1490 markOverdefined(LV, &I); 1491 MadeChange = true; 1492 } 1493 } 1494 continue; 1495 } 1496 1497 ValueLatticeElement &LV = getValueState(&I); 1498 if (!LV.isUnknown()) 1499 continue; 1500 1501 // There are two reasons a call can have an undef result 1502 // 1. It could be tracked. 1503 // 2. It could be constant-foldable. 1504 // Because of the way we solve return values, tracked calls must 1505 // never be marked overdefined in resolvedUndefsIn. 1506 if (auto *CB = dyn_cast<CallBase>(&I)) 1507 if (Function *F = CB->getCalledFunction()) 1508 if (TrackedRetVals.count(F)) 1509 continue; 1510 1511 if (isa<LoadInst>(I)) { 1512 // A load here means one of two things: a load of undef from a global, 1513 // a load from an unknown pointer. Either way, having it return undef 1514 // is okay. 1515 continue; 1516 } 1517 1518 markOverdefined(&I); 1519 MadeChange = true; 1520 } 1521 } 1522 1523 return MadeChange; 1524 } 1525 1526 //===----------------------------------------------------------------------===// 1527 // 1528 // SCCPSolver implementations 1529 // 1530 SCCPSolver::SCCPSolver( 1531 const DataLayout &DL, 1532 std::function<const TargetLibraryInfo &(Function &)> GetTLI, 1533 LLVMContext &Ctx) 1534 : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {} 1535 1536 SCCPSolver::~SCCPSolver() = default; 1537 1538 void SCCPSolver::addAnalysis(Function &F, AnalysisResultsForFn A) { 1539 return Visitor->addAnalysis(F, std::move(A)); 1540 } 1541 1542 bool SCCPSolver::markBlockExecutable(BasicBlock *BB) { 1543 return Visitor->markBlockExecutable(BB); 1544 } 1545 1546 const PredicateBase *SCCPSolver::getPredicateInfoFor(Instruction *I) { 1547 return Visitor->getPredicateInfoFor(I); 1548 } 1549 1550 DomTreeUpdater SCCPSolver::getDTU(Function &F) { return Visitor->getDTU(F); } 1551 1552 void SCCPSolver::trackValueOfGlobalVariable(GlobalVariable *GV) { 1553 Visitor->trackValueOfGlobalVariable(GV); 1554 } 1555 1556 void SCCPSolver::addTrackedFunction(Function *F) { 1557 Visitor->addTrackedFunction(F); 1558 } 1559 1560 void SCCPSolver::addToMustPreserveReturnsInFunctions(Function *F) { 1561 Visitor->addToMustPreserveReturnsInFunctions(F); 1562 } 1563 1564 bool SCCPSolver::mustPreserveReturn(Function *F) { 1565 return Visitor->mustPreserveReturn(F); 1566 } 1567 1568 void SCCPSolver::addArgumentTrackedFunction(Function *F) { 1569 Visitor->addArgumentTrackedFunction(F); 1570 } 1571 1572 bool SCCPSolver::isArgumentTrackedFunction(Function *F) { 1573 return Visitor->isArgumentTrackedFunction(F); 1574 } 1575 1576 void SCCPSolver::solve() { Visitor->solve(); } 1577 1578 bool SCCPSolver::resolvedUndefsIn(Function &F) { 1579 return Visitor->resolvedUndefsIn(F); 1580 } 1581 1582 bool SCCPSolver::isBlockExecutable(BasicBlock *BB) const { 1583 return Visitor->isBlockExecutable(BB); 1584 } 1585 1586 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const { 1587 return Visitor->isEdgeFeasible(From, To); 1588 } 1589 1590 std::vector<ValueLatticeElement> 1591 SCCPSolver::getStructLatticeValueFor(Value *V) const { 1592 return Visitor->getStructLatticeValueFor(V); 1593 } 1594 1595 void SCCPSolver::removeLatticeValueFor(Value *V) { 1596 return Visitor->removeLatticeValueFor(V); 1597 } 1598 1599 const ValueLatticeElement &SCCPSolver::getLatticeValueFor(Value *V) const { 1600 return Visitor->getLatticeValueFor(V); 1601 } 1602 1603 const MapVector<Function *, ValueLatticeElement> & 1604 SCCPSolver::getTrackedRetVals() { 1605 return Visitor->getTrackedRetVals(); 1606 } 1607 1608 const DenseMap<GlobalVariable *, ValueLatticeElement> & 1609 SCCPSolver::getTrackedGlobals() { 1610 return Visitor->getTrackedGlobals(); 1611 } 1612 1613 const SmallPtrSet<Function *, 16> SCCPSolver::getMRVFunctionsTracked() { 1614 return Visitor->getMRVFunctionsTracked(); 1615 } 1616 1617 void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); } 1618 1619 bool SCCPSolver::isStructLatticeConstant(Function *F, StructType *STy) { 1620 return Visitor->isStructLatticeConstant(F, STy); 1621 } 1622 1623 Constant *SCCPSolver::getConstant(const ValueLatticeElement &LV) const { 1624 return Visitor->getConstant(LV); 1625 } 1626 1627 SmallPtrSetImpl<Function *> &SCCPSolver::getArgumentTrackedFunctions() { 1628 return Visitor->getArgumentTrackedFunctions(); 1629 } 1630 1631 void SCCPSolver::markArgInFuncSpecialization( 1632 Function *F, const SmallVectorImpl<ArgInfo> &Args) { 1633 Visitor->markArgInFuncSpecialization(F, Args); 1634 } 1635 1636 void SCCPSolver::markFunctionUnreachable(Function *F) { 1637 Visitor->markFunctionUnreachable(F); 1638 } 1639 1640 void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); } 1641 1642 void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); } 1643