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