1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===// 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 the SampleProfileLoader transformation. This pass 10 // reads a profile file generated by a sampling profiler (e.g. Linux Perf - 11 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the 12 // profile information in the given profile. 13 // 14 // This pass generates branch weight annotations on the IR: 15 // 16 // - prof: Represents branch weights. This annotation is added to branches 17 // to indicate the weights of each edge coming out of the branch. 18 // The weight of each edge is the weight of the target block for 19 // that edge. The weight of a block B is computed as the maximum 20 // number of samples found in B. 21 // 22 //===----------------------------------------------------------------------===// 23 24 #include "llvm/Transforms/IPO/SampleProfile.h" 25 #include "llvm/ADT/ArrayRef.h" 26 #include "llvm/ADT/DenseMap.h" 27 #include "llvm/ADT/DenseSet.h" 28 #include "llvm/ADT/None.h" 29 #include "llvm/ADT/PriorityQueue.h" 30 #include "llvm/ADT/SCCIterator.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringMap.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Analysis/AssumptionCache.h" 39 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 40 #include "llvm/Analysis/CallGraph.h" 41 #include "llvm/Analysis/CallGraphSCCPass.h" 42 #include "llvm/Analysis/InlineAdvisor.h" 43 #include "llvm/Analysis/InlineCost.h" 44 #include "llvm/Analysis/LoopInfo.h" 45 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 46 #include "llvm/Analysis/PostDominators.h" 47 #include "llvm/Analysis/ProfileSummaryInfo.h" 48 #include "llvm/Analysis/ReplayInlineAdvisor.h" 49 #include "llvm/Analysis/TargetLibraryInfo.h" 50 #include "llvm/Analysis/TargetTransformInfo.h" 51 #include "llvm/IR/BasicBlock.h" 52 #include "llvm/IR/CFG.h" 53 #include "llvm/IR/DebugInfoMetadata.h" 54 #include "llvm/IR/DebugLoc.h" 55 #include "llvm/IR/DiagnosticInfo.h" 56 #include "llvm/IR/Dominators.h" 57 #include "llvm/IR/Function.h" 58 #include "llvm/IR/GlobalValue.h" 59 #include "llvm/IR/InstrTypes.h" 60 #include "llvm/IR/Instruction.h" 61 #include "llvm/IR/Instructions.h" 62 #include "llvm/IR/IntrinsicInst.h" 63 #include "llvm/IR/LLVMContext.h" 64 #include "llvm/IR/MDBuilder.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/PassManager.h" 67 #include "llvm/IR/ValueSymbolTable.h" 68 #include "llvm/InitializePasses.h" 69 #include "llvm/Pass.h" 70 #include "llvm/ProfileData/InstrProf.h" 71 #include "llvm/ProfileData/SampleProf.h" 72 #include "llvm/ProfileData/SampleProfReader.h" 73 #include "llvm/Support/Casting.h" 74 #include "llvm/Support/CommandLine.h" 75 #include "llvm/Support/Debug.h" 76 #include "llvm/Support/ErrorHandling.h" 77 #include "llvm/Support/ErrorOr.h" 78 #include "llvm/Support/GenericDomTree.h" 79 #include "llvm/Support/raw_ostream.h" 80 #include "llvm/Transforms/IPO.h" 81 #include "llvm/Transforms/IPO/ProfiledCallGraph.h" 82 #include "llvm/Transforms/IPO/SampleContextTracker.h" 83 #include "llvm/Transforms/IPO/SampleProfileProbe.h" 84 #include "llvm/Transforms/Instrumentation.h" 85 #include "llvm/Transforms/Utils/CallPromotionUtils.h" 86 #include "llvm/Transforms/Utils/Cloning.h" 87 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h" 88 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstdint> 92 #include <functional> 93 #include <limits> 94 #include <map> 95 #include <memory> 96 #include <queue> 97 #include <string> 98 #include <system_error> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 using namespace sampleprof; 104 using namespace llvm::sampleprofutil; 105 using ProfileCount = Function::ProfileCount; 106 #define DEBUG_TYPE "sample-profile" 107 #define CSINLINE_DEBUG DEBUG_TYPE "-inline" 108 109 STATISTIC(NumCSInlined, 110 "Number of functions inlined with context sensitive profile"); 111 STATISTIC(NumCSNotInlined, 112 "Number of functions not inlined with context sensitive profile"); 113 STATISTIC(NumMismatchedProfile, 114 "Number of functions with CFG mismatched profile"); 115 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile"); 116 STATISTIC(NumDuplicatedInlinesite, 117 "Number of inlined callsites with a partial distribution factor"); 118 119 STATISTIC(NumCSInlinedHitMinLimit, 120 "Number of functions with FDO inline stopped due to min size limit"); 121 STATISTIC(NumCSInlinedHitMaxLimit, 122 "Number of functions with FDO inline stopped due to max size limit"); 123 STATISTIC( 124 NumCSInlinedHitGrowthLimit, 125 "Number of functions with FDO inline stopped due to growth size limit"); 126 127 // Command line option to specify the file to read samples from. This is 128 // mainly used for debugging. 129 static cl::opt<std::string> SampleProfileFile( 130 "sample-profile-file", cl::init(""), cl::value_desc("filename"), 131 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); 132 133 // The named file contains a set of transformations that may have been applied 134 // to the symbol names between the program from which the sample data was 135 // collected and the current program's symbols. 136 static cl::opt<std::string> SampleProfileRemappingFile( 137 "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"), 138 cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden); 139 140 static cl::opt<bool> ProfileSampleAccurate( 141 "profile-sample-accurate", cl::Hidden, cl::init(false), 142 cl::desc("If the sample profile is accurate, we will mark all un-sampled " 143 "callsite and function as having 0 samples. Otherwise, treat " 144 "un-sampled callsites and functions conservatively as unknown. ")); 145 146 static cl::opt<bool> ProfileAccurateForSymsInList( 147 "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore, 148 cl::init(true), 149 cl::desc("For symbols in profile symbol list, regard their profiles to " 150 "be accurate. It may be overriden by profile-sample-accurate. ")); 151 152 static cl::opt<bool> ProfileMergeInlinee( 153 "sample-profile-merge-inlinee", cl::Hidden, cl::init(true), 154 cl::desc("Merge past inlinee's profile to outline version if sample " 155 "profile loader decided not to inline a call site. It will " 156 "only be enabled when top-down order of profile loading is " 157 "enabled. ")); 158 159 static cl::opt<bool> ProfileTopDownLoad( 160 "sample-profile-top-down-load", cl::Hidden, cl::init(true), 161 cl::desc("Do profile annotation and inlining for functions in top-down " 162 "order of call graph during sample profile loading. It only " 163 "works for new pass manager. ")); 164 165 static cl::opt<bool> 166 UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden, 167 cl::desc("Process functions in a top-down order " 168 "defined by the profiled call graph when " 169 "-sample-profile-top-down-load is on.")); 170 171 static cl::opt<bool> ProfileSizeInline( 172 "sample-profile-inline-size", cl::Hidden, cl::init(false), 173 cl::desc("Inline cold call sites in profile loader if it's beneficial " 174 "for code size.")); 175 176 cl::opt<int> ProfileInlineGrowthLimit( 177 "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12), 178 cl::desc("The size growth ratio limit for proirity-based sample profile " 179 "loader inlining.")); 180 181 cl::opt<int> ProfileInlineLimitMin( 182 "sample-profile-inline-limit-min", cl::Hidden, cl::init(100), 183 cl::desc("The lower bound of size growth limit for " 184 "proirity-based sample profile loader inlining.")); 185 186 cl::opt<int> ProfileInlineLimitMax( 187 "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000), 188 cl::desc("The upper bound of size growth limit for " 189 "proirity-based sample profile loader inlining.")); 190 191 cl::opt<int> SampleHotCallSiteThreshold( 192 "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000), 193 cl::desc("Hot callsite threshold for proirity-based sample profile loader " 194 "inlining.")); 195 196 cl::opt<int> SampleColdCallSiteThreshold( 197 "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45), 198 cl::desc("Threshold for inlining cold callsites")); 199 200 static cl::opt<unsigned> ProfileICPRelativeHotness( 201 "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25), 202 cl::desc( 203 "Relative hotness percentage threshold for indirect " 204 "call promotion in proirity-based sample profile loader inlining.")); 205 206 static cl::opt<unsigned> ProfileICPRelativeHotnessSkip( 207 "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1), 208 cl::desc( 209 "Skip relative hotness check for ICP up to given number of targets.")); 210 211 static cl::opt<bool> CallsitePrioritizedInline( 212 "sample-profile-prioritized-inline", cl::Hidden, cl::ZeroOrMore, 213 cl::init(false), 214 cl::desc("Use call site prioritized inlining for sample profile loader." 215 "Currently only CSSPGO is supported.")); 216 217 static cl::opt<bool> UsePreInlinerDecision( 218 "sample-profile-use-preinliner", cl::Hidden, cl::ZeroOrMore, 219 cl::init(false), 220 cl::desc("Use the preinliner decisions stored in profile context.")); 221 222 static cl::opt<bool> AllowRecursiveInline( 223 "sample-profile-recursive-inline", cl::Hidden, cl::ZeroOrMore, 224 cl::init(false), 225 cl::desc("Allow sample loader inliner to inline recursive calls.")); 226 227 static cl::opt<std::string> ProfileInlineReplayFile( 228 "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"), 229 cl::desc( 230 "Optimization remarks file containing inline remarks to be replayed " 231 "by inlining from sample profile loader."), 232 cl::Hidden); 233 234 static cl::opt<unsigned> 235 MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden, 236 cl::ZeroOrMore, 237 cl::desc("Max number of promotions for a single indirect " 238 "call callsite in sample profile loader")); 239 240 static cl::opt<bool> OverwriteExistingWeights( 241 "overwrite-existing-weights", cl::Hidden, cl::init(false), 242 cl::desc("Ignore existing branch weights on IR and always overwrite.")); 243 244 namespace { 245 246 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>; 247 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>; 248 using Edge = std::pair<const BasicBlock *, const BasicBlock *>; 249 using EdgeWeightMap = DenseMap<Edge, uint64_t>; 250 using BlockEdgeMap = 251 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>; 252 253 class GUIDToFuncNameMapper { 254 public: 255 GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader, 256 DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap) 257 : CurrentReader(Reader), CurrentModule(M), 258 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) { 259 if (!CurrentReader.useMD5()) 260 return; 261 262 for (const auto &F : CurrentModule) { 263 StringRef OrigName = F.getName(); 264 CurrentGUIDToFuncNameMap.insert( 265 {Function::getGUID(OrigName), OrigName}); 266 267 // Local to global var promotion used by optimization like thinlto 268 // will rename the var and add suffix like ".llvm.xxx" to the 269 // original local name. In sample profile, the suffixes of function 270 // names are all stripped. Since it is possible that the mapper is 271 // built in post-thin-link phase and var promotion has been done, 272 // we need to add the substring of function name without the suffix 273 // into the GUIDToFuncNameMap. 274 StringRef CanonName = FunctionSamples::getCanonicalFnName(F); 275 if (CanonName != OrigName) 276 CurrentGUIDToFuncNameMap.insert( 277 {Function::getGUID(CanonName), CanonName}); 278 } 279 280 // Update GUIDToFuncNameMap for each function including inlinees. 281 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap); 282 } 283 284 ~GUIDToFuncNameMapper() { 285 if (!CurrentReader.useMD5()) 286 return; 287 288 CurrentGUIDToFuncNameMap.clear(); 289 290 // Reset GUIDToFuncNameMap for of each function as they're no 291 // longer valid at this point. 292 SetGUIDToFuncNameMapForAll(nullptr); 293 } 294 295 private: 296 void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) { 297 std::queue<FunctionSamples *> FSToUpdate; 298 for (auto &IFS : CurrentReader.getProfiles()) { 299 FSToUpdate.push(&IFS.second); 300 } 301 302 while (!FSToUpdate.empty()) { 303 FunctionSamples *FS = FSToUpdate.front(); 304 FSToUpdate.pop(); 305 FS->GUIDToFuncNameMap = Map; 306 for (const auto &ICS : FS->getCallsiteSamples()) { 307 const FunctionSamplesMap &FSMap = ICS.second; 308 for (auto &IFS : FSMap) { 309 FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second); 310 FSToUpdate.push(&FS); 311 } 312 } 313 } 314 } 315 316 SampleProfileReader &CurrentReader; 317 Module &CurrentModule; 318 DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap; 319 }; 320 321 // Inline candidate used by iterative callsite prioritized inliner 322 struct InlineCandidate { 323 CallBase *CallInstr; 324 const FunctionSamples *CalleeSamples; 325 // Prorated callsite count, which will be used to guide inlining. For example, 326 // if a callsite is duplicated in LTO prelink, then in LTO postlink the two 327 // copies will get their own distribution factors and their prorated counts 328 // will be used to decide if they should be inlined independently. 329 uint64_t CallsiteCount; 330 // Call site distribution factor to prorate the profile samples for a 331 // duplicated callsite. Default value is 1.0. 332 float CallsiteDistribution; 333 }; 334 335 // Inline candidate comparer using call site weight 336 struct CandidateComparer { 337 bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) { 338 if (LHS.CallsiteCount != RHS.CallsiteCount) 339 return LHS.CallsiteCount < RHS.CallsiteCount; 340 341 const FunctionSamples *LCS = LHS.CalleeSamples; 342 const FunctionSamples *RCS = RHS.CalleeSamples; 343 assert(LCS && RCS && "Expect non-null FunctionSamples"); 344 345 // Tie breaker using number of samples try to favor smaller functions first 346 if (LCS->getBodySamples().size() != RCS->getBodySamples().size()) 347 return LCS->getBodySamples().size() > RCS->getBodySamples().size(); 348 349 // Tie breaker using GUID so we have stable/deterministic inlining order 350 return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName()); 351 } 352 }; 353 354 using CandidateQueue = 355 PriorityQueue<InlineCandidate, std::vector<InlineCandidate>, 356 CandidateComparer>; 357 358 /// Sample profile pass. 359 /// 360 /// This pass reads profile data from the file specified by 361 /// -sample-profile-file and annotates every affected function with the 362 /// profile information found in that file. 363 class SampleProfileLoader final 364 : public SampleProfileLoaderBaseImpl<BasicBlock> { 365 public: 366 SampleProfileLoader( 367 StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase, 368 std::function<AssumptionCache &(Function &)> GetAssumptionCache, 369 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo, 370 std::function<const TargetLibraryInfo &(Function &)> GetTLI) 371 : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName)), 372 GetAC(std::move(GetAssumptionCache)), 373 GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)), 374 LTOPhase(LTOPhase) {} 375 376 bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr); 377 bool runOnModule(Module &M, ModuleAnalysisManager *AM, 378 ProfileSummaryInfo *_PSI, CallGraph *CG); 379 380 protected: 381 bool runOnFunction(Function &F, ModuleAnalysisManager *AM); 382 bool emitAnnotations(Function &F); 383 ErrorOr<uint64_t> getInstWeight(const Instruction &I) override; 384 ErrorOr<uint64_t> getProbeWeight(const Instruction &I); 385 const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const; 386 const FunctionSamples * 387 findFunctionSamples(const Instruction &I) const override; 388 std::vector<const FunctionSamples *> 389 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const; 390 void findExternalInlineCandidate(const FunctionSamples *Samples, 391 DenseSet<GlobalValue::GUID> &InlinedGUIDs, 392 const StringMap<Function *> &SymbolMap, 393 uint64_t Threshold); 394 // Attempt to promote indirect call and also inline the promoted call 395 bool tryPromoteAndInlineCandidate( 396 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, 397 uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr); 398 bool inlineHotFunctions(Function &F, 399 DenseSet<GlobalValue::GUID> &InlinedGUIDs); 400 InlineCost shouldInlineCandidate(InlineCandidate &Candidate); 401 bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB); 402 bool 403 tryInlineCandidate(InlineCandidate &Candidate, 404 SmallVector<CallBase *, 8> *InlinedCallSites = nullptr); 405 bool 406 inlineHotFunctionsWithPriority(Function &F, 407 DenseSet<GlobalValue::GUID> &InlinedGUIDs); 408 // Inline cold/small functions in addition to hot ones 409 bool shouldInlineColdCallee(CallBase &CallInst); 410 void emitOptimizationRemarksForInlineCandidates( 411 const SmallVectorImpl<CallBase *> &Candidates, const Function &F, 412 bool Hot); 413 std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG); 414 std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG); 415 void generateMDProfMetadata(Function &F); 416 417 /// Map from function name to Function *. Used to find the function from 418 /// the function name. If the function name contains suffix, additional 419 /// entry is added to map from the stripped name to the function if there 420 /// is one-to-one mapping. 421 StringMap<Function *> SymbolMap; 422 423 std::function<AssumptionCache &(Function &)> GetAC; 424 std::function<TargetTransformInfo &(Function &)> GetTTI; 425 std::function<const TargetLibraryInfo &(Function &)> GetTLI; 426 427 /// Profile tracker for different context. 428 std::unique_ptr<SampleContextTracker> ContextTracker; 429 430 /// Flag indicating whether input profile is context-sensitive 431 bool ProfileIsCS = false; 432 433 /// Flag indicating which LTO/ThinLTO phase the pass is invoked in. 434 /// 435 /// We need to know the LTO phase because for example in ThinLTOPrelink 436 /// phase, in annotation, we should not promote indirect calls. Instead, 437 /// we will mark GUIDs that needs to be annotated to the function. 438 ThinOrFullLTOPhase LTOPhase; 439 440 /// Profle Symbol list tells whether a function name appears in the binary 441 /// used to generate the current profile. 442 std::unique_ptr<ProfileSymbolList> PSL; 443 444 /// Total number of samples collected in this profile. 445 /// 446 /// This is the sum of all the samples collected in all the functions executed 447 /// at runtime. 448 uint64_t TotalCollectedSamples = 0; 449 450 // Information recorded when we declined to inline a call site 451 // because we have determined it is too cold is accumulated for 452 // each callee function. Initially this is just the entry count. 453 struct NotInlinedProfileInfo { 454 uint64_t entryCount; 455 }; 456 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo; 457 458 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for 459 // all the function symbols defined or declared in current module. 460 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap; 461 462 // All the Names used in FunctionSamples including outline function 463 // names, inline instance names and call target names. 464 StringSet<> NamesInProfile; 465 466 // For symbol in profile symbol list, whether to regard their profiles 467 // to be accurate. It is mainly decided by existance of profile symbol 468 // list and -profile-accurate-for-symsinlist flag, but it can be 469 // overriden by -profile-sample-accurate or profile-sample-accurate 470 // attribute. 471 bool ProfAccForSymsInList; 472 473 // External inline advisor used to replay inline decision from remarks. 474 std::unique_ptr<ReplayInlineAdvisor> ExternalInlineAdvisor; 475 476 // A pseudo probe helper to correlate the imported sample counts. 477 std::unique_ptr<PseudoProbeManager> ProbeManager; 478 }; 479 480 class SampleProfileLoaderLegacyPass : public ModulePass { 481 public: 482 // Class identification, replacement for typeinfo 483 static char ID; 484 485 SampleProfileLoaderLegacyPass( 486 StringRef Name = SampleProfileFile, 487 ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None) 488 : ModulePass(ID), SampleLoader( 489 Name, SampleProfileRemappingFile, LTOPhase, 490 [&](Function &F) -> AssumptionCache & { 491 return ACT->getAssumptionCache(F); 492 }, 493 [&](Function &F) -> TargetTransformInfo & { 494 return TTIWP->getTTI(F); 495 }, 496 [&](Function &F) -> TargetLibraryInfo & { 497 return TLIWP->getTLI(F); 498 }) { 499 initializeSampleProfileLoaderLegacyPassPass( 500 *PassRegistry::getPassRegistry()); 501 } 502 503 void dump() { SampleLoader.dump(); } 504 505 bool doInitialization(Module &M) override { 506 return SampleLoader.doInitialization(M); 507 } 508 509 StringRef getPassName() const override { return "Sample profile pass"; } 510 bool runOnModule(Module &M) override; 511 512 void getAnalysisUsage(AnalysisUsage &AU) const override { 513 AU.addRequired<AssumptionCacheTracker>(); 514 AU.addRequired<TargetTransformInfoWrapperPass>(); 515 AU.addRequired<TargetLibraryInfoWrapperPass>(); 516 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 517 } 518 519 private: 520 SampleProfileLoader SampleLoader; 521 AssumptionCacheTracker *ACT = nullptr; 522 TargetTransformInfoWrapperPass *TTIWP = nullptr; 523 TargetLibraryInfoWrapperPass *TLIWP = nullptr; 524 }; 525 526 } // end anonymous namespace 527 528 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) { 529 if (FunctionSamples::ProfileIsProbeBased) 530 return getProbeWeight(Inst); 531 532 const DebugLoc &DLoc = Inst.getDebugLoc(); 533 if (!DLoc) 534 return std::error_code(); 535 536 // Ignore all intrinsics, phinodes and branch instructions. 537 // Branch and phinodes instruction usually contains debug info from sources 538 // outside of the residing basic block, thus we ignore them during annotation. 539 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst)) 540 return std::error_code(); 541 542 // For non-CS profile, if a direct call/invoke instruction is inlined in 543 // profile (findCalleeFunctionSamples returns non-empty result), but not 544 // inlined here, it means that the inlined callsite has no sample, thus the 545 // call instruction should have 0 count. 546 // For CS profile, the callsite count of previously inlined callees is 547 // populated with the entry count of the callees. 548 if (!ProfileIsCS) 549 if (const auto *CB = dyn_cast<CallBase>(&Inst)) 550 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB)) 551 return 0; 552 553 return getInstWeightImpl(Inst); 554 } 555 556 // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight 557 // of non-probe instruction. So if all instructions of the BB give error_code, 558 // tell the inference algorithm to infer the BB weight. 559 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) { 560 assert(FunctionSamples::ProfileIsProbeBased && 561 "Profile is not pseudo probe based"); 562 Optional<PseudoProbe> Probe = extractProbe(Inst); 563 // Ignore the non-probe instruction. If none of the instruction in the BB is 564 // probe, we choose to infer the BB's weight. 565 if (!Probe) 566 return std::error_code(); 567 568 const FunctionSamples *FS = findFunctionSamples(Inst); 569 // If none of the instruction has FunctionSample, we choose to return zero 570 // value sample to indicate the BB is cold. This could happen when the 571 // instruction is from inlinee and no profile data is found. 572 // FIXME: This should not be affected by the source drift issue as 1) if the 573 // newly added function is top-level inliner, it won't match the CFG checksum 574 // in the function profile or 2) if it's the inlinee, the inlinee should have 575 // a profile, otherwise it wouldn't be inlined. For non-probe based profile, 576 // we can improve it by adding a switch for profile-sample-block-accurate for 577 // block level counts in the future. 578 if (!FS) 579 return 0; 580 581 // For non-CS profile, If a direct call/invoke instruction is inlined in 582 // profile (findCalleeFunctionSamples returns non-empty result), but not 583 // inlined here, it means that the inlined callsite has no sample, thus the 584 // call instruction should have 0 count. 585 // For CS profile, the callsite count of previously inlined callees is 586 // populated with the entry count of the callees. 587 if (!ProfileIsCS) 588 if (const auto *CB = dyn_cast<CallBase>(&Inst)) 589 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB)) 590 return 0; 591 592 const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0); 593 if (R) { 594 uint64_t Samples = R.get() * Probe->Factor; 595 bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples); 596 if (FirstMark) { 597 ORE->emit([&]() { 598 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst); 599 Remark << "Applied " << ore::NV("NumSamples", Samples); 600 Remark << " samples from profile (ProbeId="; 601 Remark << ore::NV("ProbeId", Probe->Id); 602 Remark << ", Factor="; 603 Remark << ore::NV("Factor", Probe->Factor); 604 Remark << ", OriginalSamples="; 605 Remark << ore::NV("OriginalSamples", R.get()); 606 Remark << ")"; 607 return Remark; 608 }); 609 } 610 LLVM_DEBUG(dbgs() << " " << Probe->Id << ":" << Inst 611 << " - weight: " << R.get() << " - factor: " 612 << format("%0.2f", Probe->Factor) << ")\n"); 613 return Samples; 614 } 615 return R; 616 } 617 618 /// Get the FunctionSamples for a call instruction. 619 /// 620 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined 621 /// instance in which that call instruction is calling to. It contains 622 /// all samples that resides in the inlined instance. We first find the 623 /// inlined instance in which the call instruction is from, then we 624 /// traverse its children to find the callsite with the matching 625 /// location. 626 /// 627 /// \param Inst Call/Invoke instruction to query. 628 /// 629 /// \returns The FunctionSamples pointer to the inlined instance. 630 const FunctionSamples * 631 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const { 632 const DILocation *DIL = Inst.getDebugLoc(); 633 if (!DIL) { 634 return nullptr; 635 } 636 637 StringRef CalleeName; 638 if (Function *Callee = Inst.getCalledFunction()) 639 CalleeName = Callee->getName(); 640 641 if (ProfileIsCS) 642 return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName); 643 644 const FunctionSamples *FS = findFunctionSamples(Inst); 645 if (FS == nullptr) 646 return nullptr; 647 648 return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL), 649 CalleeName, Reader->getRemapper()); 650 } 651 652 /// Returns a vector of FunctionSamples that are the indirect call targets 653 /// of \p Inst. The vector is sorted by the total number of samples. Stores 654 /// the total call count of the indirect call in \p Sum. 655 std::vector<const FunctionSamples *> 656 SampleProfileLoader::findIndirectCallFunctionSamples( 657 const Instruction &Inst, uint64_t &Sum) const { 658 const DILocation *DIL = Inst.getDebugLoc(); 659 std::vector<const FunctionSamples *> R; 660 661 if (!DIL) { 662 return R; 663 } 664 665 auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) { 666 assert(L && R && "Expect non-null FunctionSamples"); 667 if (L->getEntrySamples() != R->getEntrySamples()) 668 return L->getEntrySamples() > R->getEntrySamples(); 669 return FunctionSamples::getGUID(L->getName()) < 670 FunctionSamples::getGUID(R->getName()); 671 }; 672 673 if (ProfileIsCS) { 674 auto CalleeSamples = 675 ContextTracker->getIndirectCalleeContextSamplesFor(DIL); 676 if (CalleeSamples.empty()) 677 return R; 678 679 // For CSSPGO, we only use target context profile's entry count 680 // as that already includes both inlined callee and non-inlined ones.. 681 Sum = 0; 682 for (const auto *const FS : CalleeSamples) { 683 Sum += FS->getEntrySamples(); 684 R.push_back(FS); 685 } 686 llvm::sort(R, FSCompare); 687 return R; 688 } 689 690 const FunctionSamples *FS = findFunctionSamples(Inst); 691 if (FS == nullptr) 692 return R; 693 694 auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL); 695 auto T = FS->findCallTargetMapAt(CallSite); 696 Sum = 0; 697 if (T) 698 for (const auto &T_C : T.get()) 699 Sum += T_C.second; 700 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) { 701 if (M->empty()) 702 return R; 703 for (const auto &NameFS : *M) { 704 Sum += NameFS.second.getEntrySamples(); 705 R.push_back(&NameFS.second); 706 } 707 llvm::sort(R, FSCompare); 708 } 709 return R; 710 } 711 712 const FunctionSamples * 713 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const { 714 if (FunctionSamples::ProfileIsProbeBased) { 715 Optional<PseudoProbe> Probe = extractProbe(Inst); 716 if (!Probe) 717 return nullptr; 718 } 719 720 const DILocation *DIL = Inst.getDebugLoc(); 721 if (!DIL) 722 return Samples; 723 724 auto it = DILocation2SampleMap.try_emplace(DIL,nullptr); 725 if (it.second) { 726 if (ProfileIsCS) 727 it.first->second = ContextTracker->getContextSamplesFor(DIL); 728 else 729 it.first->second = 730 Samples->findFunctionSamples(DIL, Reader->getRemapper()); 731 } 732 return it.first->second; 733 } 734 735 /// Check whether the indirect call promotion history of \p Inst allows 736 /// the promotion for \p Candidate. 737 /// If the profile count for the promotion candidate \p Candidate is 738 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted 739 /// for \p Inst. If we already have at least MaxNumPromotions 740 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we 741 /// cannot promote for \p Inst anymore. 742 static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) { 743 uint32_t NumVals = 0; 744 uint64_t TotalCount = 0; 745 std::unique_ptr<InstrProfValueData[]> ValueData = 746 std::make_unique<InstrProfValueData[]>(MaxNumPromotions); 747 bool Valid = 748 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions, 749 ValueData.get(), NumVals, TotalCount, true); 750 // No valid value profile so no promoted targets have been recorded 751 // before. Ok to do ICP. 752 if (!Valid) 753 return true; 754 755 unsigned NumPromoted = 0; 756 for (uint32_t I = 0; I < NumVals; I++) { 757 if (ValueData[I].Count != NOMORE_ICP_MAGICNUM) 758 continue; 759 760 // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the 761 // metadata, it means the candidate has been promoted for this 762 // indirect call. 763 if (ValueData[I].Value == Function::getGUID(Candidate)) 764 return false; 765 NumPromoted++; 766 // If already have MaxNumPromotions promotion, don't do it anymore. 767 if (NumPromoted == MaxNumPromotions) 768 return false; 769 } 770 return true; 771 } 772 773 /// Update indirect call target profile metadata for \p Inst. 774 /// Usually \p Sum is the sum of counts of all the targets for \p Inst. 775 /// If it is 0, it means updateIDTMetaData is used to mark a 776 /// certain target to be promoted already. If it is not zero, 777 /// we expect to use it to update the total count in the value profile. 778 static void 779 updateIDTMetaData(Instruction &Inst, 780 const SmallVectorImpl<InstrProfValueData> &CallTargets, 781 uint64_t Sum) { 782 uint32_t NumVals = 0; 783 // OldSum is the existing total count in the value profile data. 784 uint64_t OldSum = 0; 785 std::unique_ptr<InstrProfValueData[]> ValueData = 786 std::make_unique<InstrProfValueData[]>(MaxNumPromotions); 787 bool Valid = 788 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions, 789 ValueData.get(), NumVals, OldSum, true); 790 791 DenseMap<uint64_t, uint64_t> ValueCountMap; 792 if (Sum == 0) { 793 assert((CallTargets.size() == 1 && 794 CallTargets[0].Count == NOMORE_ICP_MAGICNUM) && 795 "If sum is 0, assume only one element in CallTargets " 796 "with count being NOMORE_ICP_MAGICNUM"); 797 // Initialize ValueCountMap with existing value profile data. 798 if (Valid) { 799 for (uint32_t I = 0; I < NumVals; I++) 800 ValueCountMap[ValueData[I].Value] = ValueData[I].Count; 801 } 802 auto Pair = 803 ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count); 804 // If the target already exists in value profile, decrease the total 805 // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM. 806 if (!Pair.second) { 807 OldSum -= Pair.first->second; 808 Pair.first->second = NOMORE_ICP_MAGICNUM; 809 } 810 Sum = OldSum; 811 } else { 812 // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM 813 // counts in the value profile. 814 if (Valid) { 815 for (uint32_t I = 0; I < NumVals; I++) { 816 if (ValueData[I].Count == NOMORE_ICP_MAGICNUM) 817 ValueCountMap[ValueData[I].Value] = ValueData[I].Count; 818 } 819 } 820 821 for (const auto &Data : CallTargets) { 822 auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count); 823 if (Pair.second) 824 continue; 825 // The target represented by Data.Value has already been promoted. 826 // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease 827 // Sum by Data.Count. 828 assert(Sum >= Data.Count && "Sum should never be less than Data.Count"); 829 Sum -= Data.Count; 830 } 831 } 832 833 SmallVector<InstrProfValueData, 8> NewCallTargets; 834 for (const auto &ValueCount : ValueCountMap) { 835 NewCallTargets.emplace_back( 836 InstrProfValueData{ValueCount.first, ValueCount.second}); 837 } 838 839 llvm::sort(NewCallTargets, 840 [](const InstrProfValueData &L, const InstrProfValueData &R) { 841 if (L.Count != R.Count) 842 return L.Count > R.Count; 843 return L.Value > R.Value; 844 }); 845 846 uint32_t MaxMDCount = 847 std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions)); 848 annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst, 849 NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount); 850 } 851 852 /// Attempt to promote indirect call and also inline the promoted call. 853 /// 854 /// \param F Caller function. 855 /// \param Candidate ICP and inline candidate. 856 /// \param SumOrigin Original sum of target counts for indirect call before 857 /// promoting given candidate. 858 /// \param Sum Prorated sum of remaining target counts for indirect call 859 /// after promoting given candidate. 860 /// \param InlinedCallSite Output vector for new call sites exposed after 861 /// inlining. 862 bool SampleProfileLoader::tryPromoteAndInlineCandidate( 863 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum, 864 SmallVector<CallBase *, 8> *InlinedCallSite) { 865 auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName(); 866 auto R = SymbolMap.find(CalleeFunctionName); 867 if (R == SymbolMap.end() || !R->getValue()) 868 return false; 869 870 auto &CI = *Candidate.CallInstr; 871 if (!doesHistoryAllowICP(CI, R->getValue()->getName())) 872 return false; 873 874 const char *Reason = "Callee function not available"; 875 // R->getValue() != &F is to prevent promoting a recursive call. 876 // If it is a recursive call, we do not inline it as it could bloat 877 // the code exponentially. There is way to better handle this, e.g. 878 // clone the caller first, and inline the cloned caller if it is 879 // recursive. As llvm does not inline recursive calls, we will 880 // simply ignore it instead of handling it explicitly. 881 if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() && 882 R->getValue()->hasFnAttribute("use-sample-profile") && 883 R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) { 884 // For promoted target, set its value with NOMORE_ICP_MAGICNUM count 885 // in the value profile metadata so the target won't be promoted again. 886 SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{ 887 Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}}; 888 updateIDTMetaData(CI, SortedCallTargets, 0); 889 890 auto *DI = &pgo::promoteIndirectCall( 891 CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE); 892 if (DI) { 893 Sum -= Candidate.CallsiteCount; 894 // Do not prorate the indirect callsite distribution since the original 895 // distribution will be used to scale down non-promoted profile target 896 // counts later. By doing this we lose track of the real callsite count 897 // for the leftover indirect callsite as a trade off for accurate call 898 // target counts. 899 // TODO: Ideally we would have two separate factors, one for call site 900 // counts and one is used to prorate call target counts. 901 // Do not update the promoted direct callsite distribution at this 902 // point since the original distribution combined with the callee profile 903 // will be used to prorate callsites from the callee if inlined. Once not 904 // inlined, the direct callsite distribution should be prorated so that 905 // the it will reflect the real callsite counts. 906 Candidate.CallInstr = DI; 907 if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) { 908 bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite); 909 if (!Inlined) { 910 // Prorate the direct callsite distribution so that it reflects real 911 // callsite counts. 912 setProbeDistributionFactor( 913 *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin); 914 } 915 return Inlined; 916 } 917 } 918 } else { 919 LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to " 920 << Candidate.CalleeSamples->getFuncName() << " because " 921 << Reason << "\n"); 922 } 923 return false; 924 } 925 926 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) { 927 if (!ProfileSizeInline) 928 return false; 929 930 Function *Callee = CallInst.getCalledFunction(); 931 if (Callee == nullptr) 932 return false; 933 934 InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee), 935 GetAC, GetTLI); 936 937 if (Cost.isNever()) 938 return false; 939 940 if (Cost.isAlways()) 941 return true; 942 943 return Cost.getCost() <= SampleColdCallSiteThreshold; 944 } 945 946 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates( 947 const SmallVectorImpl<CallBase *> &Candidates, const Function &F, 948 bool Hot) { 949 for (auto I : Candidates) { 950 Function *CalledFunction = I->getCalledFunction(); 951 if (CalledFunction) { 952 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt", 953 I->getDebugLoc(), I->getParent()) 954 << "previous inlining reattempted for " 955 << (Hot ? "hotness: '" : "size: '") 956 << ore::NV("Callee", CalledFunction) << "' into '" 957 << ore::NV("Caller", &F) << "'"); 958 } 959 } 960 } 961 962 void SampleProfileLoader::findExternalInlineCandidate( 963 const FunctionSamples *Samples, DenseSet<GlobalValue::GUID> &InlinedGUIDs, 964 const StringMap<Function *> &SymbolMap, uint64_t Threshold) { 965 assert(Samples && "expect non-null caller profile"); 966 967 // For AutoFDO profile, retrieve candidate profiles by walking over 968 // the nested inlinee profiles. 969 if (!ProfileIsCS) { 970 Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold); 971 return; 972 } 973 974 ContextTrieNode *Caller = 975 ContextTracker->getContextFor(Samples->getContext()); 976 std::queue<ContextTrieNode *> CalleeList; 977 CalleeList.push(Caller); 978 while (!CalleeList.empty()) { 979 ContextTrieNode *Node = CalleeList.front(); 980 CalleeList.pop(); 981 FunctionSamples *CalleeSample = Node->getFunctionSamples(); 982 // For CSSPGO profile, retrieve candidate profile by walking over the 983 // trie built for context profile. Note that also take call targets 984 // even if callee doesn't have a corresponding context profile. 985 if (!CalleeSample) 986 continue; 987 988 // If pre-inliner decision is used, honor that for importing as well. 989 bool PreInline = 990 UsePreInlinerDecision && 991 CalleeSample->getContext().hasAttribute(ContextShouldBeInlined); 992 if (!PreInline && CalleeSample->getEntrySamples() < Threshold) 993 continue; 994 995 StringRef Name = CalleeSample->getFuncName(); 996 Function *Func = SymbolMap.lookup(Name); 997 // Add to the import list only when it's defined out of module. 998 if (!Func || Func->isDeclaration()) 999 InlinedGUIDs.insert(FunctionSamples::getGUID(CalleeSample->getName())); 1000 1001 // Import hot CallTargets, which may not be available in IR because full 1002 // profile annotation cannot be done until backend compilation in ThinLTO. 1003 for (const auto &BS : CalleeSample->getBodySamples()) 1004 for (const auto &TS : BS.second.getCallTargets()) 1005 if (TS.getValue() > Threshold) { 1006 StringRef CalleeName = CalleeSample->getFuncName(TS.getKey()); 1007 const Function *Callee = SymbolMap.lookup(CalleeName); 1008 if (!Callee || Callee->isDeclaration()) 1009 InlinedGUIDs.insert(FunctionSamples::getGUID(TS.getKey())); 1010 } 1011 1012 // Import hot child context profile associted with callees. Note that this 1013 // may have some overlap with the call target loop above, but doing this 1014 // based child context profile again effectively allow us to use the max of 1015 // entry count and call target count to determine importing. 1016 for (auto &Child : Node->getAllChildContext()) { 1017 ContextTrieNode *CalleeNode = &Child.second; 1018 CalleeList.push(CalleeNode); 1019 } 1020 } 1021 } 1022 1023 /// Iteratively inline hot callsites of a function. 1024 /// 1025 /// Iteratively traverse all callsites of the function \p F, and find if 1026 /// the corresponding inlined instance exists and is hot in profile. If 1027 /// it is hot enough, inline the callsites and adds new callsites of the 1028 /// callee into the caller. If the call is an indirect call, first promote 1029 /// it to direct call. Each indirect call is limited with a single target. 1030 /// 1031 /// \param F function to perform iterative inlining. 1032 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are 1033 /// inlined in the profiled binary. 1034 /// 1035 /// \returns True if there is any inline happened. 1036 bool SampleProfileLoader::inlineHotFunctions( 1037 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) { 1038 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure 1039 // Profile symbol list is ignored when profile-sample-accurate is on. 1040 assert((!ProfAccForSymsInList || 1041 (!ProfileSampleAccurate && 1042 !F.hasFnAttribute("profile-sample-accurate"))) && 1043 "ProfAccForSymsInList should be false when profile-sample-accurate " 1044 "is enabled"); 1045 1046 DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites; 1047 bool Changed = false; 1048 bool LocalChanged = true; 1049 while (LocalChanged) { 1050 LocalChanged = false; 1051 SmallVector<CallBase *, 10> CIS; 1052 for (auto &BB : F) { 1053 bool Hot = false; 1054 SmallVector<CallBase *, 10> AllCandidates; 1055 SmallVector<CallBase *, 10> ColdCandidates; 1056 for (auto &I : BB.getInstList()) { 1057 const FunctionSamples *FS = nullptr; 1058 if (auto *CB = dyn_cast<CallBase>(&I)) { 1059 if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) { 1060 assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) && 1061 "GUIDToFuncNameMap has to be populated"); 1062 AllCandidates.push_back(CB); 1063 if (FS->getEntrySamples() > 0 || ProfileIsCS) 1064 LocalNotInlinedCallSites.try_emplace(CB, FS); 1065 if (callsiteIsHot(FS, PSI, ProfAccForSymsInList)) 1066 Hot = true; 1067 else if (shouldInlineColdCallee(*CB)) 1068 ColdCandidates.push_back(CB); 1069 } 1070 } 1071 } 1072 if (Hot || ExternalInlineAdvisor) { 1073 CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end()); 1074 emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true); 1075 } else { 1076 CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end()); 1077 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false); 1078 } 1079 } 1080 for (CallBase *I : CIS) { 1081 Function *CalledFunction = I->getCalledFunction(); 1082 InlineCandidate Candidate = { 1083 I, 1084 LocalNotInlinedCallSites.count(I) ? LocalNotInlinedCallSites[I] 1085 : nullptr, 1086 0 /* dummy count */, 1.0 /* dummy distribution factor */}; 1087 // Do not inline recursive calls. 1088 if (CalledFunction == &F) 1089 continue; 1090 if (I->isIndirectCall()) { 1091 uint64_t Sum; 1092 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) { 1093 uint64_t SumOrigin = Sum; 1094 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1095 findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap, 1096 PSI->getOrCompHotCountThreshold()); 1097 continue; 1098 } 1099 if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList)) 1100 continue; 1101 1102 Candidate = {I, FS, FS->getEntrySamples(), 1.0}; 1103 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) { 1104 LocalNotInlinedCallSites.erase(I); 1105 LocalChanged = true; 1106 } 1107 } 1108 } else if (CalledFunction && CalledFunction->getSubprogram() && 1109 !CalledFunction->isDeclaration()) { 1110 if (tryInlineCandidate(Candidate)) { 1111 LocalNotInlinedCallSites.erase(I); 1112 LocalChanged = true; 1113 } 1114 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1115 findExternalInlineCandidate(findCalleeFunctionSamples(*I), InlinedGUIDs, 1116 SymbolMap, 1117 PSI->getOrCompHotCountThreshold()); 1118 } 1119 } 1120 Changed |= LocalChanged; 1121 } 1122 1123 // For CS profile, profile for not inlined context will be merged when 1124 // base profile is being trieved 1125 if (ProfileIsCS) 1126 return Changed; 1127 1128 // Accumulate not inlined callsite information into notInlinedSamples 1129 for (const auto &Pair : LocalNotInlinedCallSites) { 1130 CallBase *I = Pair.getFirst(); 1131 Function *Callee = I->getCalledFunction(); 1132 if (!Callee || Callee->isDeclaration()) 1133 continue; 1134 1135 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline", 1136 I->getDebugLoc(), I->getParent()) 1137 << "previous inlining not repeated: '" 1138 << ore::NV("Callee", Callee) << "' into '" 1139 << ore::NV("Caller", &F) << "'"); 1140 1141 ++NumCSNotInlined; 1142 const FunctionSamples *FS = Pair.getSecond(); 1143 if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) { 1144 continue; 1145 } 1146 1147 if (ProfileMergeInlinee) { 1148 // A function call can be replicated by optimizations like callsite 1149 // splitting or jump threading and the replicates end up sharing the 1150 // sample nested callee profile instead of slicing the original inlinee's 1151 // profile. We want to do merge exactly once by filtering out callee 1152 // profiles with a non-zero head sample count. 1153 if (FS->getHeadSamples() == 0) { 1154 // Use entry samples as head samples during the merge, as inlinees 1155 // don't have head samples. 1156 const_cast<FunctionSamples *>(FS)->addHeadSamples( 1157 FS->getEntrySamples()); 1158 1159 // Note that we have to do the merge right after processing function. 1160 // This allows OutlineFS's profile to be used for annotation during 1161 // top-down processing of functions' annotation. 1162 FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee); 1163 OutlineFS->merge(*FS); 1164 } 1165 } else { 1166 auto pair = 1167 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0}); 1168 pair.first->second.entryCount += FS->getEntrySamples(); 1169 } 1170 } 1171 return Changed; 1172 } 1173 1174 bool SampleProfileLoader::tryInlineCandidate( 1175 InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) { 1176 1177 CallBase &CB = *Candidate.CallInstr; 1178 Function *CalledFunction = CB.getCalledFunction(); 1179 assert(CalledFunction && "Expect a callee with definition"); 1180 DebugLoc DLoc = CB.getDebugLoc(); 1181 BasicBlock *BB = CB.getParent(); 1182 1183 InlineCost Cost = shouldInlineCandidate(Candidate); 1184 if (Cost.isNever()) { 1185 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB) 1186 << "incompatible inlining"); 1187 return false; 1188 } 1189 1190 if (!Cost) 1191 return false; 1192 1193 InlineFunctionInfo IFI(nullptr, GetAC); 1194 IFI.UpdateProfile = false; 1195 if (InlineFunction(CB, IFI).isSuccess()) { 1196 // Merge the attributes based on the inlining. 1197 AttributeFuncs::mergeAttributesForInlining(*BB->getParent(), 1198 *CalledFunction); 1199 1200 // The call to InlineFunction erases I, so we can't pass it here. 1201 emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost, 1202 true, CSINLINE_DEBUG); 1203 1204 // Now populate the list of newly exposed call sites. 1205 if (InlinedCallSites) { 1206 InlinedCallSites->clear(); 1207 for (auto &I : IFI.InlinedCallSites) 1208 InlinedCallSites->push_back(I); 1209 } 1210 1211 if (ProfileIsCS) 1212 ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples); 1213 ++NumCSInlined; 1214 1215 // Prorate inlined probes for a duplicated inlining callsite which probably 1216 // has a distribution less than 100%. Samples for an inlinee should be 1217 // distributed among the copies of the original callsite based on each 1218 // callsite's distribution factor for counts accuracy. Note that an inlined 1219 // probe may come with its own distribution factor if it has been duplicated 1220 // in the inlinee body. The two factor are multiplied to reflect the 1221 // aggregation of duplication. 1222 if (Candidate.CallsiteDistribution < 1) { 1223 for (auto &I : IFI.InlinedCallSites) { 1224 if (Optional<PseudoProbe> Probe = extractProbe(*I)) 1225 setProbeDistributionFactor(*I, Probe->Factor * 1226 Candidate.CallsiteDistribution); 1227 } 1228 NumDuplicatedInlinesite++; 1229 } 1230 1231 return true; 1232 } 1233 return false; 1234 } 1235 1236 bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate, 1237 CallBase *CB) { 1238 assert(CB && "Expect non-null call instruction"); 1239 1240 if (isa<IntrinsicInst>(CB)) 1241 return false; 1242 1243 // Find the callee's profile. For indirect call, find hottest target profile. 1244 const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB); 1245 if (!CalleeSamples) 1246 return false; 1247 1248 float Factor = 1.0; 1249 if (Optional<PseudoProbe> Probe = extractProbe(*CB)) 1250 Factor = Probe->Factor; 1251 1252 uint64_t CallsiteCount = 0; 1253 ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent()); 1254 if (Weight) 1255 CallsiteCount = Weight.get(); 1256 if (CalleeSamples) 1257 CallsiteCount = std::max( 1258 CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor)); 1259 1260 *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor}; 1261 return true; 1262 } 1263 1264 InlineCost 1265 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) { 1266 std::unique_ptr<InlineAdvice> Advice = nullptr; 1267 if (ExternalInlineAdvisor) { 1268 Advice = ExternalInlineAdvisor->getAdvice(*Candidate.CallInstr); 1269 if (!Advice->isInliningRecommended()) { 1270 Advice->recordUnattemptedInlining(); 1271 return InlineCost::getNever("not previously inlined"); 1272 } 1273 Advice->recordInlining(); 1274 return InlineCost::getAlways("previously inlined"); 1275 } 1276 1277 // Adjust threshold based on call site hotness, only do this for callsite 1278 // prioritized inliner because otherwise cost-benefit check is done earlier. 1279 int SampleThreshold = SampleColdCallSiteThreshold; 1280 if (CallsitePrioritizedInline) { 1281 if (Candidate.CallsiteCount > PSI->getHotCountThreshold()) 1282 SampleThreshold = SampleHotCallSiteThreshold; 1283 else if (!ProfileSizeInline) 1284 return InlineCost::getNever("cold callsite"); 1285 } 1286 1287 Function *Callee = Candidate.CallInstr->getCalledFunction(); 1288 assert(Callee && "Expect a definition for inline candidate of direct call"); 1289 1290 InlineParams Params = getInlineParams(); 1291 // We will ignore the threshold from inline cost, so always get full cost. 1292 Params.ComputeFullInlineCost = true; 1293 Params.AllowRecursiveCall = AllowRecursiveInline; 1294 // Checks if there is anything in the reachable portion of the callee at 1295 // this callsite that makes this inlining potentially illegal. Need to 1296 // set ComputeFullInlineCost, otherwise getInlineCost may return early 1297 // when cost exceeds threshold without checking all IRs in the callee. 1298 // The acutal cost does not matter because we only checks isNever() to 1299 // see if it is legal to inline the callsite. 1300 InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params, 1301 GetTTI(*Callee), GetAC, GetTLI); 1302 1303 // Honor always inline and never inline from call analyzer 1304 if (Cost.isNever() || Cost.isAlways()) 1305 return Cost; 1306 1307 // With CSSPGO, the preinliner in llvm-profgen can estimate global inline 1308 // decisions based on hotness as well as accurate function byte sizes for 1309 // given context using function/inlinee sizes from previous build. It 1310 // stores the decision in profile, and also adjust/merge context profile 1311 // aiming at better context-sensitive post-inline profile quality, assuming 1312 // all inline decision estimates are going to be honored by compiler. Here 1313 // we replay that inline decision under `sample-profile-use-preinliner`. 1314 // Note that we don't need to handle negative decision from preinliner as 1315 // context profile for not inlined calls are merged by preinliner already. 1316 SampleContext &Context = Candidate.CalleeSamples->getContext(); 1317 if (UsePreInlinerDecision && Context.hasAttribute(ContextShouldBeInlined)) 1318 // Once two node are merged due to promotion, we're losing some context 1319 // so the original context-sensitive preinliner decision should be ignored 1320 // for SyntheticContext. 1321 if (!Context.hasState(SyntheticContext)) 1322 return InlineCost::getAlways("preinliner"); 1323 1324 // For old FDO inliner, we inline the call site as long as cost is not 1325 // "Never". The cost-benefit check is done earlier. 1326 if (!CallsitePrioritizedInline) { 1327 return InlineCost::get(Cost.getCost(), INT_MAX); 1328 } 1329 1330 // Otherwise only use the cost from call analyzer, but overwite threshold with 1331 // Sample PGO threshold. 1332 return InlineCost::get(Cost.getCost(), SampleThreshold); 1333 } 1334 1335 bool SampleProfileLoader::inlineHotFunctionsWithPriority( 1336 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) { 1337 assert(ProfileIsCS && "Prioritiy based inliner only works with CSSPGO now"); 1338 1339 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure 1340 // Profile symbol list is ignored when profile-sample-accurate is on. 1341 assert((!ProfAccForSymsInList || 1342 (!ProfileSampleAccurate && 1343 !F.hasFnAttribute("profile-sample-accurate"))) && 1344 "ProfAccForSymsInList should be false when profile-sample-accurate " 1345 "is enabled"); 1346 1347 // Populating worklist with initial call sites from root inliner, along 1348 // with call site weights. 1349 CandidateQueue CQueue; 1350 InlineCandidate NewCandidate; 1351 for (auto &BB : F) { 1352 for (auto &I : BB.getInstList()) { 1353 auto *CB = dyn_cast<CallBase>(&I); 1354 if (!CB) 1355 continue; 1356 if (getInlineCandidate(&NewCandidate, CB)) 1357 CQueue.push(NewCandidate); 1358 } 1359 } 1360 1361 // Cap the size growth from profile guided inlining. This is needed even 1362 // though cost of each inline candidate already accounts for callee size, 1363 // because with top-down inlining, we can grow inliner size significantly 1364 // with large number of smaller inlinees each pass the cost check. 1365 assert(ProfileInlineLimitMax >= ProfileInlineLimitMin && 1366 "Max inline size limit should not be smaller than min inline size " 1367 "limit."); 1368 unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit; 1369 SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax); 1370 SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin); 1371 if (ExternalInlineAdvisor) 1372 SizeLimit = std::numeric_limits<unsigned>::max(); 1373 1374 // Perform iterative BFS call site prioritized inlining 1375 bool Changed = false; 1376 while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) { 1377 InlineCandidate Candidate = CQueue.top(); 1378 CQueue.pop(); 1379 CallBase *I = Candidate.CallInstr; 1380 Function *CalledFunction = I->getCalledFunction(); 1381 1382 if (CalledFunction == &F) 1383 continue; 1384 if (I->isIndirectCall()) { 1385 uint64_t Sum = 0; 1386 auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum); 1387 uint64_t SumOrigin = Sum; 1388 Sum *= Candidate.CallsiteDistribution; 1389 unsigned ICPCount = 0; 1390 for (const auto *FS : CalleeSamples) { 1391 // TODO: Consider disable pre-lTO ICP for MonoLTO as well 1392 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1393 findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap, 1394 PSI->getOrCompHotCountThreshold()); 1395 continue; 1396 } 1397 uint64_t EntryCountDistributed = 1398 FS->getEntrySamples() * Candidate.CallsiteDistribution; 1399 // In addition to regular inline cost check, we also need to make sure 1400 // ICP isn't introducing excessive speculative checks even if individual 1401 // target looks beneficial to promote and inline. That means we should 1402 // only do ICP when there's a small number dominant targets. 1403 if (ICPCount >= ProfileICPRelativeHotnessSkip && 1404 EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness) 1405 break; 1406 // TODO: Fix CallAnalyzer to handle all indirect calls. 1407 // For indirect call, we don't run CallAnalyzer to get InlineCost 1408 // before actual inlining. This is because we could see two different 1409 // types from the same definition, which makes CallAnalyzer choke as 1410 // it's expecting matching parameter type on both caller and callee 1411 // side. See example from PR18962 for the triggering cases (the bug was 1412 // fixed, but we generate different types). 1413 if (!PSI->isHotCount(EntryCountDistributed)) 1414 break; 1415 SmallVector<CallBase *, 8> InlinedCallSites; 1416 // Attach function profile for promoted indirect callee, and update 1417 // call site count for the promoted inline candidate too. 1418 Candidate = {I, FS, EntryCountDistributed, 1419 Candidate.CallsiteDistribution}; 1420 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum, 1421 &InlinedCallSites)) { 1422 for (auto *CB : InlinedCallSites) { 1423 if (getInlineCandidate(&NewCandidate, CB)) 1424 CQueue.emplace(NewCandidate); 1425 } 1426 ICPCount++; 1427 Changed = true; 1428 } 1429 } 1430 } else if (CalledFunction && CalledFunction->getSubprogram() && 1431 !CalledFunction->isDeclaration()) { 1432 SmallVector<CallBase *, 8> InlinedCallSites; 1433 if (tryInlineCandidate(Candidate, &InlinedCallSites)) { 1434 for (auto *CB : InlinedCallSites) { 1435 if (getInlineCandidate(&NewCandidate, CB)) 1436 CQueue.emplace(NewCandidate); 1437 } 1438 Changed = true; 1439 } 1440 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1441 findExternalInlineCandidate(Candidate.CalleeSamples, InlinedGUIDs, 1442 SymbolMap, PSI->getOrCompHotCountThreshold()); 1443 } 1444 } 1445 1446 if (!CQueue.empty()) { 1447 if (SizeLimit == (unsigned)ProfileInlineLimitMax) 1448 ++NumCSInlinedHitMaxLimit; 1449 else if (SizeLimit == (unsigned)ProfileInlineLimitMin) 1450 ++NumCSInlinedHitMinLimit; 1451 else 1452 ++NumCSInlinedHitGrowthLimit; 1453 } 1454 1455 return Changed; 1456 } 1457 1458 /// Returns the sorted CallTargetMap \p M by count in descending order. 1459 static SmallVector<InstrProfValueData, 2> 1460 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) { 1461 SmallVector<InstrProfValueData, 2> R; 1462 for (const auto &I : SampleRecord::SortCallTargets(M)) { 1463 R.emplace_back( 1464 InstrProfValueData{FunctionSamples::getGUID(I.first), I.second}); 1465 } 1466 return R; 1467 } 1468 1469 // Generate MD_prof metadata for every branch instruction using the 1470 // edge weights computed during propagation. 1471 void SampleProfileLoader::generateMDProfMetadata(Function &F) { 1472 // Generate MD_prof metadata for every branch instruction using the 1473 // edge weights computed during propagation. 1474 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); 1475 LLVMContext &Ctx = F.getContext(); 1476 MDBuilder MDB(Ctx); 1477 for (auto &BI : F) { 1478 BasicBlock *BB = &BI; 1479 1480 if (BlockWeights[BB]) { 1481 for (auto &I : BB->getInstList()) { 1482 if (!isa<CallInst>(I) && !isa<InvokeInst>(I)) 1483 continue; 1484 if (!cast<CallBase>(I).getCalledFunction()) { 1485 const DebugLoc &DLoc = I.getDebugLoc(); 1486 if (!DLoc) 1487 continue; 1488 const DILocation *DIL = DLoc; 1489 const FunctionSamples *FS = findFunctionSamples(I); 1490 if (!FS) 1491 continue; 1492 auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL); 1493 auto T = FS->findCallTargetMapAt(CallSite); 1494 if (!T || T.get().empty()) 1495 continue; 1496 if (FunctionSamples::ProfileIsProbeBased) { 1497 // Prorate the callsite counts based on the pre-ICP distribution 1498 // factor to reflect what is already done to the callsite before 1499 // ICP, such as calliste cloning. 1500 if (Optional<PseudoProbe> Probe = extractProbe(I)) { 1501 if (Probe->Factor < 1) 1502 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor); 1503 } 1504 } 1505 SmallVector<InstrProfValueData, 2> SortedCallTargets = 1506 GetSortedValueDataFromCallTargets(T.get()); 1507 uint64_t Sum = 0; 1508 for (const auto &C : T.get()) 1509 Sum += C.second; 1510 // With CSSPGO all indirect call targets are counted torwards the 1511 // original indirect call site in the profile, including both 1512 // inlined and non-inlined targets. 1513 if (!FunctionSamples::ProfileIsCS) { 1514 if (const FunctionSamplesMap *M = 1515 FS->findFunctionSamplesMapAt(CallSite)) { 1516 for (const auto &NameFS : *M) 1517 Sum += NameFS.second.getEntrySamples(); 1518 } 1519 } 1520 if (Sum) 1521 updateIDTMetaData(I, SortedCallTargets, Sum); 1522 else if (OverwriteExistingWeights) 1523 I.setMetadata(LLVMContext::MD_prof, nullptr); 1524 } else if (!isa<IntrinsicInst>(&I)) { 1525 I.setMetadata(LLVMContext::MD_prof, 1526 MDB.createBranchWeights( 1527 {static_cast<uint32_t>(BlockWeights[BB])})); 1528 } 1529 } 1530 } else if (OverwriteExistingWeights) { 1531 // Set profile metadata (possibly annotated by LTO prelink) to zero or 1532 // clear it for cold code. 1533 for (auto &I : BB->getInstList()) { 1534 if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 1535 if (cast<CallBase>(I).isIndirectCall()) 1536 I.setMetadata(LLVMContext::MD_prof, nullptr); 1537 else 1538 I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(0)); 1539 } 1540 } 1541 } 1542 1543 Instruction *TI = BB->getTerminator(); 1544 if (TI->getNumSuccessors() == 1) 1545 continue; 1546 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) && 1547 !isa<IndirectBrInst>(TI)) 1548 continue; 1549 1550 DebugLoc BranchLoc = TI->getDebugLoc(); 1551 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line " 1552 << ((BranchLoc) ? Twine(BranchLoc.getLine()) 1553 : Twine("<UNKNOWN LOCATION>")) 1554 << ".\n"); 1555 SmallVector<uint32_t, 4> Weights; 1556 uint32_t MaxWeight = 0; 1557 Instruction *MaxDestInst; 1558 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { 1559 BasicBlock *Succ = TI->getSuccessor(I); 1560 Edge E = std::make_pair(BB, Succ); 1561 uint64_t Weight = EdgeWeights[E]; 1562 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); 1563 // Use uint32_t saturated arithmetic to adjust the incoming weights, 1564 // if needed. Sample counts in profiles are 64-bit unsigned values, 1565 // but internally branch weights are expressed as 32-bit values. 1566 if (Weight > std::numeric_limits<uint32_t>::max()) { 1567 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)"); 1568 Weight = std::numeric_limits<uint32_t>::max(); 1569 } 1570 // Weight is added by one to avoid propagation errors introduced by 1571 // 0 weights. 1572 Weights.push_back(static_cast<uint32_t>(Weight + 1)); 1573 if (Weight != 0) { 1574 if (Weight > MaxWeight) { 1575 MaxWeight = Weight; 1576 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime(); 1577 } 1578 } 1579 } 1580 1581 uint64_t TempWeight; 1582 // Only set weights if there is at least one non-zero weight. 1583 // In any other case, let the analyzer set weights. 1584 // Do not set weights if the weights are present unless under 1585 // OverwriteExistingWeights. In ThinLTO, the profile annotation is done 1586 // twice. If the first annotation already set the weights, the second pass 1587 // does not need to set it. With OverwriteExistingWeights, Blocks with zero 1588 // weight should have their existing metadata (possibly annotated by LTO 1589 // prelink) cleared. 1590 if (MaxWeight > 0 && 1591 (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) { 1592 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); 1593 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); 1594 ORE->emit([&]() { 1595 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst) 1596 << "most popular destination for conditional branches at " 1597 << ore::NV("CondBranchesLoc", BranchLoc); 1598 }); 1599 } else { 1600 if (OverwriteExistingWeights) { 1601 TI->setMetadata(LLVMContext::MD_prof, nullptr); 1602 LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n"); 1603 } else { 1604 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); 1605 } 1606 } 1607 } 1608 } 1609 1610 /// Once all the branch weights are computed, we emit the MD_prof 1611 /// metadata on BB using the computed values for each of its branches. 1612 /// 1613 /// \param F The function to query. 1614 /// 1615 /// \returns true if \p F was modified. Returns false, otherwise. 1616 bool SampleProfileLoader::emitAnnotations(Function &F) { 1617 bool Changed = false; 1618 1619 if (FunctionSamples::ProfileIsProbeBased) { 1620 if (!ProbeManager->profileIsValid(F, *Samples)) { 1621 LLVM_DEBUG( 1622 dbgs() << "Profile is invalid due to CFG mismatch for Function " 1623 << F.getName()); 1624 ++NumMismatchedProfile; 1625 return false; 1626 } 1627 ++NumMatchedProfile; 1628 } else { 1629 if (getFunctionLoc(F) == 0) 1630 return false; 1631 1632 LLVM_DEBUG(dbgs() << "Line number for the first instruction in " 1633 << F.getName() << ": " << getFunctionLoc(F) << "\n"); 1634 } 1635 1636 DenseSet<GlobalValue::GUID> InlinedGUIDs; 1637 if (ProfileIsCS && CallsitePrioritizedInline) 1638 Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs); 1639 else 1640 Changed |= inlineHotFunctions(F, InlinedGUIDs); 1641 1642 Changed |= computeAndPropagateWeights(F, InlinedGUIDs); 1643 1644 if (Changed) 1645 generateMDProfMetadata(F); 1646 1647 emitCoverageRemarks(F); 1648 return Changed; 1649 } 1650 1651 char SampleProfileLoaderLegacyPass::ID = 0; 1652 1653 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", 1654 "Sample Profile loader", false, false) 1655 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1656 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1657 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1658 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 1659 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile", 1660 "Sample Profile loader", false, false) 1661 1662 std::unique_ptr<ProfiledCallGraph> 1663 SampleProfileLoader::buildProfiledCallGraph(CallGraph &CG) { 1664 std::unique_ptr<ProfiledCallGraph> ProfiledCG; 1665 if (ProfileIsCS) 1666 ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker); 1667 else 1668 ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles()); 1669 1670 // Add all functions into the profiled call graph even if they are not in 1671 // the profile. This makes sure functions missing from the profile still 1672 // gets a chance to be processed. 1673 for (auto &Node : CG) { 1674 const auto *F = Node.first; 1675 if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile")) 1676 continue; 1677 ProfiledCG->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F)); 1678 } 1679 1680 return ProfiledCG; 1681 } 1682 1683 std::vector<Function *> 1684 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) { 1685 std::vector<Function *> FunctionOrderList; 1686 FunctionOrderList.reserve(M.size()); 1687 1688 if (!ProfileTopDownLoad && UseProfiledCallGraph) 1689 errs() << "WARNING: -use-profiled-call-graph ignored, should be used " 1690 "together with -sample-profile-top-down-load.\n"; 1691 1692 if (!ProfileTopDownLoad || CG == nullptr) { 1693 if (ProfileMergeInlinee) { 1694 // Disable ProfileMergeInlinee if profile is not loaded in top down order, 1695 // because the profile for a function may be used for the profile 1696 // annotation of its outline copy before the profile merging of its 1697 // non-inlined inline instances, and that is not the way how 1698 // ProfileMergeInlinee is supposed to work. 1699 ProfileMergeInlinee = false; 1700 } 1701 1702 for (Function &F : M) 1703 if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile")) 1704 FunctionOrderList.push_back(&F); 1705 return FunctionOrderList; 1706 } 1707 1708 assert(&CG->getModule() == &M); 1709 1710 if (UseProfiledCallGraph || 1711 (ProfileIsCS && !UseProfiledCallGraph.getNumOccurrences())) { 1712 // Use profiled call edges to augment the top-down order. There are cases 1713 // that the top-down order computed based on the static call graph doesn't 1714 // reflect real execution order. For example 1715 // 1716 // 1. Incomplete static call graph due to unknown indirect call targets. 1717 // Adjusting the order by considering indirect call edges from the 1718 // profile can enable the inlining of indirect call targets by allowing 1719 // the caller processed before them. 1720 // 2. Mutual call edges in an SCC. The static processing order computed for 1721 // an SCC may not reflect the call contexts in the context-sensitive 1722 // profile, thus may cause potential inlining to be overlooked. The 1723 // function order in one SCC is being adjusted to a top-down order based 1724 // on the profile to favor more inlining. This is only a problem with CS 1725 // profile. 1726 // 3. Transitive indirect call edges due to inlining. When a callee function 1727 // (say B) is inlined into into a caller function (say A) in LTO prelink, 1728 // every call edge originated from the callee B will be transferred to 1729 // the caller A. If any transferred edge (say A->C) is indirect, the 1730 // original profiled indirect edge B->C, even if considered, would not 1731 // enforce a top-down order from the caller A to the potential indirect 1732 // call target C in LTO postlink since the inlined callee B is gone from 1733 // the static call graph. 1734 // 4. #3 can happen even for direct call targets, due to functions defined 1735 // in header files. A header function (say A), when included into source 1736 // files, is defined multiple times but only one definition survives due 1737 // to ODR. Therefore, the LTO prelink inlining done on those dropped 1738 // definitions can be useless based on a local file scope. More 1739 // importantly, the inlinee (say B), once fully inlined to a 1740 // to-be-dropped A, will have no profile to consume when its outlined 1741 // version is compiled. This can lead to a profile-less prelink 1742 // compilation for the outlined version of B which may be called from 1743 // external modules. while this isn't easy to fix, we rely on the 1744 // postlink AutoFDO pipeline to optimize B. Since the survived copy of 1745 // the A can be inlined in its local scope in prelink, it may not exist 1746 // in the merged IR in postlink, and we'll need the profiled call edges 1747 // to enforce a top-down order for the rest of the functions. 1748 // 1749 // Considering those cases, a profiled call graph completely independent of 1750 // the static call graph is constructed based on profile data, where 1751 // function objects are not even needed to handle case #3 and case 4. 1752 // 1753 // Note that static callgraph edges are completely ignored since they 1754 // can be conflicting with profiled edges for cyclic SCCs and may result in 1755 // an SCC order incompatible with profile-defined one. Using strictly 1756 // profile order ensures a maximum inlining experience. On the other hand, 1757 // static call edges are not so important when they don't correspond to a 1758 // context in the profile. 1759 1760 std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(*CG); 1761 scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get()); 1762 while (!CGI.isAtEnd()) { 1763 for (ProfiledCallGraphNode *Node : *CGI) { 1764 Function *F = SymbolMap.lookup(Node->Name); 1765 if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile")) 1766 FunctionOrderList.push_back(F); 1767 } 1768 ++CGI; 1769 } 1770 } else { 1771 scc_iterator<CallGraph *> CGI = scc_begin(CG); 1772 while (!CGI.isAtEnd()) { 1773 for (CallGraphNode *Node : *CGI) { 1774 auto *F = Node->getFunction(); 1775 if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile")) 1776 FunctionOrderList.push_back(F); 1777 } 1778 ++CGI; 1779 } 1780 } 1781 1782 LLVM_DEBUG({ 1783 dbgs() << "Function processing order:\n"; 1784 for (auto F : reverse(FunctionOrderList)) { 1785 dbgs() << F->getName() << "\n"; 1786 } 1787 }); 1788 1789 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end()); 1790 return FunctionOrderList; 1791 } 1792 1793 bool SampleProfileLoader::doInitialization(Module &M, 1794 FunctionAnalysisManager *FAM) { 1795 auto &Ctx = M.getContext(); 1796 1797 auto ReaderOrErr = SampleProfileReader::create( 1798 Filename, Ctx, FSDiscriminatorPass::Base, RemappingFilename); 1799 if (std::error_code EC = ReaderOrErr.getError()) { 1800 std::string Msg = "Could not open profile: " + EC.message(); 1801 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1802 return false; 1803 } 1804 Reader = std::move(ReaderOrErr.get()); 1805 Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink); 1806 // set module before reading the profile so reader may be able to only 1807 // read the function profiles which are used by the current module. 1808 Reader->setModule(&M); 1809 if (std::error_code EC = Reader->read()) { 1810 std::string Msg = "profile reading failed: " + EC.message(); 1811 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1812 return false; 1813 } 1814 1815 PSL = Reader->getProfileSymbolList(); 1816 1817 // While profile-sample-accurate is on, ignore symbol list. 1818 ProfAccForSymsInList = 1819 ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate; 1820 if (ProfAccForSymsInList) { 1821 NamesInProfile.clear(); 1822 if (auto NameTable = Reader->getNameTable()) 1823 NamesInProfile.insert(NameTable->begin(), NameTable->end()); 1824 CoverageTracker.setProfAccForSymsInList(true); 1825 } 1826 1827 if (FAM && !ProfileInlineReplayFile.empty()) { 1828 ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>( 1829 M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile, 1830 /*EmitRemarks=*/false); 1831 if (!ExternalInlineAdvisor->areReplayRemarksLoaded()) 1832 ExternalInlineAdvisor.reset(); 1833 } 1834 1835 // Apply tweaks if context-sensitive profile is available. 1836 if (Reader->profileIsCS()) { 1837 ProfileIsCS = true; 1838 FunctionSamples::ProfileIsCS = true; 1839 1840 // Enable priority-base inliner and size inline by default for CSSPGO. 1841 if (!ProfileSizeInline.getNumOccurrences()) 1842 ProfileSizeInline = true; 1843 if (!CallsitePrioritizedInline.getNumOccurrences()) 1844 CallsitePrioritizedInline = true; 1845 1846 // For CSSPGO, use preinliner decision by default when available. 1847 if (!UsePreInlinerDecision.getNumOccurrences()) 1848 UsePreInlinerDecision = true; 1849 1850 // For CSSPGO, we also allow recursive inline to best use context profile. 1851 if (!AllowRecursiveInline.getNumOccurrences()) 1852 AllowRecursiveInline = true; 1853 1854 // Enable iterative-BFI by default for CSSPGO. 1855 if (!UseIterativeBFIInference.getNumOccurrences()) 1856 UseIterativeBFIInference = true; 1857 1858 // Tracker for profiles under different context 1859 ContextTracker = std::make_unique<SampleContextTracker>( 1860 Reader->getProfiles(), &GUIDToFuncNameMap); 1861 } 1862 1863 // Load pseudo probe descriptors for probe-based function samples. 1864 if (Reader->profileIsProbeBased()) { 1865 ProbeManager = std::make_unique<PseudoProbeManager>(M); 1866 if (!ProbeManager->moduleIsProbed(M)) { 1867 const char *Msg = 1868 "Pseudo-probe-based profile requires SampleProfileProbePass"; 1869 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1870 return false; 1871 } 1872 } 1873 1874 return true; 1875 } 1876 1877 ModulePass *llvm::createSampleProfileLoaderPass() { 1878 return new SampleProfileLoaderLegacyPass(); 1879 } 1880 1881 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { 1882 return new SampleProfileLoaderLegacyPass(Name); 1883 } 1884 1885 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM, 1886 ProfileSummaryInfo *_PSI, CallGraph *CG) { 1887 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap); 1888 1889 PSI = _PSI; 1890 if (M.getProfileSummary(/* IsCS */ false) == nullptr) { 1891 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()), 1892 ProfileSummary::PSK_Sample); 1893 PSI->refresh(); 1894 } 1895 // Compute the total number of samples collected in this profile. 1896 for (const auto &I : Reader->getProfiles()) 1897 TotalCollectedSamples += I.second.getTotalSamples(); 1898 1899 auto Remapper = Reader->getRemapper(); 1900 // Populate the symbol map. 1901 for (const auto &N_F : M.getValueSymbolTable()) { 1902 StringRef OrigName = N_F.getKey(); 1903 Function *F = dyn_cast<Function>(N_F.getValue()); 1904 if (F == nullptr || OrigName.empty()) 1905 continue; 1906 SymbolMap[OrigName] = F; 1907 StringRef NewName = FunctionSamples::getCanonicalFnName(*F); 1908 if (OrigName != NewName && !NewName.empty()) { 1909 auto r = SymbolMap.insert(std::make_pair(NewName, F)); 1910 // Failiing to insert means there is already an entry in SymbolMap, 1911 // thus there are multiple functions that are mapped to the same 1912 // stripped name. In this case of name conflicting, set the value 1913 // to nullptr to avoid confusion. 1914 if (!r.second) 1915 r.first->second = nullptr; 1916 OrigName = NewName; 1917 } 1918 // Insert the remapped names into SymbolMap. 1919 if (Remapper) { 1920 if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) { 1921 if (*MapName != OrigName && !MapName->empty()) 1922 SymbolMap.insert(std::make_pair(*MapName, F)); 1923 } 1924 } 1925 } 1926 assert(SymbolMap.count(StringRef()) == 0 && 1927 "No empty StringRef should be added in SymbolMap"); 1928 1929 bool retval = false; 1930 for (auto F : buildFunctionOrder(M, CG)) { 1931 assert(!F->isDeclaration()); 1932 clearFunctionData(); 1933 retval |= runOnFunction(*F, AM); 1934 } 1935 1936 // Account for cold calls not inlined.... 1937 if (!ProfileIsCS) 1938 for (const std::pair<Function *, NotInlinedProfileInfo> &pair : 1939 notInlinedCallInfo) 1940 updateProfileCallee(pair.first, pair.second.entryCount); 1941 1942 return retval; 1943 } 1944 1945 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) { 1946 ACT = &getAnalysis<AssumptionCacheTracker>(); 1947 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>(); 1948 TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>(); 1949 ProfileSummaryInfo *PSI = 1950 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 1951 return SampleLoader.runOnModule(M, nullptr, PSI, nullptr); 1952 } 1953 1954 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) { 1955 LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n"); 1956 DILocation2SampleMap.clear(); 1957 // By default the entry count is initialized to -1, which will be treated 1958 // conservatively by getEntryCount as the same as unknown (None). This is 1959 // to avoid newly added code to be treated as cold. If we have samples 1960 // this will be overwritten in emitAnnotations. 1961 uint64_t initialEntryCount = -1; 1962 1963 ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL; 1964 if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) { 1965 // initialize all the function entry counts to 0. It means all the 1966 // functions without profile will be regarded as cold. 1967 initialEntryCount = 0; 1968 // profile-sample-accurate is a user assertion which has a higher precedence 1969 // than symbol list. When profile-sample-accurate is on, ignore symbol list. 1970 ProfAccForSymsInList = false; 1971 } 1972 CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList); 1973 1974 // PSL -- profile symbol list include all the symbols in sampled binary. 1975 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat 1976 // old functions without samples being cold, without having to worry 1977 // about new and hot functions being mistakenly treated as cold. 1978 if (ProfAccForSymsInList) { 1979 // Initialize the entry count to 0 for functions in the list. 1980 if (PSL->contains(F.getName())) 1981 initialEntryCount = 0; 1982 1983 // Function in the symbol list but without sample will be regarded as 1984 // cold. To minimize the potential negative performance impact it could 1985 // have, we want to be a little conservative here saying if a function 1986 // shows up in the profile, no matter as outline function, inline instance 1987 // or call targets, treat the function as not being cold. This will handle 1988 // the cases such as most callsites of a function are inlined in sampled 1989 // binary but not inlined in current build (because of source code drift, 1990 // imprecise debug information, or the callsites are all cold individually 1991 // but not cold accumulatively...), so the outline function showing up as 1992 // cold in sampled binary will actually not be cold after current build. 1993 StringRef CanonName = FunctionSamples::getCanonicalFnName(F); 1994 if (NamesInProfile.count(CanonName)) 1995 initialEntryCount = -1; 1996 } 1997 1998 // Initialize entry count when the function has no existing entry 1999 // count value. 2000 if (!F.getEntryCount().hasValue()) 2001 F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real)); 2002 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE; 2003 if (AM) { 2004 auto &FAM = 2005 AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent()) 2006 .getManager(); 2007 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 2008 } else { 2009 OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F); 2010 ORE = OwnedORE.get(); 2011 } 2012 2013 if (ProfileIsCS) 2014 Samples = ContextTracker->getBaseSamplesFor(F); 2015 else 2016 Samples = Reader->getSamplesFor(F); 2017 2018 if (Samples && !Samples->empty()) 2019 return emitAnnotations(F); 2020 return false; 2021 } 2022 2023 PreservedAnalyses SampleProfileLoaderPass::run(Module &M, 2024 ModuleAnalysisManager &AM) { 2025 FunctionAnalysisManager &FAM = 2026 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2027 2028 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 2029 return FAM.getResult<AssumptionAnalysis>(F); 2030 }; 2031 auto GetTTI = [&](Function &F) -> TargetTransformInfo & { 2032 return FAM.getResult<TargetIRAnalysis>(F); 2033 }; 2034 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & { 2035 return FAM.getResult<TargetLibraryAnalysis>(F); 2036 }; 2037 2038 SampleProfileLoader SampleLoader( 2039 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName, 2040 ProfileRemappingFileName.empty() ? SampleProfileRemappingFile 2041 : ProfileRemappingFileName, 2042 LTOPhase, GetAssumptionCache, GetTTI, GetTLI); 2043 2044 if (!SampleLoader.doInitialization(M, &FAM)) 2045 return PreservedAnalyses::all(); 2046 2047 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M); 2048 CallGraph &CG = AM.getResult<CallGraphAnalysis>(M); 2049 if (!SampleLoader.runOnModule(M, &AM, PSI, &CG)) 2050 return PreservedAnalyses::all(); 2051 2052 return PreservedAnalyses::none(); 2053 } 2054