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