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/SCCIterator.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallSet.h" 32 #include "llvm/ADT/SmallVector.h" 33 #include "llvm/ADT/Statistic.h" 34 #include "llvm/ADT/StringMap.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/Twine.h" 37 #include "llvm/Analysis/AssumptionCache.h" 38 #include "llvm/Analysis/CallGraph.h" 39 #include "llvm/Analysis/CallGraphSCCPass.h" 40 #include "llvm/Analysis/InlineCost.h" 41 #include "llvm/Analysis/LoopInfo.h" 42 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 43 #include "llvm/Analysis/PostDominators.h" 44 #include "llvm/Analysis/ProfileSummaryInfo.h" 45 #include "llvm/Analysis/TargetLibraryInfo.h" 46 #include "llvm/Analysis/TargetTransformInfo.h" 47 #include "llvm/IR/BasicBlock.h" 48 #include "llvm/IR/CFG.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DiagnosticInfo.h" 52 #include "llvm/IR/Dominators.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/InstrTypes.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/IR/LLVMContext.h" 60 #include "llvm/IR/MDBuilder.h" 61 #include "llvm/IR/Module.h" 62 #include "llvm/IR/PassManager.h" 63 #include "llvm/IR/ValueSymbolTable.h" 64 #include "llvm/InitializePasses.h" 65 #include "llvm/Pass.h" 66 #include "llvm/ProfileData/InstrProf.h" 67 #include "llvm/ProfileData/SampleProf.h" 68 #include "llvm/ProfileData/SampleProfReader.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Debug.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/ErrorOr.h" 74 #include "llvm/Support/GenericDomTree.h" 75 #include "llvm/Support/raw_ostream.h" 76 #include "llvm/Transforms/IPO.h" 77 #include "llvm/Transforms/Instrumentation.h" 78 #include "llvm/Transforms/Utils/CallPromotionUtils.h" 79 #include "llvm/Transforms/Utils/Cloning.h" 80 #include "llvm/Transforms/Utils/MisExpect.h" 81 #include <algorithm> 82 #include <cassert> 83 #include <cstdint> 84 #include <functional> 85 #include <limits> 86 #include <map> 87 #include <memory> 88 #include <queue> 89 #include <string> 90 #include <system_error> 91 #include <utility> 92 #include <vector> 93 94 using namespace llvm; 95 using namespace sampleprof; 96 using ProfileCount = Function::ProfileCount; 97 #define DEBUG_TYPE "sample-profile" 98 #define CSINLINE_DEBUG DEBUG_TYPE "-inline" 99 100 STATISTIC(NumCSInlined, 101 "Number of functions inlined with context sensitive profile"); 102 STATISTIC(NumCSNotInlined, 103 "Number of functions not inlined with context sensitive profile"); 104 105 // Command line option to specify the file to read samples from. This is 106 // mainly used for debugging. 107 static cl::opt<std::string> SampleProfileFile( 108 "sample-profile-file", cl::init(""), cl::value_desc("filename"), 109 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); 110 111 // The named file contains a set of transformations that may have been applied 112 // to the symbol names between the program from which the sample data was 113 // collected and the current program's symbols. 114 static cl::opt<std::string> SampleProfileRemappingFile( 115 "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"), 116 cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden); 117 118 static cl::opt<unsigned> SampleProfileMaxPropagateIterations( 119 "sample-profile-max-propagate-iterations", cl::init(100), 120 cl::desc("Maximum number of iterations to go through when propagating " 121 "sample block/edge weights through the CFG.")); 122 123 static cl::opt<unsigned> SampleProfileRecordCoverage( 124 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"), 125 cl::desc("Emit a warning if less than N% of records in the input profile " 126 "are matched to the IR.")); 127 128 static cl::opt<unsigned> SampleProfileSampleCoverage( 129 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"), 130 cl::desc("Emit a warning if less than N% of samples in the input profile " 131 "are matched to the IR.")); 132 133 static cl::opt<bool> NoWarnSampleUnused( 134 "no-warn-sample-unused", cl::init(false), cl::Hidden, 135 cl::desc("Use this option to turn off/on warnings about function with " 136 "samples but without debug information to use those samples. ")); 137 138 static cl::opt<bool> ProfileSampleAccurate( 139 "profile-sample-accurate", cl::Hidden, cl::init(false), 140 cl::desc("If the sample profile is accurate, we will mark all un-sampled " 141 "callsite and function as having 0 samples. Otherwise, treat " 142 "un-sampled callsites and functions conservatively as unknown. ")); 143 144 static cl::opt<bool> ProfileAccurateForSymsInList( 145 "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore, 146 cl::init(true), 147 cl::desc("For symbols in profile symbol list, regard their profiles to " 148 "be accurate. It may be overriden by profile-sample-accurate. ")); 149 150 static cl::opt<bool> ProfileMergeInlinee( 151 "sample-profile-merge-inlinee", cl::Hidden, cl::init(false), 152 cl::desc("Merge past inlinee's profile to outline version if sample " 153 "profile loader decided not to inline a call site.")); 154 155 static cl::opt<bool> ProfileTopDownLoad( 156 "sample-profile-top-down-load", cl::Hidden, cl::init(false), 157 cl::desc("Do profile annotation and inlining for functions in top-down " 158 "order of call graph during sample profile loading.")); 159 160 static cl::opt<bool> ProfileSizeInline( 161 "sample-profile-inline-size", cl::Hidden, cl::init(false), 162 cl::desc("Inline cold call sites in profile loader if it's beneficial " 163 "for code size.")); 164 165 static cl::opt<int> SampleColdCallSiteThreshold( 166 "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45), 167 cl::desc("Threshold for inlining cold callsites")); 168 169 namespace { 170 171 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>; 172 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>; 173 using Edge = std::pair<const BasicBlock *, const BasicBlock *>; 174 using EdgeWeightMap = DenseMap<Edge, uint64_t>; 175 using BlockEdgeMap = 176 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>; 177 178 class SampleProfileLoader; 179 180 class SampleCoverageTracker { 181 public: 182 SampleCoverageTracker(SampleProfileLoader &SPL) : SPLoader(SPL){}; 183 184 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset, 185 uint32_t Discriminator, uint64_t Samples); 186 unsigned computeCoverage(unsigned Used, unsigned Total) const; 187 unsigned countUsedRecords(const FunctionSamples *FS, 188 ProfileSummaryInfo *PSI) const; 189 unsigned countBodyRecords(const FunctionSamples *FS, 190 ProfileSummaryInfo *PSI) const; 191 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; } 192 uint64_t countBodySamples(const FunctionSamples *FS, 193 ProfileSummaryInfo *PSI) const; 194 195 void clear() { 196 SampleCoverage.clear(); 197 TotalUsedSamples = 0; 198 } 199 200 private: 201 using BodySampleCoverageMap = std::map<LineLocation, unsigned>; 202 using FunctionSamplesCoverageMap = 203 DenseMap<const FunctionSamples *, BodySampleCoverageMap>; 204 205 /// Coverage map for sampling records. 206 /// 207 /// This map keeps a record of sampling records that have been matched to 208 /// an IR instruction. This is used to detect some form of staleness in 209 /// profiles (see flag -sample-profile-check-coverage). 210 /// 211 /// Each entry in the map corresponds to a FunctionSamples instance. This is 212 /// another map that counts how many times the sample record at the 213 /// given location has been used. 214 FunctionSamplesCoverageMap SampleCoverage; 215 216 /// Number of samples used from the profile. 217 /// 218 /// When a sampling record is used for the first time, the samples from 219 /// that record are added to this accumulator. Coverage is later computed 220 /// based on the total number of samples available in this function and 221 /// its callsites. 222 /// 223 /// Note that this accumulator tracks samples used from a single function 224 /// and all the inlined callsites. Strictly, we should have a map of counters 225 /// keyed by FunctionSamples pointers, but these stats are cleared after 226 /// every function, so we just need to keep a single counter. 227 uint64_t TotalUsedSamples = 0; 228 229 SampleProfileLoader &SPLoader; 230 }; 231 232 class GUIDToFuncNameMapper { 233 public: 234 GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader, 235 DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap) 236 : CurrentReader(Reader), CurrentModule(M), 237 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) { 238 if (!CurrentReader.useMD5()) 239 return; 240 241 for (const auto &F : CurrentModule) { 242 StringRef OrigName = F.getName(); 243 CurrentGUIDToFuncNameMap.insert( 244 {Function::getGUID(OrigName), OrigName}); 245 246 // Local to global var promotion used by optimization like thinlto 247 // will rename the var and add suffix like ".llvm.xxx" to the 248 // original local name. In sample profile, the suffixes of function 249 // names are all stripped. Since it is possible that the mapper is 250 // built in post-thin-link phase and var promotion has been done, 251 // we need to add the substring of function name without the suffix 252 // into the GUIDToFuncNameMap. 253 StringRef CanonName = FunctionSamples::getCanonicalFnName(F); 254 if (CanonName != OrigName) 255 CurrentGUIDToFuncNameMap.insert( 256 {Function::getGUID(CanonName), CanonName}); 257 } 258 259 // Update GUIDToFuncNameMap for each function including inlinees. 260 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap); 261 } 262 263 ~GUIDToFuncNameMapper() { 264 if (!CurrentReader.useMD5()) 265 return; 266 267 CurrentGUIDToFuncNameMap.clear(); 268 269 // Reset GUIDToFuncNameMap for of each function as they're no 270 // longer valid at this point. 271 SetGUIDToFuncNameMapForAll(nullptr); 272 } 273 274 private: 275 void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) { 276 std::queue<FunctionSamples *> FSToUpdate; 277 for (auto &IFS : CurrentReader.getProfiles()) { 278 FSToUpdate.push(&IFS.second); 279 } 280 281 while (!FSToUpdate.empty()) { 282 FunctionSamples *FS = FSToUpdate.front(); 283 FSToUpdate.pop(); 284 FS->GUIDToFuncNameMap = Map; 285 for (const auto &ICS : FS->getCallsiteSamples()) { 286 const FunctionSamplesMap &FSMap = ICS.second; 287 for (auto &IFS : FSMap) { 288 FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second); 289 FSToUpdate.push(&FS); 290 } 291 } 292 } 293 } 294 295 SampleProfileReader &CurrentReader; 296 Module &CurrentModule; 297 DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap; 298 }; 299 300 /// Sample profile pass. 301 /// 302 /// This pass reads profile data from the file specified by 303 /// -sample-profile-file and annotates every affected function with the 304 /// profile information found in that file. 305 class SampleProfileLoader { 306 public: 307 SampleProfileLoader( 308 StringRef Name, StringRef RemapName, bool IsThinLTOPreLink, 309 std::function<AssumptionCache &(Function &)> GetAssumptionCache, 310 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo, 311 std::function<const TargetLibraryInfo &(Function &)> GetTLI) 312 : GetAC(std::move(GetAssumptionCache)), 313 GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)), 314 CoverageTracker(*this), Filename(std::string(Name)), 315 RemappingFilename(std::string(RemapName)), 316 IsThinLTOPreLink(IsThinLTOPreLink) {} 317 318 bool doInitialization(Module &M); 319 bool runOnModule(Module &M, ModuleAnalysisManager *AM, 320 ProfileSummaryInfo *_PSI, CallGraph *CG); 321 322 void dump() { Reader->dump(); } 323 324 protected: 325 friend class SampleCoverageTracker; 326 327 bool runOnFunction(Function &F, ModuleAnalysisManager *AM); 328 unsigned getFunctionLoc(Function &F); 329 bool emitAnnotations(Function &F); 330 ErrorOr<uint64_t> getInstWeight(const Instruction &I); 331 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB); 332 const FunctionSamples *findCalleeFunctionSamples(const Instruction &I) const; 333 std::vector<const FunctionSamples *> 334 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const; 335 mutable DenseMap<const DILocation *, const FunctionSamples *> DILocation2SampleMap; 336 const FunctionSamples *findFunctionSamples(const Instruction &I) const; 337 bool inlineCallInstruction(Instruction *I); 338 bool inlineHotFunctions(Function &F, 339 DenseSet<GlobalValue::GUID> &InlinedGUIDs); 340 // Inline cold/small functions in addition to hot ones 341 bool shouldInlineColdCallee(Instruction &CallInst); 342 void emitOptimizationRemarksForInlineCandidates( 343 const SmallVector<Instruction *, 10> &Candidates, const Function &F, bool Hot); 344 void printEdgeWeight(raw_ostream &OS, Edge E); 345 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const; 346 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB); 347 bool computeBlockWeights(Function &F); 348 void findEquivalenceClasses(Function &F); 349 template <bool IsPostDom> 350 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants, 351 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree); 352 353 void propagateWeights(Function &F); 354 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); 355 void buildEdges(Function &F); 356 std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG); 357 bool propagateThroughEdges(Function &F, bool UpdateBlockCount); 358 void computeDominanceAndLoopInfo(Function &F); 359 void clearFunctionData(); 360 bool callsiteIsHot(const FunctionSamples *CallsiteFS, 361 ProfileSummaryInfo *PSI); 362 363 /// Map basic blocks to their computed weights. 364 /// 365 /// The weight of a basic block is defined to be the maximum 366 /// of all the instruction weights in that block. 367 BlockWeightMap BlockWeights; 368 369 /// Map edges to their computed weights. 370 /// 371 /// Edge weights are computed by propagating basic block weights in 372 /// SampleProfile::propagateWeights. 373 EdgeWeightMap EdgeWeights; 374 375 /// Set of visited blocks during propagation. 376 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks; 377 378 /// Set of visited edges during propagation. 379 SmallSet<Edge, 32> VisitedEdges; 380 381 /// Equivalence classes for block weights. 382 /// 383 /// Two blocks BB1 and BB2 are in the same equivalence class if they 384 /// dominate and post-dominate each other, and they are in the same loop 385 /// nest. When this happens, the two blocks are guaranteed to execute 386 /// the same number of times. 387 EquivalenceClassMap EquivalenceClass; 388 389 /// Map from function name to Function *. Used to find the function from 390 /// the function name. If the function name contains suffix, additional 391 /// entry is added to map from the stripped name to the function if there 392 /// is one-to-one mapping. 393 StringMap<Function *> SymbolMap; 394 395 /// Dominance, post-dominance and loop information. 396 std::unique_ptr<DominatorTree> DT; 397 std::unique_ptr<PostDominatorTree> PDT; 398 std::unique_ptr<LoopInfo> LI; 399 400 std::function<AssumptionCache &(Function &)> GetAC; 401 std::function<TargetTransformInfo &(Function &)> GetTTI; 402 std::function<const TargetLibraryInfo &(Function &)> GetTLI; 403 404 /// Predecessors for each basic block in the CFG. 405 BlockEdgeMap Predecessors; 406 407 /// Successors for each basic block in the CFG. 408 BlockEdgeMap Successors; 409 410 SampleCoverageTracker CoverageTracker; 411 412 /// Profile reader object. 413 std::unique_ptr<SampleProfileReader> Reader; 414 415 /// Samples collected for the body of this function. 416 FunctionSamples *Samples = nullptr; 417 418 /// Name of the profile file to load. 419 std::string Filename; 420 421 /// Name of the profile remapping file to load. 422 std::string RemappingFilename; 423 424 /// Flag indicating whether the profile input loaded successfully. 425 bool ProfileIsValid = false; 426 427 /// Flag indicating if the pass is invoked in ThinLTO compile phase. 428 /// 429 /// In this phase, in annotation, we should not promote indirect calls. 430 /// Instead, we will mark GUIDs that needs to be annotated to the function. 431 bool IsThinLTOPreLink; 432 433 /// Profile Summary Info computed from sample profile. 434 ProfileSummaryInfo *PSI = nullptr; 435 436 /// Profle Symbol list tells whether a function name appears in the binary 437 /// used to generate the current profile. 438 std::unique_ptr<ProfileSymbolList> PSL; 439 440 /// Total number of samples collected in this profile. 441 /// 442 /// This is the sum of all the samples collected in all the functions executed 443 /// at runtime. 444 uint64_t TotalCollectedSamples = 0; 445 446 /// Optimization Remark Emitter used to emit diagnostic remarks. 447 OptimizationRemarkEmitter *ORE = nullptr; 448 449 // Information recorded when we declined to inline a call site 450 // because we have determined it is too cold is accumulated for 451 // each callee function. Initially this is just the entry count. 452 struct NotInlinedProfileInfo { 453 uint64_t entryCount; 454 }; 455 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo; 456 457 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for 458 // all the function symbols defined or declared in current module. 459 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap; 460 461 // All the Names used in FunctionSamples including outline function 462 // names, inline instance names and call target names. 463 StringSet<> NamesInProfile; 464 465 // For symbol in profile symbol list, whether to regard their profiles 466 // to be accurate. It is mainly decided by existance of profile symbol 467 // list and -profile-accurate-for-symsinlist flag, but it can be 468 // overriden by -profile-sample-accurate or profile-sample-accurate 469 // attribute. 470 bool ProfAccForSymsInList; 471 }; 472 473 class SampleProfileLoaderLegacyPass : public ModulePass { 474 public: 475 // Class identification, replacement for typeinfo 476 static char ID; 477 478 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile, 479 bool IsThinLTOPreLink = false) 480 : ModulePass(ID), SampleLoader( 481 Name, SampleProfileRemappingFile, IsThinLTOPreLink, 482 [&](Function &F) -> AssumptionCache & { 483 return ACT->getAssumptionCache(F); 484 }, 485 [&](Function &F) -> TargetTransformInfo & { 486 return TTIWP->getTTI(F); 487 }, 488 [&](Function &F) -> TargetLibraryInfo & { 489 return TLIWP->getTLI(F); 490 }) { 491 initializeSampleProfileLoaderLegacyPassPass( 492 *PassRegistry::getPassRegistry()); 493 } 494 495 void dump() { SampleLoader.dump(); } 496 497 bool doInitialization(Module &M) override { 498 return SampleLoader.doInitialization(M); 499 } 500 501 StringRef getPassName() const override { return "Sample profile pass"; } 502 bool runOnModule(Module &M) override; 503 504 void getAnalysisUsage(AnalysisUsage &AU) const override { 505 AU.addRequired<AssumptionCacheTracker>(); 506 AU.addRequired<TargetTransformInfoWrapperPass>(); 507 AU.addRequired<TargetLibraryInfoWrapperPass>(); 508 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 509 } 510 511 private: 512 SampleProfileLoader SampleLoader; 513 AssumptionCacheTracker *ACT = nullptr; 514 TargetTransformInfoWrapperPass *TTIWP = nullptr; 515 TargetLibraryInfoWrapperPass *TLIWP = nullptr; 516 }; 517 518 } // end anonymous namespace 519 520 /// Return true if the given callsite is hot wrt to hot cutoff threshold. 521 /// 522 /// Functions that were inlined in the original binary will be represented 523 /// in the inline stack in the sample profile. If the profile shows that 524 /// the original inline decision was "good" (i.e., the callsite is executed 525 /// frequently), then we will recreate the inline decision and apply the 526 /// profile from the inlined callsite. 527 /// 528 /// To decide whether an inlined callsite is hot, we compare the callsite 529 /// sample count with the hot cutoff computed by ProfileSummaryInfo, it is 530 /// regarded as hot if the count is above the cutoff value. 531 /// 532 /// When ProfileAccurateForSymsInList is enabled and profile symbol list 533 /// is present, functions in the profile symbol list but without profile will 534 /// be regarded as cold and much less inlining will happen in CGSCC inlining 535 /// pass, so we tend to lower the hot criteria here to allow more early 536 /// inlining to happen for warm callsites and it is helpful for performance. 537 bool SampleProfileLoader::callsiteIsHot(const FunctionSamples *CallsiteFS, 538 ProfileSummaryInfo *PSI) { 539 if (!CallsiteFS) 540 return false; // The callsite was not inlined in the original binary. 541 542 assert(PSI && "PSI is expected to be non null"); 543 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples(); 544 if (ProfAccForSymsInList) 545 return !PSI->isColdCount(CallsiteTotalSamples); 546 else 547 return PSI->isHotCount(CallsiteTotalSamples); 548 } 549 550 /// Mark as used the sample record for the given function samples at 551 /// (LineOffset, Discriminator). 552 /// 553 /// \returns true if this is the first time we mark the given record. 554 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS, 555 uint32_t LineOffset, 556 uint32_t Discriminator, 557 uint64_t Samples) { 558 LineLocation Loc(LineOffset, Discriminator); 559 unsigned &Count = SampleCoverage[FS][Loc]; 560 bool FirstTime = (++Count == 1); 561 if (FirstTime) 562 TotalUsedSamples += Samples; 563 return FirstTime; 564 } 565 566 /// Return the number of sample records that were applied from this profile. 567 /// 568 /// This count does not include records from cold inlined callsites. 569 unsigned 570 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS, 571 ProfileSummaryInfo *PSI) const { 572 auto I = SampleCoverage.find(FS); 573 574 // The size of the coverage map for FS represents the number of records 575 // that were marked used at least once. 576 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0; 577 578 // If there are inlined callsites in this function, count the samples found 579 // in the respective bodies. However, do not bother counting callees with 0 580 // total samples, these are callees that were never invoked at runtime. 581 for (const auto &I : FS->getCallsiteSamples()) 582 for (const auto &J : I.second) { 583 const FunctionSamples *CalleeSamples = &J.second; 584 if (SPLoader.callsiteIsHot(CalleeSamples, PSI)) 585 Count += countUsedRecords(CalleeSamples, PSI); 586 } 587 588 return Count; 589 } 590 591 /// Return the number of sample records in the body of this profile. 592 /// 593 /// This count does not include records from cold inlined callsites. 594 unsigned 595 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS, 596 ProfileSummaryInfo *PSI) const { 597 unsigned Count = FS->getBodySamples().size(); 598 599 // Only count records in hot callsites. 600 for (const auto &I : FS->getCallsiteSamples()) 601 for (const auto &J : I.second) { 602 const FunctionSamples *CalleeSamples = &J.second; 603 if (SPLoader.callsiteIsHot(CalleeSamples, PSI)) 604 Count += countBodyRecords(CalleeSamples, PSI); 605 } 606 607 return Count; 608 } 609 610 /// Return the number of samples collected in the body of this profile. 611 /// 612 /// This count does not include samples from cold inlined callsites. 613 uint64_t 614 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS, 615 ProfileSummaryInfo *PSI) const { 616 uint64_t Total = 0; 617 for (const auto &I : FS->getBodySamples()) 618 Total += I.second.getSamples(); 619 620 // Only count samples in hot callsites. 621 for (const auto &I : FS->getCallsiteSamples()) 622 for (const auto &J : I.second) { 623 const FunctionSamples *CalleeSamples = &J.second; 624 if (SPLoader.callsiteIsHot(CalleeSamples, PSI)) 625 Total += countBodySamples(CalleeSamples, PSI); 626 } 627 628 return Total; 629 } 630 631 /// Return the fraction of sample records used in this profile. 632 /// 633 /// The returned value is an unsigned integer in the range 0-100 indicating 634 /// the percentage of sample records that were used while applying this 635 /// profile to the associated function. 636 unsigned SampleCoverageTracker::computeCoverage(unsigned Used, 637 unsigned Total) const { 638 assert(Used <= Total && 639 "number of used records cannot exceed the total number of records"); 640 return Total > 0 ? Used * 100 / Total : 100; 641 } 642 643 /// Clear all the per-function data used to load samples and propagate weights. 644 void SampleProfileLoader::clearFunctionData() { 645 BlockWeights.clear(); 646 EdgeWeights.clear(); 647 VisitedBlocks.clear(); 648 VisitedEdges.clear(); 649 EquivalenceClass.clear(); 650 DT = nullptr; 651 PDT = nullptr; 652 LI = nullptr; 653 Predecessors.clear(); 654 Successors.clear(); 655 CoverageTracker.clear(); 656 } 657 658 #ifndef NDEBUG 659 /// Print the weight of edge \p E on stream \p OS. 660 /// 661 /// \param OS Stream to emit the output to. 662 /// \param E Edge to print. 663 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) { 664 OS << "weight[" << E.first->getName() << "->" << E.second->getName() 665 << "]: " << EdgeWeights[E] << "\n"; 666 } 667 668 /// Print the equivalence class of block \p BB on stream \p OS. 669 /// 670 /// \param OS Stream to emit the output to. 671 /// \param BB Block to print. 672 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS, 673 const BasicBlock *BB) { 674 const BasicBlock *Equiv = EquivalenceClass[BB]; 675 OS << "equivalence[" << BB->getName() 676 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; 677 } 678 679 /// Print the weight of block \p BB on stream \p OS. 680 /// 681 /// \param OS Stream to emit the output to. 682 /// \param BB Block to print. 683 void SampleProfileLoader::printBlockWeight(raw_ostream &OS, 684 const BasicBlock *BB) const { 685 const auto &I = BlockWeights.find(BB); 686 uint64_t W = (I == BlockWeights.end() ? 0 : I->second); 687 OS << "weight[" << BB->getName() << "]: " << W << "\n"; 688 } 689 #endif 690 691 /// Get the weight for an instruction. 692 /// 693 /// The "weight" of an instruction \p Inst is the number of samples 694 /// collected on that instruction at runtime. To retrieve it, we 695 /// need to compute the line number of \p Inst relative to the start of its 696 /// function. We use HeaderLineno to compute the offset. We then 697 /// look up the samples collected for \p Inst using BodySamples. 698 /// 699 /// \param Inst Instruction to query. 700 /// 701 /// \returns the weight of \p Inst. 702 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) { 703 const DebugLoc &DLoc = Inst.getDebugLoc(); 704 if (!DLoc) 705 return std::error_code(); 706 707 const FunctionSamples *FS = findFunctionSamples(Inst); 708 if (!FS) 709 return std::error_code(); 710 711 // Ignore all intrinsics, phinodes and branch instructions. 712 // Branch and phinodes instruction usually contains debug info from sources outside of 713 // the residing basic block, thus we ignore them during annotation. 714 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst)) 715 return std::error_code(); 716 717 // If a direct call/invoke instruction is inlined in profile 718 // (findCalleeFunctionSamples returns non-empty result), but not inlined here, 719 // it means that the inlined callsite has no sample, thus the call 720 // instruction should have 0 count. 721 if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) && 722 !cast<CallBase>(Inst).isIndirectCall() && findCalleeFunctionSamples(Inst)) 723 return 0; 724 725 const DILocation *DIL = DLoc; 726 uint32_t LineOffset = FunctionSamples::getOffset(DIL); 727 uint32_t Discriminator = DIL->getBaseDiscriminator(); 728 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator); 729 if (R) { 730 bool FirstMark = 731 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get()); 732 if (FirstMark) { 733 ORE->emit([&]() { 734 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst); 735 Remark << "Applied " << ore::NV("NumSamples", *R); 736 Remark << " samples from profile (offset: "; 737 Remark << ore::NV("LineOffset", LineOffset); 738 if (Discriminator) { 739 Remark << "."; 740 Remark << ore::NV("Discriminator", Discriminator); 741 } 742 Remark << ")"; 743 return Remark; 744 }); 745 } 746 LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "." 747 << DIL->getBaseDiscriminator() << ":" << Inst 748 << " (line offset: " << LineOffset << "." 749 << DIL->getBaseDiscriminator() << " - weight: " << R.get() 750 << ")\n"); 751 } 752 return R; 753 } 754 755 /// Compute the weight of a basic block. 756 /// 757 /// The weight of basic block \p BB is the maximum weight of all the 758 /// instructions in BB. 759 /// 760 /// \param BB The basic block to query. 761 /// 762 /// \returns the weight for \p BB. 763 ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) { 764 uint64_t Max = 0; 765 bool HasWeight = false; 766 for (auto &I : BB->getInstList()) { 767 const ErrorOr<uint64_t> &R = getInstWeight(I); 768 if (R) { 769 Max = std::max(Max, R.get()); 770 HasWeight = true; 771 } 772 } 773 return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code(); 774 } 775 776 /// Compute and store the weights of every basic block. 777 /// 778 /// This populates the BlockWeights map by computing 779 /// the weights of every basic block in the CFG. 780 /// 781 /// \param F The function to query. 782 bool SampleProfileLoader::computeBlockWeights(Function &F) { 783 bool Changed = false; 784 LLVM_DEBUG(dbgs() << "Block weights\n"); 785 for (const auto &BB : F) { 786 ErrorOr<uint64_t> Weight = getBlockWeight(&BB); 787 if (Weight) { 788 BlockWeights[&BB] = Weight.get(); 789 VisitedBlocks.insert(&BB); 790 Changed = true; 791 } 792 LLVM_DEBUG(printBlockWeight(dbgs(), &BB)); 793 } 794 795 return Changed; 796 } 797 798 /// Get the FunctionSamples for a call instruction. 799 /// 800 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined 801 /// instance in which that call instruction is calling to. It contains 802 /// all samples that resides in the inlined instance. We first find the 803 /// inlined instance in which the call instruction is from, then we 804 /// traverse its children to find the callsite with the matching 805 /// location. 806 /// 807 /// \param Inst Call/Invoke instruction to query. 808 /// 809 /// \returns The FunctionSamples pointer to the inlined instance. 810 const FunctionSamples * 811 SampleProfileLoader::findCalleeFunctionSamples(const Instruction &Inst) const { 812 const DILocation *DIL = Inst.getDebugLoc(); 813 if (!DIL) { 814 return nullptr; 815 } 816 817 StringRef CalleeName; 818 if (const CallInst *CI = dyn_cast<CallInst>(&Inst)) 819 if (Function *Callee = CI->getCalledFunction()) 820 CalleeName = Callee->getName(); 821 822 const FunctionSamples *FS = findFunctionSamples(Inst); 823 if (FS == nullptr) 824 return nullptr; 825 826 return FS->findFunctionSamplesAt(LineLocation(FunctionSamples::getOffset(DIL), 827 DIL->getBaseDiscriminator()), 828 CalleeName); 829 } 830 831 /// Returns a vector of FunctionSamples that are the indirect call targets 832 /// of \p Inst. The vector is sorted by the total number of samples. Stores 833 /// the total call count of the indirect call in \p Sum. 834 std::vector<const FunctionSamples *> 835 SampleProfileLoader::findIndirectCallFunctionSamples( 836 const Instruction &Inst, uint64_t &Sum) const { 837 const DILocation *DIL = Inst.getDebugLoc(); 838 std::vector<const FunctionSamples *> R; 839 840 if (!DIL) { 841 return R; 842 } 843 844 const FunctionSamples *FS = findFunctionSamples(Inst); 845 if (FS == nullptr) 846 return R; 847 848 uint32_t LineOffset = FunctionSamples::getOffset(DIL); 849 uint32_t Discriminator = DIL->getBaseDiscriminator(); 850 851 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator); 852 Sum = 0; 853 if (T) 854 for (const auto &T_C : T.get()) 855 Sum += T_C.second; 856 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(LineLocation( 857 FunctionSamples::getOffset(DIL), DIL->getBaseDiscriminator()))) { 858 if (M->empty()) 859 return R; 860 for (const auto &NameFS : *M) { 861 Sum += NameFS.second.getEntrySamples(); 862 R.push_back(&NameFS.second); 863 } 864 llvm::sort(R, [](const FunctionSamples *L, const FunctionSamples *R) { 865 if (L->getEntrySamples() != R->getEntrySamples()) 866 return L->getEntrySamples() > R->getEntrySamples(); 867 return FunctionSamples::getGUID(L->getName()) < 868 FunctionSamples::getGUID(R->getName()); 869 }); 870 } 871 return R; 872 } 873 874 /// Get the FunctionSamples for an instruction. 875 /// 876 /// The FunctionSamples of an instruction \p Inst is the inlined instance 877 /// in which that instruction is coming from. We traverse the inline stack 878 /// of that instruction, and match it with the tree nodes in the profile. 879 /// 880 /// \param Inst Instruction to query. 881 /// 882 /// \returns the FunctionSamples pointer to the inlined instance. 883 const FunctionSamples * 884 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const { 885 const DILocation *DIL = Inst.getDebugLoc(); 886 if (!DIL) 887 return Samples; 888 889 auto it = DILocation2SampleMap.try_emplace(DIL,nullptr); 890 if (it.second) 891 it.first->second = Samples->findFunctionSamples(DIL); 892 return it.first->second; 893 } 894 895 // FIXME(CallSite): Parameter should be CallBase&, as it's assumed to be that, 896 // and non-null. 897 bool SampleProfileLoader::inlineCallInstruction(Instruction *I) { 898 assert(isa<CallInst>(I) || isa<InvokeInst>(I)); 899 CallBase &CS = *cast<CallBase>(I); 900 Function *CalledFunction = CS.getCalledFunction(); 901 assert(CalledFunction); 902 DebugLoc DLoc = I->getDebugLoc(); 903 BasicBlock *BB = I->getParent(); 904 InlineParams Params = getInlineParams(); 905 Params.ComputeFullInlineCost = true; 906 // Checks if there is anything in the reachable portion of the callee at 907 // this callsite that makes this inlining potentially illegal. Need to 908 // set ComputeFullInlineCost, otherwise getInlineCost may return early 909 // when cost exceeds threshold without checking all IRs in the callee. 910 // The acutal cost does not matter because we only checks isNever() to 911 // see if it is legal to inline the callsite. 912 InlineCost Cost = 913 getInlineCost(cast<CallBase>(*I), Params, GetTTI(*CalledFunction), GetAC, 914 None, GetTLI, nullptr, nullptr); 915 if (Cost.isNever()) { 916 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB) 917 << "incompatible inlining"); 918 return false; 919 } 920 InlineFunctionInfo IFI(nullptr, &GetAC); 921 if (InlineFunction(CS, IFI).isSuccess()) { 922 // The call to InlineFunction erases I, so we can't pass it here. 923 ORE->emit(OptimizationRemark(CSINLINE_DEBUG, "InlineSuccess", DLoc, BB) 924 << "inlined callee '" << ore::NV("Callee", CalledFunction) 925 << "' into '" << ore::NV("Caller", BB->getParent()) << "'"); 926 return true; 927 } 928 return false; 929 } 930 931 bool SampleProfileLoader::shouldInlineColdCallee(Instruction &CallInst) { 932 if (!ProfileSizeInline) 933 return false; 934 935 Function *Callee = cast<CallBase>(CallInst).getCalledFunction(); 936 if (Callee == nullptr) 937 return false; 938 939 InlineCost Cost = 940 getInlineCost(cast<CallBase>(CallInst), getInlineParams(), 941 GetTTI(*Callee), GetAC, None, GetTLI, nullptr, nullptr); 942 943 return Cost.getCost() <= SampleColdCallSiteThreshold; 944 } 945 946 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates( 947 const SmallVector<Instruction *, 10> &Candidates, const Function &F, 948 bool Hot) { 949 for (auto I : Candidates) { 950 Function *CalledFunction = cast<CallBase>(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 /// Iteratively inline hot callsites of a function. 963 /// 964 /// Iteratively traverse all callsites of the function \p F, and find if 965 /// the corresponding inlined instance exists and is hot in profile. If 966 /// it is hot enough, inline the callsites and adds new callsites of the 967 /// callee into the caller. If the call is an indirect call, first promote 968 /// it to direct call. Each indirect call is limited with a single target. 969 /// 970 /// \param F function to perform iterative inlining. 971 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are 972 /// inlined in the profiled binary. 973 /// 974 /// \returns True if there is any inline happened. 975 bool SampleProfileLoader::inlineHotFunctions( 976 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) { 977 DenseSet<Instruction *> PromotedInsns; 978 979 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure 980 // Profile symbol list is ignored when profile-sample-accurate is on. 981 assert((!ProfAccForSymsInList || 982 (!ProfileSampleAccurate && 983 !F.hasFnAttribute("profile-sample-accurate"))) && 984 "ProfAccForSymsInList should be false when profile-sample-accurate " 985 "is enabled"); 986 987 // FIXME(CallSite): refactor the vectors here, as they operate with CallBase 988 // values 989 DenseMap<Instruction *, const FunctionSamples *> localNotInlinedCallSites; 990 bool Changed = false; 991 while (true) { 992 bool LocalChanged = false; 993 SmallVector<Instruction *, 10> CIS; 994 for (auto &BB : F) { 995 bool Hot = false; 996 SmallVector<Instruction *, 10> AllCandidates; 997 SmallVector<Instruction *, 10> ColdCandidates; 998 for (auto &I : BB.getInstList()) { 999 const FunctionSamples *FS = nullptr; 1000 if ((isa<CallInst>(I) || isa<InvokeInst>(I)) && 1001 !isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(I))) { 1002 AllCandidates.push_back(&I); 1003 if (FS->getEntrySamples() > 0) 1004 localNotInlinedCallSites.try_emplace(&I, FS); 1005 if (callsiteIsHot(FS, PSI)) 1006 Hot = true; 1007 else if (shouldInlineColdCallee(I)) 1008 ColdCandidates.push_back(&I); 1009 } 1010 } 1011 if (Hot) { 1012 CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end()); 1013 emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true); 1014 } 1015 else { 1016 CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end()); 1017 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false); 1018 } 1019 } 1020 for (auto I : CIS) { 1021 Function *CalledFunction = cast<CallBase>(I)->getCalledFunction(); 1022 // Do not inline recursive calls. 1023 if (CalledFunction == &F) 1024 continue; 1025 if (cast<CallBase>(I)->isIndirectCall()) { 1026 if (PromotedInsns.count(I)) 1027 continue; 1028 uint64_t Sum; 1029 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) { 1030 if (IsThinLTOPreLink) { 1031 FS->findInlinedFunctions(InlinedGUIDs, F.getParent(), 1032 PSI->getOrCompHotCountThreshold()); 1033 continue; 1034 } 1035 auto CalleeFunctionName = FS->getFuncNameInModule(F.getParent()); 1036 // If it is a recursive call, we do not inline it as it could bloat 1037 // the code exponentially. There is way to better handle this, e.g. 1038 // clone the caller first, and inline the cloned caller if it is 1039 // recursive. As llvm does not inline recursive calls, we will 1040 // simply ignore it instead of handling it explicitly. 1041 if (CalleeFunctionName == F.getName()) 1042 continue; 1043 1044 if (!callsiteIsHot(FS, PSI)) 1045 continue; 1046 1047 const char *Reason = "Callee function not available"; 1048 auto R = SymbolMap.find(CalleeFunctionName); 1049 if (R != SymbolMap.end() && R->getValue() && 1050 !R->getValue()->isDeclaration() && 1051 R->getValue()->getSubprogram() && 1052 isLegalToPromote(*cast<CallBase>(I), R->getValue(), &Reason)) { 1053 uint64_t C = FS->getEntrySamples(); 1054 Instruction *DI = 1055 pgo::promoteIndirectCall(I, R->getValue(), C, Sum, false, ORE); 1056 Sum -= C; 1057 PromotedInsns.insert(I); 1058 // If profile mismatches, we should not attempt to inline DI. 1059 if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) && 1060 inlineCallInstruction(DI)) { 1061 localNotInlinedCallSites.erase(I); 1062 LocalChanged = true; 1063 ++NumCSInlined; 1064 } 1065 } else { 1066 LLVM_DEBUG(dbgs() 1067 << "\nFailed to promote indirect call to " 1068 << CalleeFunctionName << " because " << Reason << "\n"); 1069 } 1070 } 1071 } else if (CalledFunction && CalledFunction->getSubprogram() && 1072 !CalledFunction->isDeclaration()) { 1073 if (inlineCallInstruction(I)) { 1074 localNotInlinedCallSites.erase(I); 1075 LocalChanged = true; 1076 ++NumCSInlined; 1077 } 1078 } else if (IsThinLTOPreLink) { 1079 findCalleeFunctionSamples(*I)->findInlinedFunctions( 1080 InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold()); 1081 } 1082 } 1083 if (LocalChanged) { 1084 Changed = true; 1085 } else { 1086 break; 1087 } 1088 } 1089 1090 // Accumulate not inlined callsite information into notInlinedSamples 1091 for (const auto &Pair : localNotInlinedCallSites) { 1092 Instruction *I = Pair.getFirst(); 1093 Function *Callee = cast<CallBase>(I)->getCalledFunction(); 1094 if (!Callee || Callee->isDeclaration()) 1095 continue; 1096 1097 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline", 1098 I->getDebugLoc(), I->getParent()) 1099 << "previous inlining not repeated: '" 1100 << ore::NV("Callee", Callee) << "' into '" 1101 << ore::NV("Caller", &F) << "'"); 1102 1103 ++NumCSNotInlined; 1104 const FunctionSamples *FS = Pair.getSecond(); 1105 if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) { 1106 continue; 1107 } 1108 1109 if (ProfileMergeInlinee) { 1110 // Use entry samples as head samples during the merge, as inlinees 1111 // don't have head samples. 1112 assert(FS->getHeadSamples() == 0 && "Expect 0 head sample for inlinee"); 1113 const_cast<FunctionSamples *>(FS)->addHeadSamples(FS->getEntrySamples()); 1114 1115 // Note that we have to do the merge right after processing function. 1116 // This allows OutlineFS's profile to be used for annotation during 1117 // top-down processing of functions' annotation. 1118 FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee); 1119 OutlineFS->merge(*FS); 1120 } else { 1121 auto pair = 1122 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0}); 1123 pair.first->second.entryCount += FS->getEntrySamples(); 1124 } 1125 } 1126 return Changed; 1127 } 1128 1129 /// Find equivalence classes for the given block. 1130 /// 1131 /// This finds all the blocks that are guaranteed to execute the same 1132 /// number of times as \p BB1. To do this, it traverses all the 1133 /// descendants of \p BB1 in the dominator or post-dominator tree. 1134 /// 1135 /// A block BB2 will be in the same equivalence class as \p BB1 if 1136 /// the following holds: 1137 /// 1138 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 1139 /// is a descendant of \p BB1 in the dominator tree, then BB2 should 1140 /// dominate BB1 in the post-dominator tree. 1141 /// 1142 /// 2- Both BB2 and \p BB1 must be in the same loop. 1143 /// 1144 /// For every block BB2 that meets those two requirements, we set BB2's 1145 /// equivalence class to \p BB1. 1146 /// 1147 /// \param BB1 Block to check. 1148 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. 1149 /// \param DomTree Opposite dominator tree. If \p Descendants is filled 1150 /// with blocks from \p BB1's dominator tree, then 1151 /// this is the post-dominator tree, and vice versa. 1152 template <bool IsPostDom> 1153 void SampleProfileLoader::findEquivalencesFor( 1154 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants, 1155 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) { 1156 const BasicBlock *EC = EquivalenceClass[BB1]; 1157 uint64_t Weight = BlockWeights[EC]; 1158 for (const auto *BB2 : Descendants) { 1159 bool IsDomParent = DomTree->dominates(BB2, BB1); 1160 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); 1161 if (BB1 != BB2 && IsDomParent && IsInSameLoop) { 1162 EquivalenceClass[BB2] = EC; 1163 // If BB2 is visited, then the entire EC should be marked as visited. 1164 if (VisitedBlocks.count(BB2)) { 1165 VisitedBlocks.insert(EC); 1166 } 1167 1168 // If BB2 is heavier than BB1, make BB2 have the same weight 1169 // as BB1. 1170 // 1171 // Note that we don't worry about the opposite situation here 1172 // (when BB2 is lighter than BB1). We will deal with this 1173 // during the propagation phase. Right now, we just want to 1174 // make sure that BB1 has the largest weight of all the 1175 // members of its equivalence set. 1176 Weight = std::max(Weight, BlockWeights[BB2]); 1177 } 1178 } 1179 if (EC == &EC->getParent()->getEntryBlock()) { 1180 BlockWeights[EC] = Samples->getHeadSamples() + 1; 1181 } else { 1182 BlockWeights[EC] = Weight; 1183 } 1184 } 1185 1186 /// Find equivalence classes. 1187 /// 1188 /// Since samples may be missing from blocks, we can fill in the gaps by setting 1189 /// the weights of all the blocks in the same equivalence class to the same 1190 /// weight. To compute the concept of equivalence, we use dominance and loop 1191 /// information. Two blocks B1 and B2 are in the same equivalence class if B1 1192 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 1193 /// 1194 /// \param F The function to query. 1195 void SampleProfileLoader::findEquivalenceClasses(Function &F) { 1196 SmallVector<BasicBlock *, 8> DominatedBBs; 1197 LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n"); 1198 // Find equivalence sets based on dominance and post-dominance information. 1199 for (auto &BB : F) { 1200 BasicBlock *BB1 = &BB; 1201 1202 // Compute BB1's equivalence class once. 1203 if (EquivalenceClass.count(BB1)) { 1204 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); 1205 continue; 1206 } 1207 1208 // By default, blocks are in their own equivalence class. 1209 EquivalenceClass[BB1] = BB1; 1210 1211 // Traverse all the blocks dominated by BB1. We are looking for 1212 // every basic block BB2 such that: 1213 // 1214 // 1- BB1 dominates BB2. 1215 // 2- BB2 post-dominates BB1. 1216 // 3- BB1 and BB2 are in the same loop nest. 1217 // 1218 // If all those conditions hold, it means that BB2 is executed 1219 // as many times as BB1, so they are placed in the same equivalence 1220 // class by making BB2's equivalence class be BB1. 1221 DominatedBBs.clear(); 1222 DT->getDescendants(BB1, DominatedBBs); 1223 findEquivalencesFor(BB1, DominatedBBs, PDT.get()); 1224 1225 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); 1226 } 1227 1228 // Assign weights to equivalence classes. 1229 // 1230 // All the basic blocks in the same equivalence class will execute 1231 // the same number of times. Since we know that the head block in 1232 // each equivalence class has the largest weight, assign that weight 1233 // to all the blocks in that equivalence class. 1234 LLVM_DEBUG( 1235 dbgs() << "\nAssign the same weight to all blocks in the same class\n"); 1236 for (auto &BI : F) { 1237 const BasicBlock *BB = &BI; 1238 const BasicBlock *EquivBB = EquivalenceClass[BB]; 1239 if (BB != EquivBB) 1240 BlockWeights[BB] = BlockWeights[EquivBB]; 1241 LLVM_DEBUG(printBlockWeight(dbgs(), BB)); 1242 } 1243 } 1244 1245 /// Visit the given edge to decide if it has a valid weight. 1246 /// 1247 /// If \p E has not been visited before, we copy to \p UnknownEdge 1248 /// and increment the count of unknown edges. 1249 /// 1250 /// \param E Edge to visit. 1251 /// \param NumUnknownEdges Current number of unknown edges. 1252 /// \param UnknownEdge Set if E has not been visited before. 1253 /// 1254 /// \returns E's weight, if known. Otherwise, return 0. 1255 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges, 1256 Edge *UnknownEdge) { 1257 if (!VisitedEdges.count(E)) { 1258 (*NumUnknownEdges)++; 1259 *UnknownEdge = E; 1260 return 0; 1261 } 1262 1263 return EdgeWeights[E]; 1264 } 1265 1266 /// Propagate weights through incoming/outgoing edges. 1267 /// 1268 /// If the weight of a basic block is known, and there is only one edge 1269 /// with an unknown weight, we can calculate the weight of that edge. 1270 /// 1271 /// Similarly, if all the edges have a known count, we can calculate the 1272 /// count of the basic block, if needed. 1273 /// 1274 /// \param F Function to process. 1275 /// \param UpdateBlockCount Whether we should update basic block counts that 1276 /// has already been annotated. 1277 /// 1278 /// \returns True if new weights were assigned to edges or blocks. 1279 bool SampleProfileLoader::propagateThroughEdges(Function &F, 1280 bool UpdateBlockCount) { 1281 bool Changed = false; 1282 LLVM_DEBUG(dbgs() << "\nPropagation through edges\n"); 1283 for (const auto &BI : F) { 1284 const BasicBlock *BB = &BI; 1285 const BasicBlock *EC = EquivalenceClass[BB]; 1286 1287 // Visit all the predecessor and successor edges to determine 1288 // which ones have a weight assigned already. Note that it doesn't 1289 // matter that we only keep track of a single unknown edge. The 1290 // only case we are interested in handling is when only a single 1291 // edge is unknown (see setEdgeOrBlockWeight). 1292 for (unsigned i = 0; i < 2; i++) { 1293 uint64_t TotalWeight = 0; 1294 unsigned NumUnknownEdges = 0, NumTotalEdges = 0; 1295 Edge UnknownEdge, SelfReferentialEdge, SingleEdge; 1296 1297 if (i == 0) { 1298 // First, visit all predecessor edges. 1299 NumTotalEdges = Predecessors[BB].size(); 1300 for (auto *Pred : Predecessors[BB]) { 1301 Edge E = std::make_pair(Pred, BB); 1302 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 1303 if (E.first == E.second) 1304 SelfReferentialEdge = E; 1305 } 1306 if (NumTotalEdges == 1) { 1307 SingleEdge = std::make_pair(Predecessors[BB][0], BB); 1308 } 1309 } else { 1310 // On the second round, visit all successor edges. 1311 NumTotalEdges = Successors[BB].size(); 1312 for (auto *Succ : Successors[BB]) { 1313 Edge E = std::make_pair(BB, Succ); 1314 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 1315 } 1316 if (NumTotalEdges == 1) { 1317 SingleEdge = std::make_pair(BB, Successors[BB][0]); 1318 } 1319 } 1320 1321 // After visiting all the edges, there are three cases that we 1322 // can handle immediately: 1323 // 1324 // - All the edge weights are known (i.e., NumUnknownEdges == 0). 1325 // In this case, we simply check that the sum of all the edges 1326 // is the same as BB's weight. If not, we change BB's weight 1327 // to match. Additionally, if BB had not been visited before, 1328 // we mark it visited. 1329 // 1330 // - Only one edge is unknown and BB has already been visited. 1331 // In this case, we can compute the weight of the edge by 1332 // subtracting the total block weight from all the known 1333 // edge weights. If the edges weight more than BB, then the 1334 // edge of the last remaining edge is set to zero. 1335 // 1336 // - There exists a self-referential edge and the weight of BB is 1337 // known. In this case, this edge can be based on BB's weight. 1338 // We add up all the other known edges and set the weight on 1339 // the self-referential edge as we did in the previous case. 1340 // 1341 // In any other case, we must continue iterating. Eventually, 1342 // all edges will get a weight, or iteration will stop when 1343 // it reaches SampleProfileMaxPropagateIterations. 1344 if (NumUnknownEdges <= 1) { 1345 uint64_t &BBWeight = BlockWeights[EC]; 1346 if (NumUnknownEdges == 0) { 1347 if (!VisitedBlocks.count(EC)) { 1348 // If we already know the weight of all edges, the weight of the 1349 // basic block can be computed. It should be no larger than the sum 1350 // of all edge weights. 1351 if (TotalWeight > BBWeight) { 1352 BBWeight = TotalWeight; 1353 Changed = true; 1354 LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName() 1355 << " known. Set weight for block: "; 1356 printBlockWeight(dbgs(), BB);); 1357 } 1358 } else if (NumTotalEdges == 1 && 1359 EdgeWeights[SingleEdge] < BlockWeights[EC]) { 1360 // If there is only one edge for the visited basic block, use the 1361 // block weight to adjust edge weight if edge weight is smaller. 1362 EdgeWeights[SingleEdge] = BlockWeights[EC]; 1363 Changed = true; 1364 } 1365 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) { 1366 // If there is a single unknown edge and the block has been 1367 // visited, then we can compute E's weight. 1368 if (BBWeight >= TotalWeight) 1369 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; 1370 else 1371 EdgeWeights[UnknownEdge] = 0; 1372 const BasicBlock *OtherEC; 1373 if (i == 0) 1374 OtherEC = EquivalenceClass[UnknownEdge.first]; 1375 else 1376 OtherEC = EquivalenceClass[UnknownEdge.second]; 1377 // Edge weights should never exceed the BB weights it connects. 1378 if (VisitedBlocks.count(OtherEC) && 1379 EdgeWeights[UnknownEdge] > BlockWeights[OtherEC]) 1380 EdgeWeights[UnknownEdge] = BlockWeights[OtherEC]; 1381 VisitedEdges.insert(UnknownEdge); 1382 Changed = true; 1383 LLVM_DEBUG(dbgs() << "Set weight for edge: "; 1384 printEdgeWeight(dbgs(), UnknownEdge)); 1385 } 1386 } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) { 1387 // If a block Weights 0, all its in/out edges should weight 0. 1388 if (i == 0) { 1389 for (auto *Pred : Predecessors[BB]) { 1390 Edge E = std::make_pair(Pred, BB); 1391 EdgeWeights[E] = 0; 1392 VisitedEdges.insert(E); 1393 } 1394 } else { 1395 for (auto *Succ : Successors[BB]) { 1396 Edge E = std::make_pair(BB, Succ); 1397 EdgeWeights[E] = 0; 1398 VisitedEdges.insert(E); 1399 } 1400 } 1401 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) { 1402 uint64_t &BBWeight = BlockWeights[BB]; 1403 // We have a self-referential edge and the weight of BB is known. 1404 if (BBWeight >= TotalWeight) 1405 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; 1406 else 1407 EdgeWeights[SelfReferentialEdge] = 0; 1408 VisitedEdges.insert(SelfReferentialEdge); 1409 Changed = true; 1410 LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: "; 1411 printEdgeWeight(dbgs(), SelfReferentialEdge)); 1412 } 1413 if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) { 1414 BlockWeights[EC] = TotalWeight; 1415 VisitedBlocks.insert(EC); 1416 Changed = true; 1417 } 1418 } 1419 } 1420 1421 return Changed; 1422 } 1423 1424 /// Build in/out edge lists for each basic block in the CFG. 1425 /// 1426 /// We are interested in unique edges. If a block B1 has multiple 1427 /// edges to another block B2, we only add a single B1->B2 edge. 1428 void SampleProfileLoader::buildEdges(Function &F) { 1429 for (auto &BI : F) { 1430 BasicBlock *B1 = &BI; 1431 1432 // Add predecessors for B1. 1433 SmallPtrSet<BasicBlock *, 16> Visited; 1434 if (!Predecessors[B1].empty()) 1435 llvm_unreachable("Found a stale predecessors list in a basic block."); 1436 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) { 1437 BasicBlock *B2 = *PI; 1438 if (Visited.insert(B2).second) 1439 Predecessors[B1].push_back(B2); 1440 } 1441 1442 // Add successors for B1. 1443 Visited.clear(); 1444 if (!Successors[B1].empty()) 1445 llvm_unreachable("Found a stale successors list in a basic block."); 1446 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) { 1447 BasicBlock *B2 = *SI; 1448 if (Visited.insert(B2).second) 1449 Successors[B1].push_back(B2); 1450 } 1451 } 1452 } 1453 1454 /// Returns the sorted CallTargetMap \p M by count in descending order. 1455 static SmallVector<InstrProfValueData, 2> GetSortedValueDataFromCallTargets( 1456 const SampleRecord::CallTargetMap & M) { 1457 SmallVector<InstrProfValueData, 2> R; 1458 for (const auto &I : SampleRecord::SortCallTargets(M)) { 1459 R.emplace_back(InstrProfValueData{FunctionSamples::getGUID(I.first), I.second}); 1460 } 1461 return R; 1462 } 1463 1464 /// Propagate weights into edges 1465 /// 1466 /// The following rules are applied to every block BB in the CFG: 1467 /// 1468 /// - If BB has a single predecessor/successor, then the weight 1469 /// of that edge is the weight of the block. 1470 /// 1471 /// - If all incoming or outgoing edges are known except one, and the 1472 /// weight of the block is already known, the weight of the unknown 1473 /// edge will be the weight of the block minus the sum of all the known 1474 /// edges. If the sum of all the known edges is larger than BB's weight, 1475 /// we set the unknown edge weight to zero. 1476 /// 1477 /// - If there is a self-referential edge, and the weight of the block is 1478 /// known, the weight for that edge is set to the weight of the block 1479 /// minus the weight of the other incoming edges to that block (if 1480 /// known). 1481 void SampleProfileLoader::propagateWeights(Function &F) { 1482 bool Changed = true; 1483 unsigned I = 0; 1484 1485 // If BB weight is larger than its corresponding loop's header BB weight, 1486 // use the BB weight to replace the loop header BB weight. 1487 for (auto &BI : F) { 1488 BasicBlock *BB = &BI; 1489 Loop *L = LI->getLoopFor(BB); 1490 if (!L) { 1491 continue; 1492 } 1493 BasicBlock *Header = L->getHeader(); 1494 if (Header && BlockWeights[BB] > BlockWeights[Header]) { 1495 BlockWeights[Header] = BlockWeights[BB]; 1496 } 1497 } 1498 1499 // Before propagation starts, build, for each block, a list of 1500 // unique predecessors and successors. This is necessary to handle 1501 // identical edges in multiway branches. Since we visit all blocks and all 1502 // edges of the CFG, it is cleaner to build these lists once at the start 1503 // of the pass. 1504 buildEdges(F); 1505 1506 // Propagate until we converge or we go past the iteration limit. 1507 while (Changed && I++ < SampleProfileMaxPropagateIterations) { 1508 Changed = propagateThroughEdges(F, false); 1509 } 1510 1511 // The first propagation propagates BB counts from annotated BBs to unknown 1512 // BBs. The 2nd propagation pass resets edges weights, and use all BB weights 1513 // to propagate edge weights. 1514 VisitedEdges.clear(); 1515 Changed = true; 1516 while (Changed && I++ < SampleProfileMaxPropagateIterations) { 1517 Changed = propagateThroughEdges(F, false); 1518 } 1519 1520 // The 3rd propagation pass allows adjust annotated BB weights that are 1521 // obviously wrong. 1522 Changed = true; 1523 while (Changed && I++ < SampleProfileMaxPropagateIterations) { 1524 Changed = propagateThroughEdges(F, true); 1525 } 1526 1527 // Generate MD_prof metadata for every branch instruction using the 1528 // edge weights computed during propagation. 1529 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); 1530 LLVMContext &Ctx = F.getContext(); 1531 MDBuilder MDB(Ctx); 1532 for (auto &BI : F) { 1533 BasicBlock *BB = &BI; 1534 1535 if (BlockWeights[BB]) { 1536 for (auto &I : BB->getInstList()) { 1537 if (!isa<CallInst>(I) && !isa<InvokeInst>(I)) 1538 continue; 1539 if (!cast<CallBase>(I).getCalledFunction()) { 1540 const DebugLoc &DLoc = I.getDebugLoc(); 1541 if (!DLoc) 1542 continue; 1543 const DILocation *DIL = DLoc; 1544 uint32_t LineOffset = FunctionSamples::getOffset(DIL); 1545 uint32_t Discriminator = DIL->getBaseDiscriminator(); 1546 1547 const FunctionSamples *FS = findFunctionSamples(I); 1548 if (!FS) 1549 continue; 1550 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator); 1551 if (!T || T.get().empty()) 1552 continue; 1553 SmallVector<InstrProfValueData, 2> SortedCallTargets = 1554 GetSortedValueDataFromCallTargets(T.get()); 1555 uint64_t Sum; 1556 findIndirectCallFunctionSamples(I, Sum); 1557 annotateValueSite(*I.getParent()->getParent()->getParent(), I, 1558 SortedCallTargets, Sum, IPVK_IndirectCallTarget, 1559 SortedCallTargets.size()); 1560 } else if (!isa<IntrinsicInst>(&I)) { 1561 I.setMetadata(LLVMContext::MD_prof, 1562 MDB.createBranchWeights( 1563 {static_cast<uint32_t>(BlockWeights[BB])})); 1564 } 1565 } 1566 } 1567 Instruction *TI = BB->getTerminator(); 1568 if (TI->getNumSuccessors() == 1) 1569 continue; 1570 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) 1571 continue; 1572 1573 DebugLoc BranchLoc = TI->getDebugLoc(); 1574 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line " 1575 << ((BranchLoc) ? Twine(BranchLoc.getLine()) 1576 : Twine("<UNKNOWN LOCATION>")) 1577 << ".\n"); 1578 SmallVector<uint32_t, 4> Weights; 1579 uint32_t MaxWeight = 0; 1580 Instruction *MaxDestInst; 1581 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { 1582 BasicBlock *Succ = TI->getSuccessor(I); 1583 Edge E = std::make_pair(BB, Succ); 1584 uint64_t Weight = EdgeWeights[E]; 1585 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); 1586 // Use uint32_t saturated arithmetic to adjust the incoming weights, 1587 // if needed. Sample counts in profiles are 64-bit unsigned values, 1588 // but internally branch weights are expressed as 32-bit values. 1589 if (Weight > std::numeric_limits<uint32_t>::max()) { 1590 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)"); 1591 Weight = std::numeric_limits<uint32_t>::max(); 1592 } 1593 // Weight is added by one to avoid propagation errors introduced by 1594 // 0 weights. 1595 Weights.push_back(static_cast<uint32_t>(Weight + 1)); 1596 if (Weight != 0) { 1597 if (Weight > MaxWeight) { 1598 MaxWeight = Weight; 1599 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime(); 1600 } 1601 } 1602 } 1603 1604 misexpect::verifyMisExpect(TI, Weights, TI->getContext()); 1605 1606 uint64_t TempWeight; 1607 // Only set weights if there is at least one non-zero weight. 1608 // In any other case, let the analyzer set weights. 1609 // Do not set weights if the weights are present. In ThinLTO, the profile 1610 // annotation is done twice. If the first annotation already set the 1611 // weights, the second pass does not need to set it. 1612 if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) { 1613 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); 1614 TI->setMetadata(LLVMContext::MD_prof, 1615 MDB.createBranchWeights(Weights)); 1616 ORE->emit([&]() { 1617 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst) 1618 << "most popular destination for conditional branches at " 1619 << ore::NV("CondBranchesLoc", BranchLoc); 1620 }); 1621 } else { 1622 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); 1623 } 1624 } 1625 } 1626 1627 /// Get the line number for the function header. 1628 /// 1629 /// This looks up function \p F in the current compilation unit and 1630 /// retrieves the line number where the function is defined. This is 1631 /// line 0 for all the samples read from the profile file. Every line 1632 /// number is relative to this line. 1633 /// 1634 /// \param F Function object to query. 1635 /// 1636 /// \returns the line number where \p F is defined. If it returns 0, 1637 /// it means that there is no debug information available for \p F. 1638 unsigned SampleProfileLoader::getFunctionLoc(Function &F) { 1639 if (DISubprogram *S = F.getSubprogram()) 1640 return S->getLine(); 1641 1642 if (NoWarnSampleUnused) 1643 return 0; 1644 1645 // If the start of \p F is missing, emit a diagnostic to inform the user 1646 // about the missed opportunity. 1647 F.getContext().diagnose(DiagnosticInfoSampleProfile( 1648 "No debug information found in function " + F.getName() + 1649 ": Function profile not used", 1650 DS_Warning)); 1651 return 0; 1652 } 1653 1654 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) { 1655 DT.reset(new DominatorTree); 1656 DT->recalculate(F); 1657 1658 PDT.reset(new PostDominatorTree(F)); 1659 1660 LI.reset(new LoopInfo); 1661 LI->analyze(*DT); 1662 } 1663 1664 /// Generate branch weight metadata for all branches in \p F. 1665 /// 1666 /// Branch weights are computed out of instruction samples using a 1667 /// propagation heuristic. Propagation proceeds in 3 phases: 1668 /// 1669 /// 1- Assignment of block weights. All the basic blocks in the function 1670 /// are initial assigned the same weight as their most frequently 1671 /// executed instruction. 1672 /// 1673 /// 2- Creation of equivalence classes. Since samples may be missing from 1674 /// blocks, we can fill in the gaps by setting the weights of all the 1675 /// blocks in the same equivalence class to the same weight. To compute 1676 /// the concept of equivalence, we use dominance and loop information. 1677 /// Two blocks B1 and B2 are in the same equivalence class if B1 1678 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 1679 /// 1680 /// 3- Propagation of block weights into edges. This uses a simple 1681 /// propagation heuristic. The following rules are applied to every 1682 /// block BB in the CFG: 1683 /// 1684 /// - If BB has a single predecessor/successor, then the weight 1685 /// of that edge is the weight of the block. 1686 /// 1687 /// - If all the edges are known except one, and the weight of the 1688 /// block is already known, the weight of the unknown edge will 1689 /// be the weight of the block minus the sum of all the known 1690 /// edges. If the sum of all the known edges is larger than BB's weight, 1691 /// we set the unknown edge weight to zero. 1692 /// 1693 /// - If there is a self-referential edge, and the weight of the block is 1694 /// known, the weight for that edge is set to the weight of the block 1695 /// minus the weight of the other incoming edges to that block (if 1696 /// known). 1697 /// 1698 /// Since this propagation is not guaranteed to finalize for every CFG, we 1699 /// only allow it to proceed for a limited number of iterations (controlled 1700 /// by -sample-profile-max-propagate-iterations). 1701 /// 1702 /// FIXME: Try to replace this propagation heuristic with a scheme 1703 /// that is guaranteed to finalize. A work-list approach similar to 1704 /// the standard value propagation algorithm used by SSA-CCP might 1705 /// work here. 1706 /// 1707 /// Once all the branch weights are computed, we emit the MD_prof 1708 /// metadata on BB using the computed values for each of its branches. 1709 /// 1710 /// \param F The function to query. 1711 /// 1712 /// \returns true if \p F was modified. Returns false, otherwise. 1713 bool SampleProfileLoader::emitAnnotations(Function &F) { 1714 bool Changed = false; 1715 1716 if (getFunctionLoc(F) == 0) 1717 return false; 1718 1719 LLVM_DEBUG(dbgs() << "Line number for the first instruction in " 1720 << F.getName() << ": " << getFunctionLoc(F) << "\n"); 1721 1722 DenseSet<GlobalValue::GUID> InlinedGUIDs; 1723 Changed |= inlineHotFunctions(F, InlinedGUIDs); 1724 1725 // Compute basic block weights. 1726 Changed |= computeBlockWeights(F); 1727 1728 if (Changed) { 1729 // Add an entry count to the function using the samples gathered at the 1730 // function entry. 1731 // Sets the GUIDs that are inlined in the profiled binary. This is used 1732 // for ThinLink to make correct liveness analysis, and also make the IR 1733 // match the profiled binary before annotation. 1734 F.setEntryCount( 1735 ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real), 1736 &InlinedGUIDs); 1737 1738 // Compute dominance and loop info needed for propagation. 1739 computeDominanceAndLoopInfo(F); 1740 1741 // Find equivalence classes. 1742 findEquivalenceClasses(F); 1743 1744 // Propagate weights to all edges. 1745 propagateWeights(F); 1746 } 1747 1748 // If coverage checking was requested, compute it now. 1749 if (SampleProfileRecordCoverage) { 1750 unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI); 1751 unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI); 1752 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); 1753 if (Coverage < SampleProfileRecordCoverage) { 1754 F.getContext().diagnose(DiagnosticInfoSampleProfile( 1755 F.getSubprogram()->getFilename(), getFunctionLoc(F), 1756 Twine(Used) + " of " + Twine(Total) + " available profile records (" + 1757 Twine(Coverage) + "%) were applied", 1758 DS_Warning)); 1759 } 1760 } 1761 1762 if (SampleProfileSampleCoverage) { 1763 uint64_t Used = CoverageTracker.getTotalUsedSamples(); 1764 uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI); 1765 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); 1766 if (Coverage < SampleProfileSampleCoverage) { 1767 F.getContext().diagnose(DiagnosticInfoSampleProfile( 1768 F.getSubprogram()->getFilename(), getFunctionLoc(F), 1769 Twine(Used) + " of " + Twine(Total) + " available profile samples (" + 1770 Twine(Coverage) + "%) were applied", 1771 DS_Warning)); 1772 } 1773 } 1774 return Changed; 1775 } 1776 1777 char SampleProfileLoaderLegacyPass::ID = 0; 1778 1779 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", 1780 "Sample Profile loader", false, false) 1781 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1782 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1783 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1784 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 1785 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile", 1786 "Sample Profile loader", false, false) 1787 1788 std::vector<Function *> 1789 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) { 1790 std::vector<Function *> FunctionOrderList; 1791 FunctionOrderList.reserve(M.size()); 1792 1793 if (!ProfileTopDownLoad || CG == nullptr) { 1794 for (Function &F : M) 1795 if (!F.isDeclaration()) 1796 FunctionOrderList.push_back(&F); 1797 return FunctionOrderList; 1798 } 1799 1800 assert(&CG->getModule() == &M); 1801 scc_iterator<CallGraph *> CGI = scc_begin(CG); 1802 while (!CGI.isAtEnd()) { 1803 for (CallGraphNode *node : *CGI) { 1804 auto F = node->getFunction(); 1805 if (F && !F->isDeclaration()) 1806 FunctionOrderList.push_back(F); 1807 } 1808 ++CGI; 1809 } 1810 1811 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end()); 1812 return FunctionOrderList; 1813 } 1814 1815 bool SampleProfileLoader::doInitialization(Module &M) { 1816 auto &Ctx = M.getContext(); 1817 1818 std::unique_ptr<SampleProfileReaderItaniumRemapper> RemapReader; 1819 auto ReaderOrErr = 1820 SampleProfileReader::create(Filename, Ctx, RemappingFilename); 1821 if (std::error_code EC = ReaderOrErr.getError()) { 1822 std::string Msg = "Could not open profile: " + EC.message(); 1823 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1824 return false; 1825 } 1826 Reader = std::move(ReaderOrErr.get()); 1827 Reader->collectFuncsFrom(M); 1828 ProfileIsValid = (Reader->read() == sampleprof_error::success); 1829 PSL = Reader->getProfileSymbolList(); 1830 1831 // While profile-sample-accurate is on, ignore symbol list. 1832 ProfAccForSymsInList = 1833 ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate; 1834 if (ProfAccForSymsInList) { 1835 NamesInProfile.clear(); 1836 if (auto NameTable = Reader->getNameTable()) 1837 NamesInProfile.insert(NameTable->begin(), NameTable->end()); 1838 } 1839 1840 return true; 1841 } 1842 1843 ModulePass *llvm::createSampleProfileLoaderPass() { 1844 return new SampleProfileLoaderLegacyPass(); 1845 } 1846 1847 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { 1848 return new SampleProfileLoaderLegacyPass(Name); 1849 } 1850 1851 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM, 1852 ProfileSummaryInfo *_PSI, CallGraph *CG) { 1853 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap); 1854 if (!ProfileIsValid) 1855 return false; 1856 1857 PSI = _PSI; 1858 if (M.getProfileSummary(/* IsCS */ false) == nullptr) 1859 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()), 1860 ProfileSummary::PSK_Sample); 1861 1862 // Compute the total number of samples collected in this profile. 1863 for (const auto &I : Reader->getProfiles()) 1864 TotalCollectedSamples += I.second.getTotalSamples(); 1865 1866 // Populate the symbol map. 1867 for (const auto &N_F : M.getValueSymbolTable()) { 1868 StringRef OrigName = N_F.getKey(); 1869 Function *F = dyn_cast<Function>(N_F.getValue()); 1870 if (F == nullptr) 1871 continue; 1872 SymbolMap[OrigName] = F; 1873 auto pos = OrigName.find('.'); 1874 if (pos != StringRef::npos) { 1875 StringRef NewName = OrigName.substr(0, pos); 1876 auto r = SymbolMap.insert(std::make_pair(NewName, F)); 1877 // Failiing to insert means there is already an entry in SymbolMap, 1878 // thus there are multiple functions that are mapped to the same 1879 // stripped name. In this case of name conflicting, set the value 1880 // to nullptr to avoid confusion. 1881 if (!r.second) 1882 r.first->second = nullptr; 1883 } 1884 } 1885 1886 bool retval = false; 1887 for (auto F : buildFunctionOrder(M, CG)) { 1888 assert(!F->isDeclaration()); 1889 clearFunctionData(); 1890 retval |= runOnFunction(*F, AM); 1891 } 1892 1893 // Account for cold calls not inlined.... 1894 for (const std::pair<Function *, NotInlinedProfileInfo> &pair : 1895 notInlinedCallInfo) 1896 updateProfileCallee(pair.first, pair.second.entryCount); 1897 1898 return retval; 1899 } 1900 1901 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) { 1902 ACT = &getAnalysis<AssumptionCacheTracker>(); 1903 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>(); 1904 TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>(); 1905 ProfileSummaryInfo *PSI = 1906 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 1907 return SampleLoader.runOnModule(M, nullptr, PSI, nullptr); 1908 } 1909 1910 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) { 1911 1912 DILocation2SampleMap.clear(); 1913 // By default the entry count is initialized to -1, which will be treated 1914 // conservatively by getEntryCount as the same as unknown (None). This is 1915 // to avoid newly added code to be treated as cold. If we have samples 1916 // this will be overwritten in emitAnnotations. 1917 uint64_t initialEntryCount = -1; 1918 1919 ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL; 1920 if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) { 1921 // initialize all the function entry counts to 0. It means all the 1922 // functions without profile will be regarded as cold. 1923 initialEntryCount = 0; 1924 // profile-sample-accurate is a user assertion which has a higher precedence 1925 // than symbol list. When profile-sample-accurate is on, ignore symbol list. 1926 ProfAccForSymsInList = false; 1927 } 1928 1929 // PSL -- profile symbol list include all the symbols in sampled binary. 1930 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat 1931 // old functions without samples being cold, without having to worry 1932 // about new and hot functions being mistakenly treated as cold. 1933 if (ProfAccForSymsInList) { 1934 // Initialize the entry count to 0 for functions in the list. 1935 if (PSL->contains(F.getName())) 1936 initialEntryCount = 0; 1937 1938 // Function in the symbol list but without sample will be regarded as 1939 // cold. To minimize the potential negative performance impact it could 1940 // have, we want to be a little conservative here saying if a function 1941 // shows up in the profile, no matter as outline function, inline instance 1942 // or call targets, treat the function as not being cold. This will handle 1943 // the cases such as most callsites of a function are inlined in sampled 1944 // binary but not inlined in current build (because of source code drift, 1945 // imprecise debug information, or the callsites are all cold individually 1946 // but not cold accumulatively...), so the outline function showing up as 1947 // cold in sampled binary will actually not be cold after current build. 1948 StringRef CanonName = FunctionSamples::getCanonicalFnName(F); 1949 if (NamesInProfile.count(CanonName)) 1950 initialEntryCount = -1; 1951 } 1952 1953 F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real)); 1954 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE; 1955 if (AM) { 1956 auto &FAM = 1957 AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent()) 1958 .getManager(); 1959 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1960 } else { 1961 OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F); 1962 ORE = OwnedORE.get(); 1963 } 1964 Samples = Reader->getSamplesFor(F); 1965 if (Samples && !Samples->empty()) 1966 return emitAnnotations(F); 1967 return false; 1968 } 1969 1970 PreservedAnalyses SampleProfileLoaderPass::run(Module &M, 1971 ModuleAnalysisManager &AM) { 1972 FunctionAnalysisManager &FAM = 1973 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1974 1975 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 1976 return FAM.getResult<AssumptionAnalysis>(F); 1977 }; 1978 auto GetTTI = [&](Function &F) -> TargetTransformInfo & { 1979 return FAM.getResult<TargetIRAnalysis>(F); 1980 }; 1981 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & { 1982 return FAM.getResult<TargetLibraryAnalysis>(F); 1983 }; 1984 1985 SampleProfileLoader SampleLoader( 1986 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName, 1987 ProfileRemappingFileName.empty() ? SampleProfileRemappingFile 1988 : ProfileRemappingFileName, 1989 IsThinLTOPreLink, GetAssumptionCache, GetTTI, GetTLI); 1990 1991 if (!SampleLoader.doInitialization(M)) 1992 return PreservedAnalyses::all(); 1993 1994 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M); 1995 CallGraph &CG = AM.getResult<CallGraphAnalysis>(M); 1996 if (!SampleLoader.runOnModule(M, &AM, PSI, &CG)) 1997 return PreservedAnalyses::all(); 1998 1999 return PreservedAnalyses::none(); 2000 } 2001