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