1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===// 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 inline cost analysis. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/InlineCost.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SetVector.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/AssumptionCache.h" 20 #include "llvm/Analysis/BlockFrequencyInfo.h" 21 #include "llvm/Analysis/CFG.h" 22 #include "llvm/Analysis/CodeMetrics.h" 23 #include "llvm/Analysis/ConstantFolding.h" 24 #include "llvm/Analysis/InstructionSimplify.h" 25 #include "llvm/Analysis/LoopInfo.h" 26 #include "llvm/Analysis/ProfileSummaryInfo.h" 27 #include "llvm/Analysis/TargetTransformInfo.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Config/llvm-config.h" 30 #include "llvm/IR/CallingConv.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/GetElementPtrTypeIterator.h" 34 #include "llvm/IR/GlobalAlias.h" 35 #include "llvm/IR/InstVisitor.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/Operator.h" 38 #include "llvm/IR/PatternMatch.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/raw_ostream.h" 42 43 using namespace llvm; 44 45 #define DEBUG_TYPE "inline-cost" 46 47 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed"); 48 49 static cl::opt<int> InlineThreshold( 50 "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore, 51 cl::desc("Control the amount of inlining to perform (default = 225)")); 52 53 static cl::opt<int> HintThreshold( 54 "inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore, 55 cl::desc("Threshold for inlining functions with inline hint")); 56 57 static cl::opt<int> 58 ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, 59 cl::init(45), cl::ZeroOrMore, 60 cl::desc("Threshold for inlining cold callsites")); 61 62 // We introduce this threshold to help performance of instrumentation based 63 // PGO before we actually hook up inliner with analysis passes such as BPI and 64 // BFI. 65 static cl::opt<int> ColdThreshold( 66 "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore, 67 cl::desc("Threshold for inlining functions with cold attribute")); 68 69 static cl::opt<int> 70 HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), 71 cl::ZeroOrMore, 72 cl::desc("Threshold for hot callsites ")); 73 74 static cl::opt<int> LocallyHotCallSiteThreshold( 75 "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore, 76 cl::desc("Threshold for locally hot callsites ")); 77 78 static cl::opt<int> ColdCallSiteRelFreq( 79 "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, 80 cl::desc("Maximum block frequency, expressed as a percentage of caller's " 81 "entry frequency, for a callsite to be cold in the absence of " 82 "profile information.")); 83 84 static cl::opt<int> HotCallSiteRelFreq( 85 "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore, 86 cl::desc("Minimum block frequency, expressed as a multiple of caller's " 87 "entry frequency, for a callsite to be hot in the absence of " 88 "profile information.")); 89 90 static cl::opt<bool> OptComputeFullInlineCost( 91 "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore, 92 cl::desc("Compute the full inline cost of a call site even when the cost " 93 "exceeds the threshold.")); 94 95 namespace { 96 97 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> { 98 typedef InstVisitor<CallAnalyzer, bool> Base; 99 friend class InstVisitor<CallAnalyzer, bool>; 100 101 /// The TargetTransformInfo available for this compilation. 102 const TargetTransformInfo &TTI; 103 104 /// Getter for the cache of @llvm.assume intrinsics. 105 std::function<AssumptionCache &(Function &)> &GetAssumptionCache; 106 107 /// Getter for BlockFrequencyInfo 108 Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI; 109 110 /// Profile summary information. 111 ProfileSummaryInfo *PSI; 112 113 /// The called function. 114 Function &F; 115 116 // Cache the DataLayout since we use it a lot. 117 const DataLayout &DL; 118 119 /// The OptimizationRemarkEmitter available for this compilation. 120 OptimizationRemarkEmitter *ORE; 121 122 /// The candidate callsite being analyzed. Please do not use this to do 123 /// analysis in the caller function; we want the inline cost query to be 124 /// easily cacheable. Instead, use the cover function paramHasAttr. 125 CallBase &CandidateCall; 126 127 /// Tunable parameters that control the analysis. 128 const InlineParams &Params; 129 130 /// Upper bound for the inlining cost. Bonuses are being applied to account 131 /// for speculative "expected profit" of the inlining decision. 132 int Threshold; 133 134 /// Inlining cost measured in abstract units, accounts for all the 135 /// instructions expected to be executed for a given function invocation. 136 /// Instructions that are statically proven to be dead based on call-site 137 /// arguments are not counted here. 138 int Cost = 0; 139 140 bool ComputeFullInlineCost; 141 142 bool IsCallerRecursive = false; 143 bool IsRecursiveCall = false; 144 bool ExposesReturnsTwice = false; 145 bool HasDynamicAlloca = false; 146 bool ContainsNoDuplicateCall = false; 147 bool HasReturn = false; 148 bool HasIndirectBr = false; 149 bool HasUninlineableIntrinsic = false; 150 bool InitsVargArgs = false; 151 152 /// Attempt to evaluate indirect calls to boost its inline cost. 153 bool BoostIndirectCalls; 154 155 /// Number of bytes allocated statically by the callee. 156 uint64_t AllocatedSize = 0; 157 unsigned NumInstructions = 0; 158 unsigned NumVectorInstructions = 0; 159 160 /// Bonus to be applied when percentage of vector instructions in callee is 161 /// high (see more details in updateThreshold). 162 int VectorBonus = 0; 163 /// Bonus to be applied when the callee has only one reachable basic block. 164 int SingleBBBonus = 0; 165 166 /// While we walk the potentially-inlined instructions, we build up and 167 /// maintain a mapping of simplified values specific to this callsite. The 168 /// idea is to propagate any special information we have about arguments to 169 /// this call through the inlinable section of the function, and account for 170 /// likely simplifications post-inlining. The most important aspect we track 171 /// is CFG altering simplifications -- when we prove a basic block dead, that 172 /// can cause dramatic shifts in the cost of inlining a function. 173 DenseMap<Value *, Constant *> SimplifiedValues; 174 175 /// Keep track of the values which map back (through function arguments) to 176 /// allocas on the caller stack which could be simplified through SROA. 177 DenseMap<Value *, Value *> SROAArgValues; 178 179 /// The mapping of caller Alloca values to their accumulated cost savings. If 180 /// we have to disable SROA for one of the allocas, this tells us how much 181 /// cost must be added. 182 DenseMap<Value *, int> SROAArgCosts; 183 184 /// Keep track of values which map to a pointer base and constant offset. 185 DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs; 186 187 /// Keep track of dead blocks due to the constant arguments. 188 SetVector<BasicBlock *> DeadBlocks; 189 190 /// The mapping of the blocks to their known unique successors due to the 191 /// constant arguments. 192 DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors; 193 194 /// Model the elimination of repeated loads that is expected to happen 195 /// whenever we simplify away the stores that would otherwise cause them to be 196 /// loads. 197 bool EnableLoadElimination; 198 SmallPtrSet<Value *, 16> LoadAddrSet; 199 int LoadEliminationCost = 0; 200 201 // Custom simplification helper routines. 202 bool isAllocaDerivedArg(Value *V); 203 bool lookupSROAArgAndCost(Value *V, Value *&Arg, 204 DenseMap<Value *, int>::iterator &CostIt); 205 void disableSROA(DenseMap<Value *, int>::iterator CostIt); 206 void disableSROA(Value *V); 207 void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB); 208 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 209 int InstructionCost); 210 void disableLoadElimination(); 211 bool isGEPFree(GetElementPtrInst &GEP); 212 bool canFoldInboundsGEP(GetElementPtrInst &I); 213 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset); 214 bool simplifyCallSite(Function *F, CallBase &Call); 215 template <typename Callable> 216 bool simplifyInstruction(Instruction &I, Callable Evaluate); 217 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V); 218 219 /// Return true if the given argument to the function being considered for 220 /// inlining has the given attribute set either at the call site or the 221 /// function declaration. Primarily used to inspect call site specific 222 /// attributes since these can be more precise than the ones on the callee 223 /// itself. 224 bool paramHasAttr(Argument *A, Attribute::AttrKind Attr); 225 226 /// Return true if the given value is known non null within the callee if 227 /// inlined through this particular callsite. 228 bool isKnownNonNullInCallee(Value *V); 229 230 /// Update Threshold based on callsite properties such as callee 231 /// attributes and callee hotness for PGO builds. The Callee is explicitly 232 /// passed to support analyzing indirect calls whose target is inferred by 233 /// analysis. 234 void updateThreshold(CallBase &Call, Function &Callee); 235 236 /// Return true if size growth is allowed when inlining the callee at \p Call. 237 bool allowSizeGrowth(CallBase &Call); 238 239 /// Return true if \p Call is a cold callsite. 240 bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI); 241 242 /// Return a higher threshold if \p Call is a hot callsite. 243 Optional<int> getHotCallSiteThreshold(CallBase &Call, 244 BlockFrequencyInfo *CallerBFI); 245 246 // Custom analysis routines. 247 InlineResult analyzeBlock(BasicBlock *BB, 248 SmallPtrSetImpl<const Value *> &EphValues); 249 250 /// Handle a capped 'int' increment for Cost. 251 void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) { 252 assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound"); 253 Cost = (int)std::min(UpperBound, Cost + Inc); 254 } 255 256 // Disable several entry points to the visitor so we don't accidentally use 257 // them by declaring but not defining them here. 258 void visit(Module *); 259 void visit(Module &); 260 void visit(Function *); 261 void visit(Function &); 262 void visit(BasicBlock *); 263 void visit(BasicBlock &); 264 265 // Provide base case for our instruction visit. 266 bool visitInstruction(Instruction &I); 267 268 // Our visit overrides. 269 bool visitAlloca(AllocaInst &I); 270 bool visitPHI(PHINode &I); 271 bool visitGetElementPtr(GetElementPtrInst &I); 272 bool visitBitCast(BitCastInst &I); 273 bool visitPtrToInt(PtrToIntInst &I); 274 bool visitIntToPtr(IntToPtrInst &I); 275 bool visitCastInst(CastInst &I); 276 bool visitUnaryInstruction(UnaryInstruction &I); 277 bool visitCmpInst(CmpInst &I); 278 bool visitSub(BinaryOperator &I); 279 bool visitBinaryOperator(BinaryOperator &I); 280 bool visitFNeg(UnaryOperator &I); 281 bool visitLoad(LoadInst &I); 282 bool visitStore(StoreInst &I); 283 bool visitExtractValue(ExtractValueInst &I); 284 bool visitInsertValue(InsertValueInst &I); 285 bool visitCallBase(CallBase &Call); 286 bool visitReturnInst(ReturnInst &RI); 287 bool visitBranchInst(BranchInst &BI); 288 bool visitSelectInst(SelectInst &SI); 289 bool visitSwitchInst(SwitchInst &SI); 290 bool visitIndirectBrInst(IndirectBrInst &IBI); 291 bool visitResumeInst(ResumeInst &RI); 292 bool visitCleanupReturnInst(CleanupReturnInst &RI); 293 bool visitCatchReturnInst(CatchReturnInst &RI); 294 bool visitUnreachableInst(UnreachableInst &I); 295 296 public: 297 CallAnalyzer(const TargetTransformInfo &TTI, 298 std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 299 Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI, 300 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, 301 Function &Callee, CallBase &Call, const InlineParams &Params, 302 bool BoostIndirect = true) 303 : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI), 304 PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE), 305 CandidateCall(Call), Params(Params), Threshold(Params.DefaultThreshold), 306 ComputeFullInlineCost(OptComputeFullInlineCost || 307 Params.ComputeFullInlineCost || ORE), 308 BoostIndirectCalls(BoostIndirect), EnableLoadElimination(true) {} 309 310 InlineResult analyzeCall(CallBase &Call); 311 312 int getThreshold() { return Threshold; } 313 int getCost() { return Cost; } 314 315 // Keep a bunch of stats about the cost savings found so we can print them 316 // out when debugging. 317 unsigned NumConstantArgs = 0; 318 unsigned NumConstantOffsetPtrArgs = 0; 319 unsigned NumAllocaArgs = 0; 320 unsigned NumConstantPtrCmps = 0; 321 unsigned NumConstantPtrDiffs = 0; 322 unsigned NumInstructionsSimplified = 0; 323 unsigned SROACostSavings = 0; 324 unsigned SROACostSavingsLost = 0; 325 326 void dump(); 327 }; 328 329 } // namespace 330 331 /// Test whether the given value is an Alloca-derived function argument. 332 bool CallAnalyzer::isAllocaDerivedArg(Value *V) { 333 return SROAArgValues.count(V); 334 } 335 336 /// Lookup the SROA-candidate argument and cost iterator which V maps to. 337 /// Returns false if V does not map to a SROA-candidate. 338 bool CallAnalyzer::lookupSROAArgAndCost( 339 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) { 340 if (SROAArgValues.empty() || SROAArgCosts.empty()) 341 return false; 342 343 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V); 344 if (ArgIt == SROAArgValues.end()) 345 return false; 346 347 Arg = ArgIt->second; 348 CostIt = SROAArgCosts.find(Arg); 349 return CostIt != SROAArgCosts.end(); 350 } 351 352 /// Disable SROA for the candidate marked by this cost iterator. 353 /// 354 /// This marks the candidate as no longer viable for SROA, and adds the cost 355 /// savings associated with it back into the inline cost measurement. 356 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) { 357 // If we're no longer able to perform SROA we need to undo its cost savings 358 // and prevent subsequent analysis. 359 addCost(CostIt->second); 360 SROACostSavings -= CostIt->second; 361 SROACostSavingsLost += CostIt->second; 362 SROAArgCosts.erase(CostIt); 363 disableLoadElimination(); 364 } 365 366 /// If 'V' maps to a SROA candidate, disable SROA for it. 367 void CallAnalyzer::disableSROA(Value *V) { 368 Value *SROAArg; 369 DenseMap<Value *, int>::iterator CostIt; 370 if (lookupSROAArgAndCost(V, SROAArg, CostIt)) 371 disableSROA(CostIt); 372 } 373 374 /// Accumulate the given cost for a particular SROA candidate. 375 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt, 376 int InstructionCost) { 377 CostIt->second += InstructionCost; 378 SROACostSavings += InstructionCost; 379 } 380 381 void CallAnalyzer::disableLoadElimination() { 382 if (EnableLoadElimination) { 383 addCost(LoadEliminationCost); 384 LoadEliminationCost = 0; 385 EnableLoadElimination = false; 386 } 387 } 388 389 /// Accumulate a constant GEP offset into an APInt if possible. 390 /// 391 /// Returns false if unable to compute the offset for any reason. Respects any 392 /// simplified values known during the analysis of this callsite. 393 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) { 394 unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType()); 395 assert(IntPtrWidth == Offset.getBitWidth()); 396 397 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 398 GTI != GTE; ++GTI) { 399 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 400 if (!OpC) 401 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand())) 402 OpC = dyn_cast<ConstantInt>(SimpleOp); 403 if (!OpC) 404 return false; 405 if (OpC->isZero()) 406 continue; 407 408 // Handle a struct index, which adds its field offset to the pointer. 409 if (StructType *STy = GTI.getStructTypeOrNull()) { 410 unsigned ElementIdx = OpC->getZExtValue(); 411 const StructLayout *SL = DL.getStructLayout(STy); 412 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx)); 413 continue; 414 } 415 416 APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType())); 417 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize; 418 } 419 return true; 420 } 421 422 /// Use TTI to check whether a GEP is free. 423 /// 424 /// Respects any simplified values known during the analysis of this callsite. 425 bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) { 426 SmallVector<Value *, 4> Operands; 427 Operands.push_back(GEP.getOperand(0)); 428 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 429 if (Constant *SimpleOp = SimplifiedValues.lookup(*I)) 430 Operands.push_back(SimpleOp); 431 else 432 Operands.push_back(*I); 433 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands); 434 } 435 436 bool CallAnalyzer::visitAlloca(AllocaInst &I) { 437 // Check whether inlining will turn a dynamic alloca into a static 438 // alloca and handle that case. 439 if (I.isArrayAllocation()) { 440 Constant *Size = SimplifiedValues.lookup(I.getArraySize()); 441 if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) { 442 Type *Ty = I.getAllocatedType(); 443 AllocatedSize = SaturatingMultiplyAdd( 444 AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty).getFixedSize(), 445 AllocatedSize); 446 return Base::visitAlloca(I); 447 } 448 } 449 450 // Accumulate the allocated size. 451 if (I.isStaticAlloca()) { 452 Type *Ty = I.getAllocatedType(); 453 AllocatedSize = SaturatingAdd(DL.getTypeAllocSize(Ty).getFixedSize(), 454 AllocatedSize); 455 } 456 457 // We will happily inline static alloca instructions. 458 if (I.isStaticAlloca()) 459 return Base::visitAlloca(I); 460 461 // FIXME: This is overly conservative. Dynamic allocas are inefficient for 462 // a variety of reasons, and so we would like to not inline them into 463 // functions which don't currently have a dynamic alloca. This simply 464 // disables inlining altogether in the presence of a dynamic alloca. 465 HasDynamicAlloca = true; 466 return false; 467 } 468 469 bool CallAnalyzer::visitPHI(PHINode &I) { 470 // FIXME: We need to propagate SROA *disabling* through phi nodes, even 471 // though we don't want to propagate it's bonuses. The idea is to disable 472 // SROA if it *might* be used in an inappropriate manner. 473 474 // Phi nodes are always zero-cost. 475 // FIXME: Pointer sizes may differ between different address spaces, so do we 476 // need to use correct address space in the call to getPointerSizeInBits here? 477 // Or could we skip the getPointerSizeInBits call completely? As far as I can 478 // see the ZeroOffset is used as a dummy value, so we can probably use any 479 // bit width for the ZeroOffset? 480 APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0)); 481 bool CheckSROA = I.getType()->isPointerTy(); 482 483 // Track the constant or pointer with constant offset we've seen so far. 484 Constant *FirstC = nullptr; 485 std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset}; 486 Value *FirstV = nullptr; 487 488 for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) { 489 BasicBlock *Pred = I.getIncomingBlock(i); 490 // If the incoming block is dead, skip the incoming block. 491 if (DeadBlocks.count(Pred)) 492 continue; 493 // If the parent block of phi is not the known successor of the incoming 494 // block, skip the incoming block. 495 BasicBlock *KnownSuccessor = KnownSuccessors[Pred]; 496 if (KnownSuccessor && KnownSuccessor != I.getParent()) 497 continue; 498 499 Value *V = I.getIncomingValue(i); 500 // If the incoming value is this phi itself, skip the incoming value. 501 if (&I == V) 502 continue; 503 504 Constant *C = dyn_cast<Constant>(V); 505 if (!C) 506 C = SimplifiedValues.lookup(V); 507 508 std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset}; 509 if (!C && CheckSROA) 510 BaseAndOffset = ConstantOffsetPtrs.lookup(V); 511 512 if (!C && !BaseAndOffset.first) 513 // The incoming value is neither a constant nor a pointer with constant 514 // offset, exit early. 515 return true; 516 517 if (FirstC) { 518 if (FirstC == C) 519 // If we've seen a constant incoming value before and it is the same 520 // constant we see this time, continue checking the next incoming value. 521 continue; 522 // Otherwise early exit because we either see a different constant or saw 523 // a constant before but we have a pointer with constant offset this time. 524 return true; 525 } 526 527 if (FirstV) { 528 // The same logic as above, but check pointer with constant offset here. 529 if (FirstBaseAndOffset == BaseAndOffset) 530 continue; 531 return true; 532 } 533 534 if (C) { 535 // This is the 1st time we've seen a constant, record it. 536 FirstC = C; 537 continue; 538 } 539 540 // The remaining case is that this is the 1st time we've seen a pointer with 541 // constant offset, record it. 542 FirstV = V; 543 FirstBaseAndOffset = BaseAndOffset; 544 } 545 546 // Check if we can map phi to a constant. 547 if (FirstC) { 548 SimplifiedValues[&I] = FirstC; 549 return true; 550 } 551 552 // Check if we can map phi to a pointer with constant offset. 553 if (FirstBaseAndOffset.first) { 554 ConstantOffsetPtrs[&I] = FirstBaseAndOffset; 555 556 Value *SROAArg; 557 DenseMap<Value *, int>::iterator CostIt; 558 if (lookupSROAArgAndCost(FirstV, SROAArg, CostIt)) 559 SROAArgValues[&I] = SROAArg; 560 } 561 562 return true; 563 } 564 565 /// Check we can fold GEPs of constant-offset call site argument pointers. 566 /// This requires target data and inbounds GEPs. 567 /// 568 /// \return true if the specified GEP can be folded. 569 bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) { 570 // Check if we have a base + offset for the pointer. 571 std::pair<Value *, APInt> BaseAndOffset = 572 ConstantOffsetPtrs.lookup(I.getPointerOperand()); 573 if (!BaseAndOffset.first) 574 return false; 575 576 // Check if the offset of this GEP is constant, and if so accumulate it 577 // into Offset. 578 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) 579 return false; 580 581 // Add the result as a new mapping to Base + Offset. 582 ConstantOffsetPtrs[&I] = BaseAndOffset; 583 584 return true; 585 } 586 587 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) { 588 Value *SROAArg; 589 DenseMap<Value *, int>::iterator CostIt; 590 bool SROACandidate = 591 lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt); 592 593 // Lambda to check whether a GEP's indices are all constant. 594 auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) { 595 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 596 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I)) 597 return false; 598 return true; 599 }; 600 601 if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) { 602 if (SROACandidate) 603 SROAArgValues[&I] = SROAArg; 604 605 // Constant GEPs are modeled as free. 606 return true; 607 } 608 609 // Variable GEPs will require math and will disable SROA. 610 if (SROACandidate) 611 disableSROA(CostIt); 612 return isGEPFree(I); 613 } 614 615 /// Simplify \p I if its operands are constants and update SimplifiedValues. 616 /// \p Evaluate is a callable specific to instruction type that evaluates the 617 /// instruction when all the operands are constants. 618 template <typename Callable> 619 bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) { 620 SmallVector<Constant *, 2> COps; 621 for (Value *Op : I.operands()) { 622 Constant *COp = dyn_cast<Constant>(Op); 623 if (!COp) 624 COp = SimplifiedValues.lookup(Op); 625 if (!COp) 626 return false; 627 COps.push_back(COp); 628 } 629 auto *C = Evaluate(COps); 630 if (!C) 631 return false; 632 SimplifiedValues[&I] = C; 633 return true; 634 } 635 636 bool CallAnalyzer::visitBitCast(BitCastInst &I) { 637 // Propagate constants through bitcasts. 638 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 639 return ConstantExpr::getBitCast(COps[0], I.getType()); 640 })) 641 return true; 642 643 // Track base/offsets through casts 644 std::pair<Value *, APInt> BaseAndOffset = 645 ConstantOffsetPtrs.lookup(I.getOperand(0)); 646 // Casts don't change the offset, just wrap it up. 647 if (BaseAndOffset.first) 648 ConstantOffsetPtrs[&I] = BaseAndOffset; 649 650 // Also look for SROA candidates here. 651 Value *SROAArg; 652 DenseMap<Value *, int>::iterator CostIt; 653 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 654 SROAArgValues[&I] = SROAArg; 655 656 // Bitcasts are always zero cost. 657 return true; 658 } 659 660 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) { 661 // Propagate constants through ptrtoint. 662 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 663 return ConstantExpr::getPtrToInt(COps[0], I.getType()); 664 })) 665 return true; 666 667 // Track base/offset pairs when converted to a plain integer provided the 668 // integer is large enough to represent the pointer. 669 unsigned IntegerSize = I.getType()->getScalarSizeInBits(); 670 unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace(); 671 if (IntegerSize >= DL.getPointerSizeInBits(AS)) { 672 std::pair<Value *, APInt> BaseAndOffset = 673 ConstantOffsetPtrs.lookup(I.getOperand(0)); 674 if (BaseAndOffset.first) 675 ConstantOffsetPtrs[&I] = BaseAndOffset; 676 } 677 678 // This is really weird. Technically, ptrtoint will disable SROA. However, 679 // unless that ptrtoint is *used* somewhere in the live basic blocks after 680 // inlining, it will be nuked, and SROA should proceed. All of the uses which 681 // would block SROA would also block SROA if applied directly to a pointer, 682 // and so we can just add the integer in here. The only places where SROA is 683 // preserved either cannot fire on an integer, or won't in-and-of themselves 684 // disable SROA (ext) w/o some later use that we would see and disable. 685 Value *SROAArg; 686 DenseMap<Value *, int>::iterator CostIt; 687 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) 688 SROAArgValues[&I] = SROAArg; 689 690 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 691 } 692 693 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) { 694 // Propagate constants through ptrtoint. 695 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 696 return ConstantExpr::getIntToPtr(COps[0], I.getType()); 697 })) 698 return true; 699 700 // Track base/offset pairs when round-tripped through a pointer without 701 // modifications provided the integer is not too large. 702 Value *Op = I.getOperand(0); 703 unsigned IntegerSize = Op->getType()->getScalarSizeInBits(); 704 if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) { 705 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op); 706 if (BaseAndOffset.first) 707 ConstantOffsetPtrs[&I] = BaseAndOffset; 708 } 709 710 // "Propagate" SROA here in the same manner as we do for ptrtoint above. 711 Value *SROAArg; 712 DenseMap<Value *, int>::iterator CostIt; 713 if (lookupSROAArgAndCost(Op, SROAArg, CostIt)) 714 SROAArgValues[&I] = SROAArg; 715 716 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 717 } 718 719 bool CallAnalyzer::visitCastInst(CastInst &I) { 720 // Propagate constants through casts. 721 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 722 return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType()); 723 })) 724 return true; 725 726 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere. 727 disableSROA(I.getOperand(0)); 728 729 // If this is a floating-point cast, and the target says this operation 730 // is expensive, this may eventually become a library call. Treat the cost 731 // as such. 732 switch (I.getOpcode()) { 733 case Instruction::FPTrunc: 734 case Instruction::FPExt: 735 case Instruction::UIToFP: 736 case Instruction::SIToFP: 737 case Instruction::FPToUI: 738 case Instruction::FPToSI: 739 if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive) 740 addCost(InlineConstants::CallPenalty); 741 break; 742 default: 743 break; 744 } 745 746 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 747 } 748 749 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) { 750 Value *Operand = I.getOperand(0); 751 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 752 return ConstantFoldInstOperands(&I, COps[0], DL); 753 })) 754 return true; 755 756 // Disable any SROA on the argument to arbitrary unary instructions. 757 disableSROA(Operand); 758 759 return false; 760 } 761 762 bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) { 763 return CandidateCall.paramHasAttr(A->getArgNo(), Attr); 764 } 765 766 bool CallAnalyzer::isKnownNonNullInCallee(Value *V) { 767 // Does the *call site* have the NonNull attribute set on an argument? We 768 // use the attribute on the call site to memoize any analysis done in the 769 // caller. This will also trip if the callee function has a non-null 770 // parameter attribute, but that's a less interesting case because hopefully 771 // the callee would already have been simplified based on that. 772 if (Argument *A = dyn_cast<Argument>(V)) 773 if (paramHasAttr(A, Attribute::NonNull)) 774 return true; 775 776 // Is this an alloca in the caller? This is distinct from the attribute case 777 // above because attributes aren't updated within the inliner itself and we 778 // always want to catch the alloca derived case. 779 if (isAllocaDerivedArg(V)) 780 // We can actually predict the result of comparisons between an 781 // alloca-derived value and null. Note that this fires regardless of 782 // SROA firing. 783 return true; 784 785 return false; 786 } 787 788 bool CallAnalyzer::allowSizeGrowth(CallBase &Call) { 789 // If the normal destination of the invoke or the parent block of the call 790 // site is unreachable-terminated, there is little point in inlining this 791 // unless there is literally zero cost. 792 // FIXME: Note that it is possible that an unreachable-terminated block has a 793 // hot entry. For example, in below scenario inlining hot_call_X() may be 794 // beneficial : 795 // main() { 796 // hot_call_1(); 797 // ... 798 // hot_call_N() 799 // exit(0); 800 // } 801 // For now, we are not handling this corner case here as it is rare in real 802 // code. In future, we should elaborate this based on BPI and BFI in more 803 // general threshold adjusting heuristics in updateThreshold(). 804 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) { 805 if (isa<UnreachableInst>(II->getNormalDest()->getTerminator())) 806 return false; 807 } else if (isa<UnreachableInst>(Call.getParent()->getTerminator())) 808 return false; 809 810 return true; 811 } 812 813 bool CallAnalyzer::isColdCallSite(CallBase &Call, 814 BlockFrequencyInfo *CallerBFI) { 815 // If global profile summary is available, then callsite's coldness is 816 // determined based on that. 817 if (PSI && PSI->hasProfileSummary()) 818 return PSI->isColdCallSite(CallSite(&Call), CallerBFI); 819 820 // Otherwise we need BFI to be available. 821 if (!CallerBFI) 822 return false; 823 824 // Determine if the callsite is cold relative to caller's entry. We could 825 // potentially cache the computation of scaled entry frequency, but the added 826 // complexity is not worth it unless this scaling shows up high in the 827 // profiles. 828 const BranchProbability ColdProb(ColdCallSiteRelFreq, 100); 829 auto CallSiteBB = Call.getParent(); 830 auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB); 831 auto CallerEntryFreq = 832 CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock())); 833 return CallSiteFreq < CallerEntryFreq * ColdProb; 834 } 835 836 Optional<int> 837 CallAnalyzer::getHotCallSiteThreshold(CallBase &Call, 838 BlockFrequencyInfo *CallerBFI) { 839 840 // If global profile summary is available, then callsite's hotness is 841 // determined based on that. 842 if (PSI && PSI->hasProfileSummary() && 843 PSI->isHotCallSite(CallSite(&Call), CallerBFI)) 844 return Params.HotCallSiteThreshold; 845 846 // Otherwise we need BFI to be available and to have a locally hot callsite 847 // threshold. 848 if (!CallerBFI || !Params.LocallyHotCallSiteThreshold) 849 return None; 850 851 // Determine if the callsite is hot relative to caller's entry. We could 852 // potentially cache the computation of scaled entry frequency, but the added 853 // complexity is not worth it unless this scaling shows up high in the 854 // profiles. 855 auto CallSiteBB = Call.getParent(); 856 auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency(); 857 auto CallerEntryFreq = CallerBFI->getEntryFreq(); 858 if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq) 859 return Params.LocallyHotCallSiteThreshold; 860 861 // Otherwise treat it normally. 862 return None; 863 } 864 865 void CallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) { 866 // If no size growth is allowed for this inlining, set Threshold to 0. 867 if (!allowSizeGrowth(Call)) { 868 Threshold = 0; 869 return; 870 } 871 872 Function *Caller = Call.getCaller(); 873 874 // return min(A, B) if B is valid. 875 auto MinIfValid = [](int A, Optional<int> B) { 876 return B ? std::min(A, B.getValue()) : A; 877 }; 878 879 // return max(A, B) if B is valid. 880 auto MaxIfValid = [](int A, Optional<int> B) { 881 return B ? std::max(A, B.getValue()) : A; 882 }; 883 884 // Various bonus percentages. These are multiplied by Threshold to get the 885 // bonus values. 886 // SingleBBBonus: This bonus is applied if the callee has a single reachable 887 // basic block at the given callsite context. This is speculatively applied 888 // and withdrawn if more than one basic block is seen. 889 // 890 // LstCallToStaticBonus: This large bonus is applied to ensure the inlining 891 // of the last call to a static function as inlining such functions is 892 // guaranteed to reduce code size. 893 // 894 // These bonus percentages may be set to 0 based on properties of the caller 895 // and the callsite. 896 int SingleBBBonusPercent = 50; 897 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent(); 898 int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus; 899 900 // Lambda to set all the above bonus and bonus percentages to 0. 901 auto DisallowAllBonuses = [&]() { 902 SingleBBBonusPercent = 0; 903 VectorBonusPercent = 0; 904 LastCallToStaticBonus = 0; 905 }; 906 907 // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available 908 // and reduce the threshold if the caller has the necessary attribute. 909 if (Caller->hasMinSize()) { 910 Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold); 911 // For minsize, we want to disable the single BB bonus and the vector 912 // bonuses, but not the last-call-to-static bonus. Inlining the last call to 913 // a static function will, at the minimum, eliminate the parameter setup and 914 // call/return instructions. 915 SingleBBBonusPercent = 0; 916 VectorBonusPercent = 0; 917 } else if (Caller->hasOptSize()) 918 Threshold = MinIfValid(Threshold, Params.OptSizeThreshold); 919 920 // Adjust the threshold based on inlinehint attribute and profile based 921 // hotness information if the caller does not have MinSize attribute. 922 if (!Caller->hasMinSize()) { 923 if (Callee.hasFnAttribute(Attribute::InlineHint)) 924 Threshold = MaxIfValid(Threshold, Params.HintThreshold); 925 926 // FIXME: After switching to the new passmanager, simplify the logic below 927 // by checking only the callsite hotness/coldness as we will reliably 928 // have local profile information. 929 // 930 // Callsite hotness and coldness can be determined if sample profile is 931 // used (which adds hotness metadata to calls) or if caller's 932 // BlockFrequencyInfo is available. 933 BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr; 934 auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI); 935 if (!Caller->hasOptSize() && HotCallSiteThreshold) { 936 LLVM_DEBUG(dbgs() << "Hot callsite.\n"); 937 // FIXME: This should update the threshold only if it exceeds the 938 // current threshold, but AutoFDO + ThinLTO currently relies on this 939 // behavior to prevent inlining of hot callsites during ThinLTO 940 // compile phase. 941 Threshold = HotCallSiteThreshold.getValue(); 942 } else if (isColdCallSite(Call, CallerBFI)) { 943 LLVM_DEBUG(dbgs() << "Cold callsite.\n"); 944 // Do not apply bonuses for a cold callsite including the 945 // LastCallToStatic bonus. While this bonus might result in code size 946 // reduction, it can cause the size of a non-cold caller to increase 947 // preventing it from being inlined. 948 DisallowAllBonuses(); 949 Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold); 950 } else if (PSI) { 951 // Use callee's global profile information only if we have no way of 952 // determining this via callsite information. 953 if (PSI->isFunctionEntryHot(&Callee)) { 954 LLVM_DEBUG(dbgs() << "Hot callee.\n"); 955 // If callsite hotness can not be determined, we may still know 956 // that the callee is hot and treat it as a weaker hint for threshold 957 // increase. 958 Threshold = MaxIfValid(Threshold, Params.HintThreshold); 959 } else if (PSI->isFunctionEntryCold(&Callee)) { 960 LLVM_DEBUG(dbgs() << "Cold callee.\n"); 961 // Do not apply bonuses for a cold callee including the 962 // LastCallToStatic bonus. While this bonus might result in code size 963 // reduction, it can cause the size of a non-cold caller to increase 964 // preventing it from being inlined. 965 DisallowAllBonuses(); 966 Threshold = MinIfValid(Threshold, Params.ColdThreshold); 967 } 968 } 969 } 970 971 // Finally, take the target-specific inlining threshold multiplier into 972 // account. 973 Threshold *= TTI.getInliningThresholdMultiplier(); 974 975 SingleBBBonus = Threshold * SingleBBBonusPercent / 100; 976 VectorBonus = Threshold * VectorBonusPercent / 100; 977 978 bool OnlyOneCallAndLocalLinkage = 979 F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction(); 980 // If there is only one call of the function, and it has internal linkage, 981 // the cost of inlining it drops dramatically. It may seem odd to update 982 // Cost in updateThreshold, but the bonus depends on the logic in this method. 983 if (OnlyOneCallAndLocalLinkage) 984 Cost -= LastCallToStaticBonus; 985 } 986 987 bool CallAnalyzer::visitCmpInst(CmpInst &I) { 988 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 989 // First try to handle simplified comparisons. 990 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 991 return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]); 992 })) 993 return true; 994 995 if (I.getOpcode() == Instruction::FCmp) 996 return false; 997 998 // Otherwise look for a comparison between constant offset pointers with 999 // a common base. 1000 Value *LHSBase, *RHSBase; 1001 APInt LHSOffset, RHSOffset; 1002 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 1003 if (LHSBase) { 1004 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 1005 if (RHSBase && LHSBase == RHSBase) { 1006 // We have common bases, fold the icmp to a constant based on the 1007 // offsets. 1008 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 1009 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 1010 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) { 1011 SimplifiedValues[&I] = C; 1012 ++NumConstantPtrCmps; 1013 return true; 1014 } 1015 } 1016 } 1017 1018 // If the comparison is an equality comparison with null, we can simplify it 1019 // if we know the value (argument) can't be null 1020 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) && 1021 isKnownNonNullInCallee(I.getOperand(0))) { 1022 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE; 1023 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType()) 1024 : ConstantInt::getFalse(I.getType()); 1025 return true; 1026 } 1027 // Finally check for SROA candidates in comparisons. 1028 Value *SROAArg; 1029 DenseMap<Value *, int>::iterator CostIt; 1030 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) { 1031 if (isa<ConstantPointerNull>(I.getOperand(1))) { 1032 accumulateSROACost(CostIt, InlineConstants::InstrCost); 1033 return true; 1034 } 1035 1036 disableSROA(CostIt); 1037 } 1038 1039 return false; 1040 } 1041 1042 bool CallAnalyzer::visitSub(BinaryOperator &I) { 1043 // Try to handle a special case: we can fold computing the difference of two 1044 // constant-related pointers. 1045 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1046 Value *LHSBase, *RHSBase; 1047 APInt LHSOffset, RHSOffset; 1048 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 1049 if (LHSBase) { 1050 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 1051 if (RHSBase && LHSBase == RHSBase) { 1052 // We have common bases, fold the subtract to a constant based on the 1053 // offsets. 1054 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 1055 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 1056 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) { 1057 SimplifiedValues[&I] = C; 1058 ++NumConstantPtrDiffs; 1059 return true; 1060 } 1061 } 1062 } 1063 1064 // Otherwise, fall back to the generic logic for simplifying and handling 1065 // instructions. 1066 return Base::visitSub(I); 1067 } 1068 1069 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) { 1070 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1071 Constant *CLHS = dyn_cast<Constant>(LHS); 1072 if (!CLHS) 1073 CLHS = SimplifiedValues.lookup(LHS); 1074 Constant *CRHS = dyn_cast<Constant>(RHS); 1075 if (!CRHS) 1076 CRHS = SimplifiedValues.lookup(RHS); 1077 1078 Value *SimpleV = nullptr; 1079 if (auto FI = dyn_cast<FPMathOperator>(&I)) 1080 SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, 1081 CRHS ? CRHS : RHS, FI->getFastMathFlags(), DL); 1082 else 1083 SimpleV = 1084 SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL); 1085 1086 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 1087 SimplifiedValues[&I] = C; 1088 1089 if (SimpleV) 1090 return true; 1091 1092 // Disable any SROA on arguments to arbitrary, unsimplified binary operators. 1093 disableSROA(LHS); 1094 disableSROA(RHS); 1095 1096 // If the instruction is floating point, and the target says this operation 1097 // is expensive, this may eventually become a library call. Treat the cost 1098 // as such. Unless it's fneg which can be implemented with an xor. 1099 using namespace llvm::PatternMatch; 1100 if (I.getType()->isFloatingPointTy() && 1101 TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive && 1102 !match(&I, m_FNeg(m_Value()))) 1103 addCost(InlineConstants::CallPenalty); 1104 1105 return false; 1106 } 1107 1108 bool CallAnalyzer::visitFNeg(UnaryOperator &I) { 1109 Value *Op = I.getOperand(0); 1110 Constant *COp = dyn_cast<Constant>(Op); 1111 if (!COp) 1112 COp = SimplifiedValues.lookup(Op); 1113 1114 Value *SimpleV = SimplifyFNegInst(COp ? COp : Op, 1115 cast<FPMathOperator>(I).getFastMathFlags(), 1116 DL); 1117 1118 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 1119 SimplifiedValues[&I] = C; 1120 1121 if (SimpleV) 1122 return true; 1123 1124 // Disable any SROA on arguments to arbitrary, unsimplified fneg. 1125 disableSROA(Op); 1126 1127 return false; 1128 } 1129 1130 bool CallAnalyzer::visitLoad(LoadInst &I) { 1131 Value *SROAArg; 1132 DenseMap<Value *, int>::iterator CostIt; 1133 if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) { 1134 if (I.isSimple()) { 1135 accumulateSROACost(CostIt, InlineConstants::InstrCost); 1136 return true; 1137 } 1138 1139 disableSROA(CostIt); 1140 } 1141 1142 // If the data is already loaded from this address and hasn't been clobbered 1143 // by any stores or calls, this load is likely to be redundant and can be 1144 // eliminated. 1145 if (EnableLoadElimination && 1146 !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) { 1147 LoadEliminationCost += InlineConstants::InstrCost; 1148 return true; 1149 } 1150 1151 return false; 1152 } 1153 1154 bool CallAnalyzer::visitStore(StoreInst &I) { 1155 Value *SROAArg; 1156 DenseMap<Value *, int>::iterator CostIt; 1157 if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) { 1158 if (I.isSimple()) { 1159 accumulateSROACost(CostIt, InlineConstants::InstrCost); 1160 return true; 1161 } 1162 1163 disableSROA(CostIt); 1164 } 1165 1166 // The store can potentially clobber loads and prevent repeated loads from 1167 // being eliminated. 1168 // FIXME: 1169 // 1. We can probably keep an initial set of eliminatable loads substracted 1170 // from the cost even when we finally see a store. We just need to disable 1171 // *further* accumulation of elimination savings. 1172 // 2. We should probably at some point thread MemorySSA for the callee into 1173 // this and then use that to actually compute *really* precise savings. 1174 disableLoadElimination(); 1175 return false; 1176 } 1177 1178 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) { 1179 // Constant folding for extract value is trivial. 1180 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1181 return ConstantExpr::getExtractValue(COps[0], I.getIndices()); 1182 })) 1183 return true; 1184 1185 // SROA can look through these but give them a cost. 1186 return false; 1187 } 1188 1189 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) { 1190 // Constant folding for insert value is trivial. 1191 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1192 return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0], 1193 /*InsertedValueOperand*/ COps[1], 1194 I.getIndices()); 1195 })) 1196 return true; 1197 1198 // SROA can look through these but give them a cost. 1199 return false; 1200 } 1201 1202 /// Try to simplify a call site. 1203 /// 1204 /// Takes a concrete function and callsite and tries to actually simplify it by 1205 /// analyzing the arguments and call itself with instsimplify. Returns true if 1206 /// it has simplified the callsite to some other entity (a constant), making it 1207 /// free. 1208 bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) { 1209 // FIXME: Using the instsimplify logic directly for this is inefficient 1210 // because we have to continually rebuild the argument list even when no 1211 // simplifications can be performed. Until that is fixed with remapping 1212 // inside of instsimplify, directly constant fold calls here. 1213 if (!canConstantFoldCallTo(&Call, F)) 1214 return false; 1215 1216 // Try to re-map the arguments to constants. 1217 SmallVector<Constant *, 4> ConstantArgs; 1218 ConstantArgs.reserve(Call.arg_size()); 1219 for (Value *I : Call.args()) { 1220 Constant *C = dyn_cast<Constant>(I); 1221 if (!C) 1222 C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I)); 1223 if (!C) 1224 return false; // This argument doesn't map to a constant. 1225 1226 ConstantArgs.push_back(C); 1227 } 1228 if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) { 1229 SimplifiedValues[&Call] = C; 1230 return true; 1231 } 1232 1233 return false; 1234 } 1235 1236 bool CallAnalyzer::visitCallBase(CallBase &Call) { 1237 if (Call.hasFnAttr(Attribute::ReturnsTwice) && 1238 !F.hasFnAttribute(Attribute::ReturnsTwice)) { 1239 // This aborts the entire analysis. 1240 ExposesReturnsTwice = true; 1241 return false; 1242 } 1243 if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate()) 1244 ContainsNoDuplicateCall = true; 1245 1246 Value *Callee = Call.getCalledOperand(); 1247 Function *F = dyn_cast_or_null<Function>(Callee); 1248 bool IsIndirectCall = !F; 1249 if (IsIndirectCall) { 1250 // Check if this happens to be an indirect function call to a known function 1251 // in this inline context. If not, we've done all we can. 1252 F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee)); 1253 if (!F) { 1254 // Pay the price of the argument setup. We account for the average 1 1255 // instruction per call argument setup here. 1256 addCost(Call.arg_size() * InlineConstants::InstrCost); 1257 1258 if (!Call.onlyReadsMemory()) 1259 disableLoadElimination(); 1260 return Base::visitCallBase(Call); 1261 } 1262 } 1263 1264 assert(F && "Expected a call to a known function"); 1265 1266 // When we have a concrete function, first try to simplify it directly. 1267 if (simplifyCallSite(F, Call)) 1268 return true; 1269 1270 // Next check if it is an intrinsic we know about. 1271 // FIXME: Lift this into part of the InstVisitor. 1272 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) { 1273 switch (II->getIntrinsicID()) { 1274 default: 1275 if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II)) 1276 disableLoadElimination(); 1277 return Base::visitCallBase(Call); 1278 1279 case Intrinsic::load_relative: 1280 // This is normally lowered to 4 LLVM instructions. 1281 addCost(3 * InlineConstants::InstrCost); 1282 return false; 1283 1284 case Intrinsic::memset: 1285 case Intrinsic::memcpy: 1286 case Intrinsic::memmove: 1287 disableLoadElimination(); 1288 // SROA can usually chew through these intrinsics, but they aren't free. 1289 return false; 1290 case Intrinsic::icall_branch_funnel: 1291 case Intrinsic::localescape: 1292 HasUninlineableIntrinsic = true; 1293 return false; 1294 case Intrinsic::vastart: 1295 InitsVargArgs = true; 1296 return false; 1297 } 1298 } 1299 1300 if (F == Call.getFunction()) { 1301 // This flag will fully abort the analysis, so don't bother with anything 1302 // else. 1303 IsRecursiveCall = true; 1304 return false; 1305 } 1306 1307 if (TTI.isLoweredToCall(F)) { 1308 // We account for the average 1 instruction per call argument setup here. 1309 addCost(Call.arg_size() * InlineConstants::InstrCost); 1310 1311 // If we have a constant that we are calling as a function, we can peer 1312 // through it and see the function target. This happens not infrequently 1313 // during devirtualization and so we want to give it a hefty bonus for 1314 // inlining, but cap that bonus in the event that inlining wouldn't pan out. 1315 // Pretend to inline the function, with a custom threshold. 1316 if (IsIndirectCall && BoostIndirectCalls) { 1317 auto IndirectCallParams = Params; 1318 IndirectCallParams.DefaultThreshold = 1319 InlineConstants::IndirectCallThreshold; 1320 CallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F, Call, 1321 IndirectCallParams, false); 1322 if (CA.analyzeCall(Call)) { 1323 // We were able to inline the indirect call! Subtract the cost from the 1324 // threshold to get the bonus we want to apply, but don't go below zero. 1325 Cost -= std::max(0, CA.getThreshold() - CA.getCost()); 1326 } 1327 } else 1328 // Otherwise simply add the cost for merely making the call. 1329 addCost(InlineConstants::CallPenalty); 1330 } 1331 1332 if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory()))) 1333 disableLoadElimination(); 1334 return Base::visitCallBase(Call); 1335 } 1336 1337 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) { 1338 // At least one return instruction will be free after inlining. 1339 bool Free = !HasReturn; 1340 HasReturn = true; 1341 return Free; 1342 } 1343 1344 bool CallAnalyzer::visitBranchInst(BranchInst &BI) { 1345 // We model unconditional branches as essentially free -- they really 1346 // shouldn't exist at all, but handling them makes the behavior of the 1347 // inliner more regular and predictable. Interestingly, conditional branches 1348 // which will fold away are also free. 1349 return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) || 1350 dyn_cast_or_null<ConstantInt>( 1351 SimplifiedValues.lookup(BI.getCondition())); 1352 } 1353 1354 bool CallAnalyzer::visitSelectInst(SelectInst &SI) { 1355 bool CheckSROA = SI.getType()->isPointerTy(); 1356 Value *TrueVal = SI.getTrueValue(); 1357 Value *FalseVal = SI.getFalseValue(); 1358 1359 Constant *TrueC = dyn_cast<Constant>(TrueVal); 1360 if (!TrueC) 1361 TrueC = SimplifiedValues.lookup(TrueVal); 1362 Constant *FalseC = dyn_cast<Constant>(FalseVal); 1363 if (!FalseC) 1364 FalseC = SimplifiedValues.lookup(FalseVal); 1365 Constant *CondC = 1366 dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition())); 1367 1368 if (!CondC) { 1369 // Select C, X, X => X 1370 if (TrueC == FalseC && TrueC) { 1371 SimplifiedValues[&SI] = TrueC; 1372 return true; 1373 } 1374 1375 if (!CheckSROA) 1376 return Base::visitSelectInst(SI); 1377 1378 std::pair<Value *, APInt> TrueBaseAndOffset = 1379 ConstantOffsetPtrs.lookup(TrueVal); 1380 std::pair<Value *, APInt> FalseBaseAndOffset = 1381 ConstantOffsetPtrs.lookup(FalseVal); 1382 if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) { 1383 ConstantOffsetPtrs[&SI] = TrueBaseAndOffset; 1384 1385 Value *SROAArg; 1386 DenseMap<Value *, int>::iterator CostIt; 1387 if (lookupSROAArgAndCost(TrueVal, SROAArg, CostIt)) 1388 SROAArgValues[&SI] = SROAArg; 1389 return true; 1390 } 1391 1392 return Base::visitSelectInst(SI); 1393 } 1394 1395 // Select condition is a constant. 1396 Value *SelectedV = CondC->isAllOnesValue() 1397 ? TrueVal 1398 : (CondC->isNullValue()) ? FalseVal : nullptr; 1399 if (!SelectedV) { 1400 // Condition is a vector constant that is not all 1s or all 0s. If all 1401 // operands are constants, ConstantExpr::getSelect() can handle the cases 1402 // such as select vectors. 1403 if (TrueC && FalseC) { 1404 if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) { 1405 SimplifiedValues[&SI] = C; 1406 return true; 1407 } 1408 } 1409 return Base::visitSelectInst(SI); 1410 } 1411 1412 // Condition is either all 1s or all 0s. SI can be simplified. 1413 if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) { 1414 SimplifiedValues[&SI] = SelectedC; 1415 return true; 1416 } 1417 1418 if (!CheckSROA) 1419 return true; 1420 1421 std::pair<Value *, APInt> BaseAndOffset = 1422 ConstantOffsetPtrs.lookup(SelectedV); 1423 if (BaseAndOffset.first) { 1424 ConstantOffsetPtrs[&SI] = BaseAndOffset; 1425 1426 Value *SROAArg; 1427 DenseMap<Value *, int>::iterator CostIt; 1428 if (lookupSROAArgAndCost(SelectedV, SROAArg, CostIt)) 1429 SROAArgValues[&SI] = SROAArg; 1430 } 1431 1432 return true; 1433 } 1434 1435 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) { 1436 // We model unconditional switches as free, see the comments on handling 1437 // branches. 1438 if (isa<ConstantInt>(SI.getCondition())) 1439 return true; 1440 if (Value *V = SimplifiedValues.lookup(SI.getCondition())) 1441 if (isa<ConstantInt>(V)) 1442 return true; 1443 1444 // Assume the most general case where the switch is lowered into 1445 // either a jump table, bit test, or a balanced binary tree consisting of 1446 // case clusters without merging adjacent clusters with the same 1447 // destination. We do not consider the switches that are lowered with a mix 1448 // of jump table/bit test/binary search tree. The cost of the switch is 1449 // proportional to the size of the tree or the size of jump table range. 1450 // 1451 // NB: We convert large switches which are just used to initialize large phi 1452 // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent 1453 // inlining those. It will prevent inlining in cases where the optimization 1454 // does not (yet) fire. 1455 1456 // Maximum valid cost increased in this function. 1457 int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1; 1458 1459 unsigned JumpTableSize = 0; 1460 BlockFrequencyInfo *BFI = GetBFI ? &((*GetBFI)(F)) : nullptr; 1461 unsigned NumCaseCluster = 1462 TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI); 1463 1464 // If suitable for a jump table, consider the cost for the table size and 1465 // branch to destination. 1466 if (JumpTableSize) { 1467 int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost + 1468 4 * InlineConstants::InstrCost; 1469 1470 addCost(JTCost, (int64_t)CostUpperBound); 1471 return false; 1472 } 1473 1474 // Considering forming a binary search, we should find the number of nodes 1475 // which is same as the number of comparisons when lowered. For a given 1476 // number of clusters, n, we can define a recursive function, f(n), to find 1477 // the number of nodes in the tree. The recursion is : 1478 // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3, 1479 // and f(n) = n, when n <= 3. 1480 // This will lead a binary tree where the leaf should be either f(2) or f(3) 1481 // when n > 3. So, the number of comparisons from leaves should be n, while 1482 // the number of non-leaf should be : 1483 // 2^(log2(n) - 1) - 1 1484 // = 2^log2(n) * 2^-1 - 1 1485 // = n / 2 - 1. 1486 // Considering comparisons from leaf and non-leaf nodes, we can estimate the 1487 // number of comparisons in a simple closed form : 1488 // n + n / 2 - 1 = n * 3 / 2 - 1 1489 if (NumCaseCluster <= 3) { 1490 // Suppose a comparison includes one compare and one conditional branch. 1491 addCost(NumCaseCluster * 2 * InlineConstants::InstrCost); 1492 return false; 1493 } 1494 1495 int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1; 1496 int64_t SwitchCost = 1497 ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost; 1498 1499 addCost(SwitchCost, (int64_t)CostUpperBound); 1500 return false; 1501 } 1502 1503 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) { 1504 // We never want to inline functions that contain an indirectbr. This is 1505 // incorrect because all the blockaddress's (in static global initializers 1506 // for example) would be referring to the original function, and this 1507 // indirect jump would jump from the inlined copy of the function into the 1508 // original function which is extremely undefined behavior. 1509 // FIXME: This logic isn't really right; we can safely inline functions with 1510 // indirectbr's as long as no other function or global references the 1511 // blockaddress of a block within the current function. 1512 HasIndirectBr = true; 1513 return false; 1514 } 1515 1516 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) { 1517 // FIXME: It's not clear that a single instruction is an accurate model for 1518 // the inline cost of a resume instruction. 1519 return false; 1520 } 1521 1522 bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) { 1523 // FIXME: It's not clear that a single instruction is an accurate model for 1524 // the inline cost of a cleanupret instruction. 1525 return false; 1526 } 1527 1528 bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) { 1529 // FIXME: It's not clear that a single instruction is an accurate model for 1530 // the inline cost of a catchret instruction. 1531 return false; 1532 } 1533 1534 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) { 1535 // FIXME: It might be reasonably to discount the cost of instructions leading 1536 // to unreachable as they have the lowest possible impact on both runtime and 1537 // code size. 1538 return true; // No actual code is needed for unreachable. 1539 } 1540 1541 bool CallAnalyzer::visitInstruction(Instruction &I) { 1542 // Some instructions are free. All of the free intrinsics can also be 1543 // handled by SROA, etc. 1544 if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I)) 1545 return true; 1546 1547 // We found something we don't understand or can't handle. Mark any SROA-able 1548 // values in the operand list as no longer viable. 1549 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI) 1550 disableSROA(*OI); 1551 1552 return false; 1553 } 1554 1555 /// Analyze a basic block for its contribution to the inline cost. 1556 /// 1557 /// This method walks the analyzer over every instruction in the given basic 1558 /// block and accounts for their cost during inlining at this callsite. It 1559 /// aborts early if the threshold has been exceeded or an impossible to inline 1560 /// construct has been detected. It returns false if inlining is no longer 1561 /// viable, and true if inlining remains viable. 1562 InlineResult 1563 CallAnalyzer::analyzeBlock(BasicBlock *BB, 1564 SmallPtrSetImpl<const Value *> &EphValues) { 1565 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1566 // FIXME: Currently, the number of instructions in a function regardless of 1567 // our ability to simplify them during inline to constants or dead code, 1568 // are actually used by the vector bonus heuristic. As long as that's true, 1569 // we have to special case debug intrinsics here to prevent differences in 1570 // inlining due to debug symbols. Eventually, the number of unsimplified 1571 // instructions shouldn't factor into the cost computation, but until then, 1572 // hack around it here. 1573 if (isa<DbgInfoIntrinsic>(I)) 1574 continue; 1575 1576 // Skip ephemeral values. 1577 if (EphValues.count(&*I)) 1578 continue; 1579 1580 ++NumInstructions; 1581 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy()) 1582 ++NumVectorInstructions; 1583 1584 // If the instruction simplified to a constant, there is no cost to this 1585 // instruction. Visit the instructions using our InstVisitor to account for 1586 // all of the per-instruction logic. The visit tree returns true if we 1587 // consumed the instruction in any way, and false if the instruction's base 1588 // cost should count against inlining. 1589 if (Base::visit(&*I)) 1590 ++NumInstructionsSimplified; 1591 else 1592 addCost(InlineConstants::InstrCost); 1593 1594 using namespace ore; 1595 // If the visit this instruction detected an uninlinable pattern, abort. 1596 InlineResult IR; 1597 if (IsRecursiveCall) 1598 IR = "recursive"; 1599 else if (ExposesReturnsTwice) 1600 IR = "exposes returns twice"; 1601 else if (HasDynamicAlloca) 1602 IR = "dynamic alloca"; 1603 else if (HasIndirectBr) 1604 IR = "indirect branch"; 1605 else if (HasUninlineableIntrinsic) 1606 IR = "uninlinable intrinsic"; 1607 else if (InitsVargArgs) 1608 IR = "varargs"; 1609 if (!IR) { 1610 if (ORE) 1611 ORE->emit([&]() { 1612 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 1613 &CandidateCall) 1614 << NV("Callee", &F) << " has uninlinable pattern (" 1615 << NV("InlineResult", IR.message) 1616 << ") and cost is not fully computed"; 1617 }); 1618 return IR; 1619 } 1620 1621 // If the caller is a recursive function then we don't want to inline 1622 // functions which allocate a lot of stack space because it would increase 1623 // the caller stack usage dramatically. 1624 if (IsCallerRecursive && 1625 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) { 1626 InlineResult IR = "recursive and allocates too much stack space"; 1627 if (ORE) 1628 ORE->emit([&]() { 1629 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 1630 &CandidateCall) 1631 << NV("Callee", &F) << " is " << NV("InlineResult", IR.message) 1632 << ". Cost is not fully computed"; 1633 }); 1634 return IR; 1635 } 1636 1637 // Check if we've passed the maximum possible threshold so we don't spin in 1638 // huge basic blocks that will never inline. 1639 if (Cost >= Threshold && !ComputeFullInlineCost) 1640 return false; 1641 } 1642 1643 return true; 1644 } 1645 1646 /// Compute the base pointer and cumulative constant offsets for V. 1647 /// 1648 /// This strips all constant offsets off of V, leaving it the base pointer, and 1649 /// accumulates the total constant offset applied in the returned constant. It 1650 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 1651 /// no constant offsets applied. 1652 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) { 1653 if (!V->getType()->isPointerTy()) 1654 return nullptr; 1655 1656 unsigned AS = V->getType()->getPointerAddressSpace(); 1657 unsigned IntPtrWidth = DL.getIndexSizeInBits(AS); 1658 APInt Offset = APInt::getNullValue(IntPtrWidth); 1659 1660 // Even though we don't look through PHI nodes, we could be called on an 1661 // instruction in an unreachable block, which may be on a cycle. 1662 SmallPtrSet<Value *, 4> Visited; 1663 Visited.insert(V); 1664 do { 1665 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 1666 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset)) 1667 return nullptr; 1668 V = GEP->getPointerOperand(); 1669 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 1670 V = cast<Operator>(V)->getOperand(0); 1671 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 1672 if (GA->isInterposable()) 1673 break; 1674 V = GA->getAliasee(); 1675 } else { 1676 break; 1677 } 1678 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 1679 } while (Visited.insert(V).second); 1680 1681 Type *IntPtrTy = DL.getIntPtrType(V->getContext(), AS); 1682 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset)); 1683 } 1684 1685 /// Find dead blocks due to deleted CFG edges during inlining. 1686 /// 1687 /// If we know the successor of the current block, \p CurrBB, has to be \p 1688 /// NextBB, the other successors of \p CurrBB are dead if these successors have 1689 /// no live incoming CFG edges. If one block is found to be dead, we can 1690 /// continue growing the dead block list by checking the successors of the dead 1691 /// blocks to see if all their incoming edges are dead or not. 1692 void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) { 1693 auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) { 1694 // A CFG edge is dead if the predecessor is dead or the predecessor has a 1695 // known successor which is not the one under exam. 1696 return (DeadBlocks.count(Pred) || 1697 (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ)); 1698 }; 1699 1700 auto IsNewlyDead = [&](BasicBlock *BB) { 1701 // If all the edges to a block are dead, the block is also dead. 1702 return (!DeadBlocks.count(BB) && 1703 llvm::all_of(predecessors(BB), 1704 [&](BasicBlock *P) { return IsEdgeDead(P, BB); })); 1705 }; 1706 1707 for (BasicBlock *Succ : successors(CurrBB)) { 1708 if (Succ == NextBB || !IsNewlyDead(Succ)) 1709 continue; 1710 SmallVector<BasicBlock *, 4> NewDead; 1711 NewDead.push_back(Succ); 1712 while (!NewDead.empty()) { 1713 BasicBlock *Dead = NewDead.pop_back_val(); 1714 if (DeadBlocks.insert(Dead)) 1715 // Continue growing the dead block lists. 1716 for (BasicBlock *S : successors(Dead)) 1717 if (IsNewlyDead(S)) 1718 NewDead.push_back(S); 1719 } 1720 } 1721 } 1722 1723 /// Analyze a call site for potential inlining. 1724 /// 1725 /// Returns true if inlining this call is viable, and false if it is not 1726 /// viable. It computes the cost and adjusts the threshold based on numerous 1727 /// factors and heuristics. If this method returns false but the computed cost 1728 /// is below the computed threshold, then inlining was forcibly disabled by 1729 /// some artifact of the routine. 1730 InlineResult CallAnalyzer::analyzeCall(CallBase &Call) { 1731 ++NumCallsAnalyzed; 1732 1733 // Perform some tweaks to the cost and threshold based on the direct 1734 // callsite information. 1735 1736 // We want to more aggressively inline vector-dense kernels, so up the 1737 // threshold, and we'll lower it if the % of vector instructions gets too 1738 // low. Note that these bonuses are some what arbitrary and evolved over time 1739 // by accident as much as because they are principled bonuses. 1740 // 1741 // FIXME: It would be nice to remove all such bonuses. At least it would be 1742 // nice to base the bonus values on something more scientific. 1743 assert(NumInstructions == 0); 1744 assert(NumVectorInstructions == 0); 1745 1746 // Update the threshold based on callsite properties 1747 updateThreshold(Call, F); 1748 1749 // While Threshold depends on commandline options that can take negative 1750 // values, we want to enforce the invariant that the computed threshold and 1751 // bonuses are non-negative. 1752 assert(Threshold >= 0); 1753 assert(SingleBBBonus >= 0); 1754 assert(VectorBonus >= 0); 1755 1756 // Speculatively apply all possible bonuses to Threshold. If cost exceeds 1757 // this Threshold any time, and cost cannot decrease, we can stop processing 1758 // the rest of the function body. 1759 Threshold += (SingleBBBonus + VectorBonus); 1760 1761 // Give out bonuses for the callsite, as the instructions setting them up 1762 // will be gone after inlining. 1763 addCost(-getCallsiteCost(Call, DL)); 1764 1765 // If this function uses the coldcc calling convention, prefer not to inline 1766 // it. 1767 if (F.getCallingConv() == CallingConv::Cold) 1768 Cost += InlineConstants::ColdccPenalty; 1769 1770 // Check if we're done. This can happen due to bonuses and penalties. 1771 if (Cost >= Threshold && !ComputeFullInlineCost) 1772 return "high cost"; 1773 1774 if (F.empty()) 1775 return true; 1776 1777 Function *Caller = Call.getFunction(); 1778 // Check if the caller function is recursive itself. 1779 for (User *U : Caller->users()) { 1780 CallBase *Call = dyn_cast<CallBase>(U); 1781 if (Call && Call->getFunction() == Caller) { 1782 IsCallerRecursive = true; 1783 break; 1784 } 1785 } 1786 1787 // Populate our simplified values by mapping from function arguments to call 1788 // arguments with known important simplifications. 1789 auto CAI = Call.arg_begin(); 1790 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end(); 1791 FAI != FAE; ++FAI, ++CAI) { 1792 assert(CAI != Call.arg_end()); 1793 if (Constant *C = dyn_cast<Constant>(CAI)) 1794 SimplifiedValues[&*FAI] = C; 1795 1796 Value *PtrArg = *CAI; 1797 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) { 1798 ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue()); 1799 1800 // We can SROA any pointer arguments derived from alloca instructions. 1801 if (isa<AllocaInst>(PtrArg)) { 1802 SROAArgValues[&*FAI] = PtrArg; 1803 SROAArgCosts[PtrArg] = 0; 1804 } 1805 } 1806 } 1807 NumConstantArgs = SimplifiedValues.size(); 1808 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size(); 1809 NumAllocaArgs = SROAArgValues.size(); 1810 1811 // FIXME: If a caller has multiple calls to a callee, we end up recomputing 1812 // the ephemeral values multiple times (and they're completely determined by 1813 // the callee, so this is purely duplicate work). 1814 SmallPtrSet<const Value *, 32> EphValues; 1815 CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues); 1816 1817 // The worklist of live basic blocks in the callee *after* inlining. We avoid 1818 // adding basic blocks of the callee which can be proven to be dead for this 1819 // particular call site in order to get more accurate cost estimates. This 1820 // requires a somewhat heavyweight iteration pattern: we need to walk the 1821 // basic blocks in a breadth-first order as we insert live successors. To 1822 // accomplish this, prioritizing for small iterations because we exit after 1823 // crossing our threshold, we use a small-size optimized SetVector. 1824 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>, 1825 SmallPtrSet<BasicBlock *, 16>> 1826 BBSetVector; 1827 BBSetVector BBWorklist; 1828 BBWorklist.insert(&F.getEntryBlock()); 1829 bool SingleBB = true; 1830 // Note that we *must not* cache the size, this loop grows the worklist. 1831 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 1832 // Bail out the moment we cross the threshold. This means we'll under-count 1833 // the cost, but only when undercounting doesn't matter. 1834 if (Cost >= Threshold && !ComputeFullInlineCost) 1835 break; 1836 1837 BasicBlock *BB = BBWorklist[Idx]; 1838 if (BB->empty()) 1839 continue; 1840 1841 // Disallow inlining a blockaddress with uses other than strictly callbr. 1842 // A blockaddress only has defined behavior for an indirect branch in the 1843 // same function, and we do not currently support inlining indirect 1844 // branches. But, the inliner may not see an indirect branch that ends up 1845 // being dead code at a particular call site. If the blockaddress escapes 1846 // the function, e.g., via a global variable, inlining may lead to an 1847 // invalid cross-function reference. 1848 // FIXME: pr/39560: continue relaxing this overt restriction. 1849 if (BB->hasAddressTaken()) 1850 for (User *U : BlockAddress::get(&*BB)->users()) 1851 if (!isa<CallBrInst>(*U)) 1852 return "blockaddress used outside of callbr"; 1853 1854 // Analyze the cost of this block. If we blow through the threshold, this 1855 // returns false, and we can bail on out. 1856 InlineResult IR = analyzeBlock(BB, EphValues); 1857 if (!IR) 1858 return IR; 1859 1860 Instruction *TI = BB->getTerminator(); 1861 1862 // Add in the live successors by first checking whether we have terminator 1863 // that may be simplified based on the values simplified by this call. 1864 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1865 if (BI->isConditional()) { 1866 Value *Cond = BI->getCondition(); 1867 if (ConstantInt *SimpleCond = 1868 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 1869 BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0); 1870 BBWorklist.insert(NextBB); 1871 KnownSuccessors[BB] = NextBB; 1872 findDeadBlocks(BB, NextBB); 1873 continue; 1874 } 1875 } 1876 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 1877 Value *Cond = SI->getCondition(); 1878 if (ConstantInt *SimpleCond = 1879 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 1880 BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor(); 1881 BBWorklist.insert(NextBB); 1882 KnownSuccessors[BB] = NextBB; 1883 findDeadBlocks(BB, NextBB); 1884 continue; 1885 } 1886 } 1887 1888 // If we're unable to select a particular successor, just count all of 1889 // them. 1890 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize; 1891 ++TIdx) 1892 BBWorklist.insert(TI->getSuccessor(TIdx)); 1893 1894 // If we had any successors at this point, than post-inlining is likely to 1895 // have them as well. Note that we assume any basic blocks which existed 1896 // due to branches or switches which folded above will also fold after 1897 // inlining. 1898 if (SingleBB && TI->getNumSuccessors() > 1) { 1899 // Take off the bonus we applied to the threshold. 1900 Threshold -= SingleBBBonus; 1901 SingleBB = false; 1902 } 1903 } 1904 1905 bool OnlyOneCallAndLocalLinkage = 1906 F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction(); 1907 // If this is a noduplicate call, we can still inline as long as 1908 // inlining this would cause the removal of the caller (so the instruction 1909 // is not actually duplicated, just moved). 1910 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall) 1911 return "noduplicate"; 1912 1913 // Loops generally act a lot like calls in that they act like barriers to 1914 // movement, require a certain amount of setup, etc. So when optimising for 1915 // size, we penalise any call sites that perform loops. We do this after all 1916 // other costs here, so will likely only be dealing with relatively small 1917 // functions (and hence DT and LI will hopefully be cheap). 1918 if (Caller->hasMinSize()) { 1919 DominatorTree DT(F); 1920 LoopInfo LI(DT); 1921 int NumLoops = 0; 1922 for (Loop *L : LI) { 1923 // Ignore loops that will not be executed 1924 if (DeadBlocks.count(L->getHeader())) 1925 continue; 1926 NumLoops++; 1927 } 1928 addCost(NumLoops * InlineConstants::CallPenalty); 1929 } 1930 1931 // We applied the maximum possible vector bonus at the beginning. Now, 1932 // subtract the excess bonus, if any, from the Threshold before 1933 // comparing against Cost. 1934 if (NumVectorInstructions <= NumInstructions / 10) 1935 Threshold -= VectorBonus; 1936 else if (NumVectorInstructions <= NumInstructions / 2) 1937 Threshold -= VectorBonus/2; 1938 1939 return Cost < std::max(1, Threshold); 1940 } 1941 1942 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1943 /// Dump stats about this call's analysis. 1944 LLVM_DUMP_METHOD void CallAnalyzer::dump() { 1945 #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n" 1946 DEBUG_PRINT_STAT(NumConstantArgs); 1947 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs); 1948 DEBUG_PRINT_STAT(NumAllocaArgs); 1949 DEBUG_PRINT_STAT(NumConstantPtrCmps); 1950 DEBUG_PRINT_STAT(NumConstantPtrDiffs); 1951 DEBUG_PRINT_STAT(NumInstructionsSimplified); 1952 DEBUG_PRINT_STAT(NumInstructions); 1953 DEBUG_PRINT_STAT(SROACostSavings); 1954 DEBUG_PRINT_STAT(SROACostSavingsLost); 1955 DEBUG_PRINT_STAT(LoadEliminationCost); 1956 DEBUG_PRINT_STAT(ContainsNoDuplicateCall); 1957 DEBUG_PRINT_STAT(Cost); 1958 DEBUG_PRINT_STAT(Threshold); 1959 #undef DEBUG_PRINT_STAT 1960 } 1961 #endif 1962 1963 /// Test that there are no attribute conflicts between Caller and Callee 1964 /// that prevent inlining. 1965 static bool functionsHaveCompatibleAttributes(Function *Caller, 1966 Function *Callee, 1967 TargetTransformInfo &TTI) { 1968 return TTI.areInlineCompatible(Caller, Callee) && 1969 AttributeFuncs::areInlineCompatible(*Caller, *Callee); 1970 } 1971 1972 int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) { 1973 int Cost = 0; 1974 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) { 1975 if (Call.isByValArgument(I)) { 1976 // We approximate the number of loads and stores needed by dividing the 1977 // size of the byval type by the target's pointer size. 1978 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType()); 1979 unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType()); 1980 unsigned AS = PTy->getAddressSpace(); 1981 unsigned PointerSize = DL.getPointerSizeInBits(AS); 1982 // Ceiling division. 1983 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize; 1984 1985 // If it generates more than 8 stores it is likely to be expanded as an 1986 // inline memcpy so we take that as an upper bound. Otherwise we assume 1987 // one load and one store per word copied. 1988 // FIXME: The maxStoresPerMemcpy setting from the target should be used 1989 // here instead of a magic number of 8, but it's not available via 1990 // DataLayout. 1991 NumStores = std::min(NumStores, 8U); 1992 1993 Cost += 2 * NumStores * InlineConstants::InstrCost; 1994 } else { 1995 // For non-byval arguments subtract off one instruction per call 1996 // argument. 1997 Cost += InlineConstants::InstrCost; 1998 } 1999 } 2000 // The call instruction also disappears after inlining. 2001 Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty; 2002 return Cost; 2003 } 2004 2005 InlineCost llvm::getInlineCost( 2006 CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, 2007 std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 2008 Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 2009 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 2010 return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI, 2011 GetAssumptionCache, GetBFI, PSI, ORE); 2012 } 2013 2014 InlineCost llvm::getInlineCost( 2015 CallBase &Call, Function *Callee, const InlineParams &Params, 2016 TargetTransformInfo &CalleeTTI, 2017 std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 2018 Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 2019 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 2020 2021 // Cannot inline indirect calls. 2022 if (!Callee) 2023 return llvm::InlineCost::getNever("indirect call"); 2024 2025 // Never inline calls with byval arguments that does not have the alloca 2026 // address space. Since byval arguments can be replaced with a copy to an 2027 // alloca, the inlined code would need to be adjusted to handle that the 2028 // argument is in the alloca address space (so it is a little bit complicated 2029 // to solve). 2030 unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace(); 2031 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) 2032 if (Call.isByValArgument(I)) { 2033 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType()); 2034 if (PTy->getAddressSpace() != AllocaAS) 2035 return llvm::InlineCost::getNever("byval arguments without alloca" 2036 " address space"); 2037 } 2038 2039 // Calls to functions with always-inline attributes should be inlined 2040 // whenever possible. 2041 if (Call.hasFnAttr(Attribute::AlwaysInline)) { 2042 auto IsViable = isInlineViable(*Callee); 2043 if (IsViable) 2044 return llvm::InlineCost::getAlways("always inline attribute"); 2045 return llvm::InlineCost::getNever(IsViable.message); 2046 } 2047 2048 // Never inline functions with conflicting attributes (unless callee has 2049 // always-inline attribute). 2050 Function *Caller = Call.getCaller(); 2051 if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI)) 2052 return llvm::InlineCost::getNever("conflicting attributes"); 2053 2054 // Don't inline this call if the caller has the optnone attribute. 2055 if (Caller->hasOptNone()) 2056 return llvm::InlineCost::getNever("optnone attribute"); 2057 2058 // Don't inline a function that treats null pointer as valid into a caller 2059 // that does not have this attribute. 2060 if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined()) 2061 return llvm::InlineCost::getNever("nullptr definitions incompatible"); 2062 2063 // Don't inline functions which can be interposed at link-time. 2064 if (Callee->isInterposable()) 2065 return llvm::InlineCost::getNever("interposable"); 2066 2067 // Don't inline functions marked noinline. 2068 if (Callee->hasFnAttribute(Attribute::NoInline)) 2069 return llvm::InlineCost::getNever("noinline function attribute"); 2070 2071 // Don't inline call sites marked noinline. 2072 if (Call.isNoInline()) 2073 return llvm::InlineCost::getNever("noinline call site attribute"); 2074 2075 LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() 2076 << "... (caller:" << Caller->getName() << ")\n"); 2077 2078 CallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE, *Callee, 2079 Call, Params); 2080 InlineResult ShouldInline = CA.analyzeCall(Call); 2081 2082 LLVM_DEBUG(CA.dump()); 2083 2084 // Check if there was a reason to force inlining or no inlining. 2085 if (!ShouldInline && CA.getCost() < CA.getThreshold()) 2086 return InlineCost::getNever(ShouldInline.message); 2087 if (ShouldInline && CA.getCost() >= CA.getThreshold()) 2088 return InlineCost::getAlways("empty function"); 2089 2090 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold()); 2091 } 2092 2093 InlineResult llvm::isInlineViable(Function &F) { 2094 bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice); 2095 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { 2096 // Disallow inlining of functions which contain indirect branches. 2097 if (isa<IndirectBrInst>(BI->getTerminator())) 2098 return "contains indirect branches"; 2099 2100 // Disallow inlining of blockaddresses which are used by non-callbr 2101 // instructions. 2102 if (BI->hasAddressTaken()) 2103 for (User *U : BlockAddress::get(&*BI)->users()) 2104 if (!isa<CallBrInst>(*U)) 2105 return "blockaddress used outside of callbr"; 2106 2107 for (auto &II : *BI) { 2108 CallBase *Call = dyn_cast<CallBase>(&II); 2109 if (!Call) 2110 continue; 2111 2112 // Disallow recursive calls. 2113 if (&F == Call->getCalledFunction()) 2114 return "recursive call"; 2115 2116 // Disallow calls which expose returns-twice to a function not previously 2117 // attributed as such. 2118 if (!ReturnsTwice && isa<CallInst>(Call) && 2119 cast<CallInst>(Call)->canReturnTwice()) 2120 return "exposes returns-twice attribute"; 2121 2122 if (Call->getCalledFunction()) 2123 switch (Call->getCalledFunction()->getIntrinsicID()) { 2124 default: 2125 break; 2126 // Disallow inlining of @llvm.icall.branch.funnel because current 2127 // backend can't separate call targets from call arguments. 2128 case llvm::Intrinsic::icall_branch_funnel: 2129 return "disallowed inlining of @llvm.icall.branch.funnel"; 2130 // Disallow inlining functions that call @llvm.localescape. Doing this 2131 // correctly would require major changes to the inliner. 2132 case llvm::Intrinsic::localescape: 2133 return "disallowed inlining of @llvm.localescape"; 2134 // Disallow inlining of functions that initialize VarArgs with va_start. 2135 case llvm::Intrinsic::vastart: 2136 return "contains VarArgs initialized with va_start"; 2137 } 2138 } 2139 } 2140 2141 return true; 2142 } 2143 2144 // APIs to create InlineParams based on command line flags and/or other 2145 // parameters. 2146 2147 InlineParams llvm::getInlineParams(int Threshold) { 2148 InlineParams Params; 2149 2150 // This field is the threshold to use for a callee by default. This is 2151 // derived from one or more of: 2152 // * optimization or size-optimization levels, 2153 // * a value passed to createFunctionInliningPass function, or 2154 // * the -inline-threshold flag. 2155 // If the -inline-threshold flag is explicitly specified, that is used 2156 // irrespective of anything else. 2157 if (InlineThreshold.getNumOccurrences() > 0) 2158 Params.DefaultThreshold = InlineThreshold; 2159 else 2160 Params.DefaultThreshold = Threshold; 2161 2162 // Set the HintThreshold knob from the -inlinehint-threshold. 2163 Params.HintThreshold = HintThreshold; 2164 2165 // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold. 2166 Params.HotCallSiteThreshold = HotCallSiteThreshold; 2167 2168 // If the -locally-hot-callsite-threshold is explicitly specified, use it to 2169 // populate LocallyHotCallSiteThreshold. Later, we populate 2170 // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if 2171 // we know that optimization level is O3 (in the getInlineParams variant that 2172 // takes the opt and size levels). 2173 // FIXME: Remove this check (and make the assignment unconditional) after 2174 // addressing size regression issues at O2. 2175 if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0) 2176 Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2177 2178 // Set the ColdCallSiteThreshold knob from the -inline-cold-callsite-threshold. 2179 Params.ColdCallSiteThreshold = ColdCallSiteThreshold; 2180 2181 // Set the OptMinSizeThreshold and OptSizeThreshold params only if the 2182 // -inlinehint-threshold commandline option is not explicitly given. If that 2183 // option is present, then its value applies even for callees with size and 2184 // minsize attributes. 2185 // If the -inline-threshold is not specified, set the ColdThreshold from the 2186 // -inlinecold-threshold even if it is not explicitly passed. If 2187 // -inline-threshold is specified, then -inlinecold-threshold needs to be 2188 // explicitly specified to set the ColdThreshold knob 2189 if (InlineThreshold.getNumOccurrences() == 0) { 2190 Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold; 2191 Params.OptSizeThreshold = InlineConstants::OptSizeThreshold; 2192 Params.ColdThreshold = ColdThreshold; 2193 } else if (ColdThreshold.getNumOccurrences() > 0) { 2194 Params.ColdThreshold = ColdThreshold; 2195 } 2196 return Params; 2197 } 2198 2199 InlineParams llvm::getInlineParams() { 2200 return getInlineParams(InlineThreshold); 2201 } 2202 2203 // Compute the default threshold for inlining based on the opt level and the 2204 // size opt level. 2205 static int computeThresholdFromOptLevels(unsigned OptLevel, 2206 unsigned SizeOptLevel) { 2207 if (OptLevel > 2) 2208 return InlineConstants::OptAggressiveThreshold; 2209 if (SizeOptLevel == 1) // -Os 2210 return InlineConstants::OptSizeThreshold; 2211 if (SizeOptLevel == 2) // -Oz 2212 return InlineConstants::OptMinSizeThreshold; 2213 return InlineThreshold; 2214 } 2215 2216 InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) { 2217 auto Params = 2218 getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel)); 2219 // At O3, use the value of -locally-hot-callsite-threshold option to populate 2220 // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only 2221 // when it is specified explicitly. 2222 if (OptLevel > 2) 2223 Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2224 return Params; 2225 } 2226