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