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/CallGraph.h"
40 #include "llvm/Analysis/CallGraphSCCPass.h"
41 #include "llvm/Analysis/InlineAdvisor.h"
42 #include "llvm/Analysis/InlineCost.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/PostDominators.h"
46 #include "llvm/Analysis/ProfileSummaryInfo.h"
47 #include "llvm/Analysis/ReplayInlineAdvisor.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/TargetTransformInfo.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/CFG.h"
52 #include "llvm/IR/DebugInfoMetadata.h"
53 #include "llvm/IR/DebugLoc.h"
54 #include "llvm/IR/DiagnosticInfo.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/GlobalValue.h"
58 #include "llvm/IR/InstrTypes.h"
59 #include "llvm/IR/Instruction.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/MDBuilder.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/PassManager.h"
66 #include "llvm/IR/ValueSymbolTable.h"
67 #include "llvm/InitializePasses.h"
68 #include "llvm/Pass.h"
69 #include "llvm/ProfileData/InstrProf.h"
70 #include "llvm/ProfileData/SampleProf.h"
71 #include "llvm/ProfileData/SampleProfReader.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/ErrorOr.h"
77 #include "llvm/Support/GenericDomTree.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Transforms/IPO.h"
80 #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
81 #include "llvm/Transforms/IPO/SampleContextTracker.h"
82 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
83 #include "llvm/Transforms/Instrumentation.h"
84 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
85 #include "llvm/Transforms/Utils/Cloning.h"
86 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
87 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstdint>
91 #include <functional>
92 #include <limits>
93 #include <map>
94 #include <memory>
95 #include <queue>
96 #include <string>
97 #include <system_error>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 using namespace sampleprof;
103 using namespace llvm::sampleprofutil;
104 using ProfileCount = Function::ProfileCount;
105 #define DEBUG_TYPE "sample-profile"
106 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
107 
108 STATISTIC(NumCSInlined,
109           "Number of functions inlined with context sensitive profile");
110 STATISTIC(NumCSNotInlined,
111           "Number of functions not inlined with context sensitive profile");
112 STATISTIC(NumMismatchedProfile,
113           "Number of functions with CFG mismatched profile");
114 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
115 STATISTIC(NumDuplicatedInlinesite,
116           "Number of inlined callsites with a partial distribution factor");
117 
118 STATISTIC(NumCSInlinedHitMinLimit,
119           "Number of functions with FDO inline stopped due to min size limit");
120 STATISTIC(NumCSInlinedHitMaxLimit,
121           "Number of functions with FDO inline stopped due to max size limit");
122 STATISTIC(
123     NumCSInlinedHitGrowthLimit,
124     "Number of functions with FDO inline stopped due to growth size limit");
125 
126 // Command line option to specify the file to read samples from. This is
127 // mainly used for debugging.
128 static cl::opt<std::string> SampleProfileFile(
129     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
130     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
131 
132 // The named file contains a set of transformations that may have been applied
133 // to the symbol names between the program from which the sample data was
134 // collected and the current program's symbols.
135 static cl::opt<std::string> SampleProfileRemappingFile(
136     "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
137     cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
138 
139 static cl::opt<bool> ProfileSampleAccurate(
140     "profile-sample-accurate", cl::Hidden, cl::init(false),
141     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
142              "callsite and function as having 0 samples. Otherwise, treat "
143              "un-sampled callsites and functions conservatively as unknown. "));
144 
145 static cl::opt<bool> ProfileAccurateForSymsInList(
146     "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
147     cl::init(true),
148     cl::desc("For symbols in profile symbol list, regard their profiles to "
149              "be accurate. It may be overriden by profile-sample-accurate. "));
150 
151 static cl::opt<bool> ProfileMergeInlinee(
152     "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
153     cl::desc("Merge past inlinee's profile to outline version if sample "
154              "profile loader decided not to inline a call site. It will "
155              "only be enabled when top-down order of profile loading is "
156              "enabled. "));
157 
158 static cl::opt<bool> ProfileTopDownLoad(
159     "sample-profile-top-down-load", cl::Hidden, cl::init(true),
160     cl::desc("Do profile annotation and inlining for functions in top-down "
161              "order of call graph during sample profile loading. It only "
162              "works for new pass manager. "));
163 
164 static cl::opt<bool>
165     UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
166                          cl::desc("Process functions in a top-down order "
167                                   "defined by the profiled call graph when "
168                                   "-sample-profile-top-down-load is on."));
169 
170 static cl::opt<bool> ProfileSizeInline(
171     "sample-profile-inline-size", cl::Hidden, cl::init(false),
172     cl::desc("Inline cold call sites in profile loader if it's beneficial "
173              "for code size."));
174 
175 cl::opt<int> ProfileInlineGrowthLimit(
176     "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
177     cl::desc("The size growth ratio limit for proirity-based sample profile "
178              "loader inlining."));
179 
180 cl::opt<int> ProfileInlineLimitMin(
181     "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
182     cl::desc("The lower bound of size growth limit for "
183              "proirity-based sample profile loader inlining."));
184 
185 cl::opt<int> ProfileInlineLimitMax(
186     "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
187     cl::desc("The upper bound of size growth limit for "
188              "proirity-based sample profile loader inlining."));
189 
190 cl::opt<int> SampleHotCallSiteThreshold(
191     "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
192     cl::desc("Hot callsite threshold for proirity-based sample profile loader "
193              "inlining."));
194 
195 cl::opt<int> SampleColdCallSiteThreshold(
196     "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
197     cl::desc("Threshold for inlining cold callsites"));
198 
199 static cl::opt<int> ProfileICPThreshold(
200     "sample-profile-icp-threshold", cl::Hidden, cl::init(5),
201     cl::desc(
202         "Relative hotness threshold for indirect "
203         "call promotion in proirity-based sample profile loader inlining."));
204 
205 static cl::opt<bool> CallsitePrioritizedInline(
206     "sample-profile-prioritized-inline", cl::Hidden, cl::ZeroOrMore,
207     cl::init(false),
208     cl::desc("Use call site prioritized inlining for sample profile loader."
209              "Currently only CSSPGO is supported."));
210 
211 static cl::opt<std::string> ProfileInlineReplayFile(
212     "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
213     cl::desc(
214         "Optimization remarks file containing inline remarks to be replayed "
215         "by inlining from sample profile loader."),
216     cl::Hidden);
217 
218 static cl::opt<unsigned>
219     MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
220                      cl::ZeroOrMore,
221                      cl::desc("Max number of promotions for a single indirect "
222                               "call callsite in sample profile loader"));
223 
224 static cl::opt<bool> OverwriteExistingWeights(
225     "overwrite-existing-weights", cl::Hidden, cl::init(false),
226     cl::desc("Ignore existing branch weights on IR and always overwrite."));
227 
228 namespace {
229 
230 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
231 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
232 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
233 using EdgeWeightMap = DenseMap<Edge, uint64_t>;
234 using BlockEdgeMap =
235     DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
236 
237 class GUIDToFuncNameMapper {
238 public:
239   GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
240                        DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
241       : CurrentReader(Reader), CurrentModule(M),
242         CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
243     if (!CurrentReader.useMD5())
244       return;
245 
246     for (const auto &F : CurrentModule) {
247       StringRef OrigName = F.getName();
248       CurrentGUIDToFuncNameMap.insert(
249           {Function::getGUID(OrigName), OrigName});
250 
251       // Local to global var promotion used by optimization like thinlto
252       // will rename the var and add suffix like ".llvm.xxx" to the
253       // original local name. In sample profile, the suffixes of function
254       // names are all stripped. Since it is possible that the mapper is
255       // built in post-thin-link phase and var promotion has been done,
256       // we need to add the substring of function name without the suffix
257       // into the GUIDToFuncNameMap.
258       StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
259       if (CanonName != OrigName)
260         CurrentGUIDToFuncNameMap.insert(
261             {Function::getGUID(CanonName), CanonName});
262     }
263 
264     // Update GUIDToFuncNameMap for each function including inlinees.
265     SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
266   }
267 
268   ~GUIDToFuncNameMapper() {
269     if (!CurrentReader.useMD5())
270       return;
271 
272     CurrentGUIDToFuncNameMap.clear();
273 
274     // Reset GUIDToFuncNameMap for of each function as they're no
275     // longer valid at this point.
276     SetGUIDToFuncNameMapForAll(nullptr);
277   }
278 
279 private:
280   void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
281     std::queue<FunctionSamples *> FSToUpdate;
282     for (auto &IFS : CurrentReader.getProfiles()) {
283       FSToUpdate.push(&IFS.second);
284     }
285 
286     while (!FSToUpdate.empty()) {
287       FunctionSamples *FS = FSToUpdate.front();
288       FSToUpdate.pop();
289       FS->GUIDToFuncNameMap = Map;
290       for (const auto &ICS : FS->getCallsiteSamples()) {
291         const FunctionSamplesMap &FSMap = ICS.second;
292         for (auto &IFS : FSMap) {
293           FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
294           FSToUpdate.push(&FS);
295         }
296       }
297     }
298   }
299 
300   SampleProfileReader &CurrentReader;
301   Module &CurrentModule;
302   DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
303 };
304 
305 // Inline candidate used by iterative callsite prioritized inliner
306 struct InlineCandidate {
307   CallBase *CallInstr;
308   const FunctionSamples *CalleeSamples;
309   // Prorated callsite count, which will be used to guide inlining. For example,
310   // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
311   // copies will get their own distribution factors and their prorated counts
312   // will be used to decide if they should be inlined independently.
313   uint64_t CallsiteCount;
314   // Call site distribution factor to prorate the profile samples for a
315   // duplicated callsite. Default value is 1.0.
316   float CallsiteDistribution;
317 };
318 
319 // Inline candidate comparer using call site weight
320 struct CandidateComparer {
321   bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
322     if (LHS.CallsiteCount != RHS.CallsiteCount)
323       return LHS.CallsiteCount < RHS.CallsiteCount;
324 
325     const FunctionSamples *LCS = LHS.CalleeSamples;
326     const FunctionSamples *RCS = RHS.CalleeSamples;
327     assert(LCS && RCS && "Expect non-null FunctionSamples");
328 
329     // Tie breaker using number of samples try to favor smaller functions first
330     if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
331       return LCS->getBodySamples().size() > RCS->getBodySamples().size();
332 
333     // Tie breaker using GUID so we have stable/deterministic inlining order
334     return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName());
335   }
336 };
337 
338 using CandidateQueue =
339     PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
340                   CandidateComparer>;
341 
342 /// Sample profile pass.
343 ///
344 /// This pass reads profile data from the file specified by
345 /// -sample-profile-file and annotates every affected function with the
346 /// profile information found in that file.
347 class SampleProfileLoader final
348     : public SampleProfileLoaderBaseImpl<BasicBlock> {
349 public:
350   SampleProfileLoader(
351       StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
352       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
353       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
354       std::function<const TargetLibraryInfo &(Function &)> GetTLI)
355       : SampleProfileLoaderBaseImpl(std::string(Name)),
356         GetAC(std::move(GetAssumptionCache)),
357         GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
358         RemappingFilename(std::string(RemapName)), LTOPhase(LTOPhase) {}
359 
360   bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
361   bool runOnModule(Module &M, ModuleAnalysisManager *AM,
362                    ProfileSummaryInfo *_PSI, CallGraph *CG);
363 
364 protected:
365   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
366   bool emitAnnotations(Function &F);
367   ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
368   ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
369   const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
370   const FunctionSamples *
371   findFunctionSamples(const Instruction &I) const override;
372   std::vector<const FunctionSamples *>
373   findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
374   void findExternalInlineCandidate(const FunctionSamples *Samples,
375                                    DenseSet<GlobalValue::GUID> &InlinedGUIDs,
376                                    const StringMap<Function *> &SymbolMap,
377                                    uint64_t Threshold);
378   // Attempt to promote indirect call and also inline the promoted call
379   bool tryPromoteAndInlineCandidate(
380       Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
381       uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
382   bool inlineHotFunctions(Function &F,
383                           DenseSet<GlobalValue::GUID> &InlinedGUIDs);
384   InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
385   bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
386   bool
387   tryInlineCandidate(InlineCandidate &Candidate,
388                      SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
389   bool
390   inlineHotFunctionsWithPriority(Function &F,
391                                  DenseSet<GlobalValue::GUID> &InlinedGUIDs);
392   // Inline cold/small functions in addition to hot ones
393   bool shouldInlineColdCallee(CallBase &CallInst);
394   void emitOptimizationRemarksForInlineCandidates(
395       const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
396       bool Hot);
397   std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
398   std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG);
399   void generateMDProfMetadata(Function &F);
400 
401   /// Map from function name to Function *. Used to find the function from
402   /// the function name. If the function name contains suffix, additional
403   /// entry is added to map from the stripped name to the function if there
404   /// is one-to-one mapping.
405   StringMap<Function *> SymbolMap;
406 
407   std::function<AssumptionCache &(Function &)> GetAC;
408   std::function<TargetTransformInfo &(Function &)> GetTTI;
409   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
410 
411   /// Profile tracker for different context.
412   std::unique_ptr<SampleContextTracker> ContextTracker;
413 
414   /// Name of the profile remapping file to load.
415   std::string RemappingFilename;
416 
417   /// Flag indicating whether the profile input loaded successfully.
418   bool ProfileIsValid = false;
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     // The call to InlineFunction erases I, so we can't pass it here.
1180     emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost,
1181                     true, CSINLINE_DEBUG);
1182 
1183     // Now populate the list of newly exposed call sites.
1184     if (InlinedCallSites) {
1185       InlinedCallSites->clear();
1186       for (auto &I : IFI.InlinedCallSites)
1187         InlinedCallSites->push_back(I);
1188     }
1189 
1190     if (ProfileIsCS)
1191       ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1192     ++NumCSInlined;
1193 
1194     // Prorate inlined probes for a duplicated inlining callsite which probably
1195     // has a distribution less than 100%. Samples for an inlinee should be
1196     // distributed among the copies of the original callsite based on each
1197     // callsite's distribution factor for counts accuracy. Note that an inlined
1198     // probe may come with its own distribution factor if it has been duplicated
1199     // in the inlinee body. The two factor are multiplied to reflect the
1200     // aggregation of duplication.
1201     if (Candidate.CallsiteDistribution < 1) {
1202       for (auto &I : IFI.InlinedCallSites) {
1203         if (Optional<PseudoProbe> Probe = extractProbe(*I))
1204           setProbeDistributionFactor(*I, Probe->Factor *
1205                                              Candidate.CallsiteDistribution);
1206       }
1207       NumDuplicatedInlinesite++;
1208     }
1209 
1210     return true;
1211   }
1212   return false;
1213 }
1214 
1215 bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1216                                              CallBase *CB) {
1217   assert(CB && "Expect non-null call instruction");
1218 
1219   if (isa<IntrinsicInst>(CB))
1220     return false;
1221 
1222   // Find the callee's profile. For indirect call, find hottest target profile.
1223   const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1224   if (!CalleeSamples)
1225     return false;
1226 
1227   float Factor = 1.0;
1228   if (Optional<PseudoProbe> Probe = extractProbe(*CB))
1229     Factor = Probe->Factor;
1230 
1231   uint64_t CallsiteCount = 0;
1232   ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent());
1233   if (Weight)
1234     CallsiteCount = Weight.get();
1235   if (CalleeSamples)
1236     CallsiteCount = std::max(
1237         CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor));
1238 
1239   *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1240   return true;
1241 }
1242 
1243 InlineCost
1244 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1245   std::unique_ptr<InlineAdvice> Advice = nullptr;
1246   if (ExternalInlineAdvisor) {
1247     Advice = ExternalInlineAdvisor->getAdvice(*Candidate.CallInstr);
1248     if (!Advice->isInliningRecommended()) {
1249       Advice->recordUnattemptedInlining();
1250       return InlineCost::getNever("not previously inlined");
1251     }
1252     Advice->recordInlining();
1253     return InlineCost::getAlways("previously inlined");
1254   }
1255 
1256   // Adjust threshold based on call site hotness, only do this for callsite
1257   // prioritized inliner because otherwise cost-benefit check is done earlier.
1258   int SampleThreshold = SampleColdCallSiteThreshold;
1259   if (CallsitePrioritizedInline) {
1260     if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1261       SampleThreshold = SampleHotCallSiteThreshold;
1262     else if (!ProfileSizeInline)
1263       return InlineCost::getNever("cold callsite");
1264   }
1265 
1266   Function *Callee = Candidate.CallInstr->getCalledFunction();
1267   assert(Callee && "Expect a definition for inline candidate of direct call");
1268 
1269   InlineParams Params = getInlineParams();
1270   Params.ComputeFullInlineCost = true;
1271   // Checks if there is anything in the reachable portion of the callee at
1272   // this callsite that makes this inlining potentially illegal. Need to
1273   // set ComputeFullInlineCost, otherwise getInlineCost may return early
1274   // when cost exceeds threshold without checking all IRs in the callee.
1275   // The acutal cost does not matter because we only checks isNever() to
1276   // see if it is legal to inline the callsite.
1277   InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1278                                   GetTTI(*Callee), GetAC, GetTLI);
1279 
1280   // Honor always inline and never inline from call analyzer
1281   if (Cost.isNever() || Cost.isAlways())
1282     return Cost;
1283 
1284   // For old FDO inliner, we inline the call site as long as cost is not
1285   // "Never". The cost-benefit check is done earlier.
1286   if (!CallsitePrioritizedInline) {
1287     return InlineCost::get(Cost.getCost(), INT_MAX);
1288   }
1289 
1290   // Otherwise only use the cost from call analyzer, but overwite threshold with
1291   // Sample PGO threshold.
1292   return InlineCost::get(Cost.getCost(), SampleThreshold);
1293 }
1294 
1295 bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1296     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1297   assert(ProfileIsCS && "Prioritiy based inliner only works with CSSPGO now");
1298 
1299   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1300   // Profile symbol list is ignored when profile-sample-accurate is on.
1301   assert((!ProfAccForSymsInList ||
1302           (!ProfileSampleAccurate &&
1303            !F.hasFnAttribute("profile-sample-accurate"))) &&
1304          "ProfAccForSymsInList should be false when profile-sample-accurate "
1305          "is enabled");
1306 
1307   // Populating worklist with initial call sites from root inliner, along
1308   // with call site weights.
1309   CandidateQueue CQueue;
1310   InlineCandidate NewCandidate;
1311   for (auto &BB : F) {
1312     for (auto &I : BB.getInstList()) {
1313       auto *CB = dyn_cast<CallBase>(&I);
1314       if (!CB)
1315         continue;
1316       if (getInlineCandidate(&NewCandidate, CB))
1317         CQueue.push(NewCandidate);
1318     }
1319   }
1320 
1321   // Cap the size growth from profile guided inlining. This is needed even
1322   // though cost of each inline candidate already accounts for callee size,
1323   // because with top-down inlining, we can grow inliner size significantly
1324   // with large number of smaller inlinees each pass the cost check.
1325   assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
1326          "Max inline size limit should not be smaller than min inline size "
1327          "limit.");
1328   unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
1329   SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
1330   SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
1331   if (ExternalInlineAdvisor)
1332     SizeLimit = std::numeric_limits<unsigned>::max();
1333 
1334   // Perform iterative BFS call site prioritized inlining
1335   bool Changed = false;
1336   while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1337     InlineCandidate Candidate = CQueue.top();
1338     CQueue.pop();
1339     CallBase *I = Candidate.CallInstr;
1340     Function *CalledFunction = I->getCalledFunction();
1341 
1342     if (CalledFunction == &F)
1343       continue;
1344     if (I->isIndirectCall()) {
1345       uint64_t Sum = 0;
1346       auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1347       uint64_t SumOrigin = Sum;
1348       Sum *= Candidate.CallsiteDistribution;
1349       for (const auto *FS : CalleeSamples) {
1350         // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1351         if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1352           findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap,
1353                                       PSI->getOrCompHotCountThreshold());
1354           continue;
1355         }
1356         uint64_t EntryCountDistributed =
1357             FS->getEntrySamples() * Candidate.CallsiteDistribution;
1358         // In addition to regular inline cost check, we also need to make sure
1359         // ICP isn't introducing excessive speculative checks even if individual
1360         // target looks beneficial to promote and inline. That means we should
1361         // only do ICP when there's a small number dominant targets.
1362         if (EntryCountDistributed < SumOrigin / ProfileICPThreshold)
1363           break;
1364         // TODO: Fix CallAnalyzer to handle all indirect calls.
1365         // For indirect call, we don't run CallAnalyzer to get InlineCost
1366         // before actual inlining. This is because we could see two different
1367         // types from the same definition, which makes CallAnalyzer choke as
1368         // it's expecting matching parameter type on both caller and callee
1369         // side. See example from PR18962 for the triggering cases (the bug was
1370         // fixed, but we generate different types).
1371         if (!PSI->isHotCount(EntryCountDistributed))
1372           break;
1373         SmallVector<CallBase *, 8> InlinedCallSites;
1374         // Attach function profile for promoted indirect callee, and update
1375         // call site count for the promoted inline candidate too.
1376         Candidate = {I, FS, EntryCountDistributed,
1377                      Candidate.CallsiteDistribution};
1378         if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1379                                          &InlinedCallSites)) {
1380           for (auto *CB : InlinedCallSites) {
1381             if (getInlineCandidate(&NewCandidate, CB))
1382               CQueue.emplace(NewCandidate);
1383           }
1384           Changed = true;
1385         }
1386       }
1387     } else if (CalledFunction && CalledFunction->getSubprogram() &&
1388                !CalledFunction->isDeclaration()) {
1389       SmallVector<CallBase *, 8> InlinedCallSites;
1390       if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1391         for (auto *CB : InlinedCallSites) {
1392           if (getInlineCandidate(&NewCandidate, CB))
1393             CQueue.emplace(NewCandidate);
1394         }
1395         Changed = true;
1396       }
1397     } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1398       findExternalInlineCandidate(Candidate.CalleeSamples, InlinedGUIDs,
1399                                   SymbolMap, PSI->getOrCompHotCountThreshold());
1400     }
1401   }
1402 
1403   if (!CQueue.empty()) {
1404     if (SizeLimit == (unsigned)ProfileInlineLimitMax)
1405       ++NumCSInlinedHitMaxLimit;
1406     else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
1407       ++NumCSInlinedHitMinLimit;
1408     else
1409       ++NumCSInlinedHitGrowthLimit;
1410   }
1411 
1412   return Changed;
1413 }
1414 
1415 /// Returns the sorted CallTargetMap \p M by count in descending order.
1416 static SmallVector<InstrProfValueData, 2>
1417 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
1418   SmallVector<InstrProfValueData, 2> R;
1419   for (const auto &I : SampleRecord::SortCallTargets(M)) {
1420     R.emplace_back(
1421         InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
1422   }
1423   return R;
1424 }
1425 
1426 // Generate MD_prof metadata for every branch instruction using the
1427 // edge weights computed during propagation.
1428 void SampleProfileLoader::generateMDProfMetadata(Function &F) {
1429   // Generate MD_prof metadata for every branch instruction using the
1430   // edge weights computed during propagation.
1431   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1432   LLVMContext &Ctx = F.getContext();
1433   MDBuilder MDB(Ctx);
1434   for (auto &BI : F) {
1435     BasicBlock *BB = &BI;
1436 
1437     if (BlockWeights[BB]) {
1438       for (auto &I : BB->getInstList()) {
1439         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1440           continue;
1441         if (!cast<CallBase>(I).getCalledFunction()) {
1442           const DebugLoc &DLoc = I.getDebugLoc();
1443           if (!DLoc)
1444             continue;
1445           const DILocation *DIL = DLoc;
1446           const FunctionSamples *FS = findFunctionSamples(I);
1447           if (!FS)
1448             continue;
1449           auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1450           auto T = FS->findCallTargetMapAt(CallSite);
1451           if (!T || T.get().empty())
1452             continue;
1453           if (FunctionSamples::ProfileIsProbeBased) {
1454             // Prorate the callsite counts based on the pre-ICP distribution
1455             // factor to reflect what is already done to the callsite before
1456             // ICP, such as calliste cloning.
1457             if (Optional<PseudoProbe> Probe = extractProbe(I)) {
1458               if (Probe->Factor < 1)
1459                 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1460             }
1461           }
1462           SmallVector<InstrProfValueData, 2> SortedCallTargets =
1463               GetSortedValueDataFromCallTargets(T.get());
1464           uint64_t Sum = 0;
1465           for (const auto &C : T.get())
1466             Sum += C.second;
1467           // With CSSPGO all indirect call targets are counted torwards the
1468           // original indirect call site in the profile, including both
1469           // inlined and non-inlined targets.
1470           if (!FunctionSamples::ProfileIsCS) {
1471             if (const FunctionSamplesMap *M =
1472                     FS->findFunctionSamplesMapAt(CallSite)) {
1473               for (const auto &NameFS : *M)
1474                 Sum += NameFS.second.getEntrySamples();
1475             }
1476           }
1477           if (Sum)
1478             updateIDTMetaData(I, SortedCallTargets, Sum);
1479           else if (OverwriteExistingWeights)
1480             I.setMetadata(LLVMContext::MD_prof, nullptr);
1481         } else if (!isa<IntrinsicInst>(&I)) {
1482           I.setMetadata(LLVMContext::MD_prof,
1483                         MDB.createBranchWeights(
1484                             {static_cast<uint32_t>(BlockWeights[BB])}));
1485         }
1486       }
1487     } else if (OverwriteExistingWeights) {
1488       // Set profile metadata (possibly annotated by LTO prelink) to zero or
1489       // clear it for cold code.
1490       for (auto &I : BB->getInstList()) {
1491         if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1492           if (cast<CallBase>(I).isIndirectCall())
1493             I.setMetadata(LLVMContext::MD_prof, nullptr);
1494           else
1495             I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(0));
1496         }
1497       }
1498     }
1499 
1500     Instruction *TI = BB->getTerminator();
1501     if (TI->getNumSuccessors() == 1)
1502       continue;
1503     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) &&
1504         !isa<IndirectBrInst>(TI))
1505       continue;
1506 
1507     DebugLoc BranchLoc = TI->getDebugLoc();
1508     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1509                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
1510                                       : Twine("<UNKNOWN LOCATION>"))
1511                       << ".\n");
1512     SmallVector<uint32_t, 4> Weights;
1513     uint32_t MaxWeight = 0;
1514     Instruction *MaxDestInst;
1515     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1516       BasicBlock *Succ = TI->getSuccessor(I);
1517       Edge E = std::make_pair(BB, Succ);
1518       uint64_t Weight = EdgeWeights[E];
1519       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1520       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1521       // if needed. Sample counts in profiles are 64-bit unsigned values,
1522       // but internally branch weights are expressed as 32-bit values.
1523       if (Weight > std::numeric_limits<uint32_t>::max()) {
1524         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1525         Weight = std::numeric_limits<uint32_t>::max();
1526       }
1527       // Weight is added by one to avoid propagation errors introduced by
1528       // 0 weights.
1529       Weights.push_back(static_cast<uint32_t>(Weight + 1));
1530       if (Weight != 0) {
1531         if (Weight > MaxWeight) {
1532           MaxWeight = Weight;
1533           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1534         }
1535       }
1536     }
1537 
1538     uint64_t TempWeight;
1539     // Only set weights if there is at least one non-zero weight.
1540     // In any other case, let the analyzer set weights.
1541     // Do not set weights if the weights are present unless under
1542     // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1543     // twice. If the first annotation already set the weights, the second pass
1544     // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1545     // weight should have their existing metadata (possibly annotated by LTO
1546     // prelink) cleared.
1547     if (MaxWeight > 0 &&
1548         (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) {
1549       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1550       TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1551       ORE->emit([&]() {
1552         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1553                << "most popular destination for conditional branches at "
1554                << ore::NV("CondBranchesLoc", BranchLoc);
1555       });
1556     } else {
1557       if (OverwriteExistingWeights) {
1558         TI->setMetadata(LLVMContext::MD_prof, nullptr);
1559         LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1560       } else {
1561         LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1562       }
1563     }
1564   }
1565 }
1566 
1567 /// Once all the branch weights are computed, we emit the MD_prof
1568 /// metadata on BB using the computed values for each of its branches.
1569 ///
1570 /// \param F The function to query.
1571 ///
1572 /// \returns true if \p F was modified. Returns false, otherwise.
1573 bool SampleProfileLoader::emitAnnotations(Function &F) {
1574   bool Changed = false;
1575 
1576   if (FunctionSamples::ProfileIsProbeBased) {
1577     if (!ProbeManager->profileIsValid(F, *Samples)) {
1578       LLVM_DEBUG(
1579           dbgs() << "Profile is invalid due to CFG mismatch for Function "
1580                  << F.getName());
1581       ++NumMismatchedProfile;
1582       return false;
1583     }
1584     ++NumMatchedProfile;
1585   } else {
1586     if (getFunctionLoc(F) == 0)
1587       return false;
1588 
1589     LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1590                       << F.getName() << ": " << getFunctionLoc(F) << "\n");
1591   }
1592 
1593   DenseSet<GlobalValue::GUID> InlinedGUIDs;
1594   if (ProfileIsCS && CallsitePrioritizedInline)
1595     Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1596   else
1597     Changed |= inlineHotFunctions(F, InlinedGUIDs);
1598 
1599   Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
1600 
1601   if (Changed)
1602     generateMDProfMetadata(F);
1603 
1604   emitCoverageRemarks(F);
1605   return Changed;
1606 }
1607 
1608 char SampleProfileLoaderLegacyPass::ID = 0;
1609 
1610 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1611                       "Sample Profile loader", false, false)
1612 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1613 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1614 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1615 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1616 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1617                     "Sample Profile loader", false, false)
1618 
1619 std::unique_ptr<ProfiledCallGraph>
1620 SampleProfileLoader::buildProfiledCallGraph(CallGraph &CG) {
1621   std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1622   if (ProfileIsCS)
1623     ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1624   else
1625     ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1626 
1627   // Add all functions into the profiled call graph even if they are not in
1628   // the profile. This makes sure functions missing from the profile still
1629   // gets a chance to be processed.
1630   for (auto &Node : CG) {
1631     const auto *F = Node.first;
1632     if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile"))
1633       continue;
1634     ProfiledCG->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F));
1635   }
1636 
1637   return ProfiledCG;
1638 }
1639 
1640 std::vector<Function *>
1641 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1642   std::vector<Function *> FunctionOrderList;
1643   FunctionOrderList.reserve(M.size());
1644 
1645   if (!ProfileTopDownLoad && UseProfiledCallGraph)
1646     errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1647               "together with -sample-profile-top-down-load.\n";
1648 
1649   if (!ProfileTopDownLoad || CG == nullptr) {
1650     if (ProfileMergeInlinee) {
1651       // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1652       // because the profile for a function may be used for the profile
1653       // annotation of its outline copy before the profile merging of its
1654       // non-inlined inline instances, and that is not the way how
1655       // ProfileMergeInlinee is supposed to work.
1656       ProfileMergeInlinee = false;
1657     }
1658 
1659     for (Function &F : M)
1660       if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1661         FunctionOrderList.push_back(&F);
1662     return FunctionOrderList;
1663   }
1664 
1665   assert(&CG->getModule() == &M);
1666 
1667   if (UseProfiledCallGraph ||
1668       (ProfileIsCS && !UseProfiledCallGraph.getNumOccurrences())) {
1669     // Use profiled call edges to augment the top-down order. There are cases
1670     // that the top-down order computed based on the static call graph doesn't
1671     // reflect real execution order. For example
1672     //
1673     // 1. Incomplete static call graph due to unknown indirect call targets.
1674     //    Adjusting the order by considering indirect call edges from the
1675     //    profile can enable the inlining of indirect call targets by allowing
1676     //    the caller processed before them.
1677     // 2. Mutual call edges in an SCC. The static processing order computed for
1678     //    an SCC may not reflect the call contexts in the context-sensitive
1679     //    profile, thus may cause potential inlining to be overlooked. The
1680     //    function order in one SCC is being adjusted to a top-down order based
1681     //    on the profile to favor more inlining. This is only a problem with CS
1682     //    profile.
1683     // 3. Transitive indirect call edges due to inlining. When a callee function
1684     //    (say B) is inlined into into a caller function (say A) in LTO prelink,
1685     //    every call edge originated from the callee B will be transferred to
1686     //    the caller A. If any transferred edge (say A->C) is indirect, the
1687     //    original profiled indirect edge B->C, even if considered, would not
1688     //    enforce a top-down order from the caller A to the potential indirect
1689     //    call target C in LTO postlink since the inlined callee B is gone from
1690     //    the static call graph.
1691     // 4. #3 can happen even for direct call targets, due to functions defined
1692     //    in header files. A header function (say A), when included into source
1693     //    files, is defined multiple times but only one definition survives due
1694     //    to ODR. Therefore, the LTO prelink inlining done on those dropped
1695     //    definitions can be useless based on a local file scope. More
1696     //    importantly, the inlinee (say B), once fully inlined to a
1697     //    to-be-dropped A, will have no profile to consume when its outlined
1698     //    version is compiled. This can lead to a profile-less prelink
1699     //    compilation for the outlined version of B which may be called from
1700     //    external modules. while this isn't easy to fix, we rely on the
1701     //    postlink AutoFDO pipeline to optimize B. Since the survived copy of
1702     //    the A can be inlined in its local scope in prelink, it may not exist
1703     //    in the merged IR in postlink, and we'll need the profiled call edges
1704     //    to enforce a top-down order for the rest of the functions.
1705     //
1706     // Considering those cases, a profiled call graph completely independent of
1707     // the static call graph is constructed based on profile data, where
1708     // function objects are not even needed to handle case #3 and case 4.
1709     //
1710     // Note that static callgraph edges are completely ignored since they
1711     // can be conflicting with profiled edges for cyclic SCCs and may result in
1712     // an SCC order incompatible with profile-defined one. Using strictly
1713     // profile order ensures a maximum inlining experience. On the other hand,
1714     // static call edges are not so important when they don't correspond to a
1715     // context in the profile.
1716 
1717     std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(*CG);
1718     scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1719     while (!CGI.isAtEnd()) {
1720       for (ProfiledCallGraphNode *Node : *CGI) {
1721         Function *F = SymbolMap.lookup(Node->Name);
1722         if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1723           FunctionOrderList.push_back(F);
1724       }
1725       ++CGI;
1726     }
1727   } else {
1728     scc_iterator<CallGraph *> CGI = scc_begin(CG);
1729     while (!CGI.isAtEnd()) {
1730       for (CallGraphNode *Node : *CGI) {
1731         auto *F = Node->getFunction();
1732         if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1733           FunctionOrderList.push_back(F);
1734       }
1735       ++CGI;
1736     }
1737   }
1738 
1739   LLVM_DEBUG({
1740     dbgs() << "Function processing order:\n";
1741     for (auto F : reverse(FunctionOrderList)) {
1742       dbgs() << F->getName() << "\n";
1743     }
1744   });
1745 
1746   std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1747   return FunctionOrderList;
1748 }
1749 
1750 bool SampleProfileLoader::doInitialization(Module &M,
1751                                            FunctionAnalysisManager *FAM) {
1752   auto &Ctx = M.getContext();
1753 
1754   auto ReaderOrErr = SampleProfileReader::create(
1755       Filename, Ctx, FSDiscriminatorPass::Base, RemappingFilename);
1756   if (std::error_code EC = ReaderOrErr.getError()) {
1757     std::string Msg = "Could not open profile: " + EC.message();
1758     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1759     return false;
1760   }
1761   Reader = std::move(ReaderOrErr.get());
1762   Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1763   // set module before reading the profile so reader may be able to only
1764   // read the function profiles which are used by the current module.
1765   Reader->setModule(&M);
1766   if (std::error_code EC = Reader->read()) {
1767     std::string Msg = "profile reading failed: " + EC.message();
1768     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1769     return false;
1770   }
1771 
1772   PSL = Reader->getProfileSymbolList();
1773 
1774   // While profile-sample-accurate is on, ignore symbol list.
1775   ProfAccForSymsInList =
1776       ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1777   if (ProfAccForSymsInList) {
1778     NamesInProfile.clear();
1779     if (auto NameTable = Reader->getNameTable())
1780       NamesInProfile.insert(NameTable->begin(), NameTable->end());
1781     CoverageTracker.setProfAccForSymsInList(true);
1782   }
1783 
1784   if (FAM && !ProfileInlineReplayFile.empty()) {
1785     ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>(
1786         M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile,
1787         /*EmitRemarks=*/false);
1788     if (!ExternalInlineAdvisor->areReplayRemarksLoaded())
1789       ExternalInlineAdvisor.reset();
1790   }
1791 
1792   // Apply tweaks if context-sensitive profile is available.
1793   if (Reader->profileIsCS()) {
1794     ProfileIsCS = true;
1795     FunctionSamples::ProfileIsCS = true;
1796 
1797     // Enable priority-base inliner and size inline by default for CSSPGO.
1798     if (!ProfileSizeInline.getNumOccurrences())
1799       ProfileSizeInline = true;
1800     if (!CallsitePrioritizedInline.getNumOccurrences())
1801       CallsitePrioritizedInline = true;
1802 
1803     // Tracker for profiles under different context
1804     ContextTracker =
1805         std::make_unique<SampleContextTracker>(Reader->getProfiles());
1806   }
1807 
1808   // Load pseudo probe descriptors for probe-based function samples.
1809   if (Reader->profileIsProbeBased()) {
1810     ProbeManager = std::make_unique<PseudoProbeManager>(M);
1811     if (!ProbeManager->moduleIsProbed(M)) {
1812       const char *Msg =
1813           "Pseudo-probe-based profile requires SampleProfileProbePass";
1814       Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1815       return false;
1816     }
1817   }
1818 
1819   return true;
1820 }
1821 
1822 ModulePass *llvm::createSampleProfileLoaderPass() {
1823   return new SampleProfileLoaderLegacyPass();
1824 }
1825 
1826 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1827   return new SampleProfileLoaderLegacyPass(Name);
1828 }
1829 
1830 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1831                                       ProfileSummaryInfo *_PSI, CallGraph *CG) {
1832   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1833 
1834   PSI = _PSI;
1835   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
1836     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
1837                         ProfileSummary::PSK_Sample);
1838     PSI->refresh();
1839   }
1840   // Compute the total number of samples collected in this profile.
1841   for (const auto &I : Reader->getProfiles())
1842     TotalCollectedSamples += I.second.getTotalSamples();
1843 
1844   auto Remapper = Reader->getRemapper();
1845   // Populate the symbol map.
1846   for (const auto &N_F : M.getValueSymbolTable()) {
1847     StringRef OrigName = N_F.getKey();
1848     Function *F = dyn_cast<Function>(N_F.getValue());
1849     if (F == nullptr || OrigName.empty())
1850       continue;
1851     SymbolMap[OrigName] = F;
1852     StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
1853     if (OrigName != NewName && !NewName.empty()) {
1854       auto r = SymbolMap.insert(std::make_pair(NewName, F));
1855       // Failiing to insert means there is already an entry in SymbolMap,
1856       // thus there are multiple functions that are mapped to the same
1857       // stripped name. In this case of name conflicting, set the value
1858       // to nullptr to avoid confusion.
1859       if (!r.second)
1860         r.first->second = nullptr;
1861       OrigName = NewName;
1862     }
1863     // Insert the remapped names into SymbolMap.
1864     if (Remapper) {
1865       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
1866         if (*MapName != OrigName && !MapName->empty())
1867           SymbolMap.insert(std::make_pair(*MapName, F));
1868       }
1869     }
1870   }
1871   assert(SymbolMap.count(StringRef()) == 0 &&
1872          "No empty StringRef should be added in SymbolMap");
1873 
1874   bool retval = false;
1875   for (auto F : buildFunctionOrder(M, CG)) {
1876     assert(!F->isDeclaration());
1877     clearFunctionData();
1878     retval |= runOnFunction(*F, AM);
1879   }
1880 
1881   // Account for cold calls not inlined....
1882   if (!ProfileIsCS)
1883     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
1884          notInlinedCallInfo)
1885       updateProfileCallee(pair.first, pair.second.entryCount);
1886 
1887   return retval;
1888 }
1889 
1890 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1891   ACT = &getAnalysis<AssumptionCacheTracker>();
1892   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1893   TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
1894   ProfileSummaryInfo *PSI =
1895       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1896   return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
1897 }
1898 
1899 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
1900   LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
1901   DILocation2SampleMap.clear();
1902   // By default the entry count is initialized to -1, which will be treated
1903   // conservatively by getEntryCount as the same as unknown (None). This is
1904   // to avoid newly added code to be treated as cold. If we have samples
1905   // this will be overwritten in emitAnnotations.
1906   uint64_t initialEntryCount = -1;
1907 
1908   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
1909   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
1910     // initialize all the function entry counts to 0. It means all the
1911     // functions without profile will be regarded as cold.
1912     initialEntryCount = 0;
1913     // profile-sample-accurate is a user assertion which has a higher precedence
1914     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
1915     ProfAccForSymsInList = false;
1916   }
1917   CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
1918 
1919   // PSL -- profile symbol list include all the symbols in sampled binary.
1920   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
1921   // old functions without samples being cold, without having to worry
1922   // about new and hot functions being mistakenly treated as cold.
1923   if (ProfAccForSymsInList) {
1924     // Initialize the entry count to 0 for functions in the list.
1925     if (PSL->contains(F.getName()))
1926       initialEntryCount = 0;
1927 
1928     // Function in the symbol list but without sample will be regarded as
1929     // cold. To minimize the potential negative performance impact it could
1930     // have, we want to be a little conservative here saying if a function
1931     // shows up in the profile, no matter as outline function, inline instance
1932     // or call targets, treat the function as not being cold. This will handle
1933     // the cases such as most callsites of a function are inlined in sampled
1934     // binary but not inlined in current build (because of source code drift,
1935     // imprecise debug information, or the callsites are all cold individually
1936     // but not cold accumulatively...), so the outline function showing up as
1937     // cold in sampled binary will actually not be cold after current build.
1938     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
1939     if (NamesInProfile.count(CanonName))
1940       initialEntryCount = -1;
1941   }
1942 
1943   // Initialize entry count when the function has no existing entry
1944   // count value.
1945   if (!F.getEntryCount().hasValue())
1946     F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
1947   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1948   if (AM) {
1949     auto &FAM =
1950         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1951             .getManager();
1952     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1953   } else {
1954     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
1955     ORE = OwnedORE.get();
1956   }
1957 
1958   if (ProfileIsCS)
1959     Samples = ContextTracker->getBaseSamplesFor(F);
1960   else
1961     Samples = Reader->getSamplesFor(F);
1962 
1963   if (Samples && !Samples->empty())
1964     return emitAnnotations(F);
1965   return false;
1966 }
1967 
1968 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1969                                                ModuleAnalysisManager &AM) {
1970   FunctionAnalysisManager &FAM =
1971       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1972 
1973   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1974     return FAM.getResult<AssumptionAnalysis>(F);
1975   };
1976   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1977     return FAM.getResult<TargetIRAnalysis>(F);
1978   };
1979   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
1980     return FAM.getResult<TargetLibraryAnalysis>(F);
1981   };
1982 
1983   SampleProfileLoader SampleLoader(
1984       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
1985       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
1986                                        : ProfileRemappingFileName,
1987       LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
1988 
1989   if (!SampleLoader.doInitialization(M, &FAM))
1990     return PreservedAnalyses::all();
1991 
1992   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1993   CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
1994   if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
1995     return PreservedAnalyses::all();
1996 
1997   return PreservedAnalyses::none();
1998 }
1999