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