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