1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SampleProfileLoader transformation. This pass
10 // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
11 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
12 // profile information in the given profile.
13 //
14 // This pass generates branch weight annotations on the IR:
15 //
16 // - prof: Represents branch weights. This annotation is added to branches
17 //      to indicate the weights of each edge coming out of the branch.
18 //      The weight of each edge is the weight of the target block for
19 //      that edge. The weight of a block B is computed as the maximum
20 //      number of samples found in B.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "llvm/Transforms/IPO/SampleProfile.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/None.h"
29 #include "llvm/ADT/PriorityQueue.h"
30 #include "llvm/ADT/SCCIterator.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/AssumptionCache.h"
39 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
40 #include "llvm/Analysis/CallGraph.h"
41 #include "llvm/Analysis/CallGraphSCCPass.h"
42 #include "llvm/Analysis/InlineAdvisor.h"
43 #include "llvm/Analysis/InlineCost.h"
44 #include "llvm/Analysis/LoopInfo.h"
45 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
46 #include "llvm/Analysis/PostDominators.h"
47 #include "llvm/Analysis/ProfileSummaryInfo.h"
48 #include "llvm/Analysis/ReplayInlineAdvisor.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/TargetTransformInfo.h"
51 #include "llvm/IR/BasicBlock.h"
52 #include "llvm/IR/CFG.h"
53 #include "llvm/IR/DebugInfoMetadata.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DiagnosticInfo.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/GlobalValue.h"
59 #include "llvm/IR/InstrTypes.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/MDBuilder.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/PassManager.h"
67 #include "llvm/IR/ValueSymbolTable.h"
68 #include "llvm/InitializePasses.h"
69 #include "llvm/Pass.h"
70 #include "llvm/ProfileData/InstrProf.h"
71 #include "llvm/ProfileData/SampleProf.h"
72 #include "llvm/ProfileData/SampleProfReader.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/ErrorHandling.h"
77 #include "llvm/Support/ErrorOr.h"
78 #include "llvm/Support/GenericDomTree.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Transforms/IPO.h"
81 #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
82 #include "llvm/Transforms/IPO/SampleContextTracker.h"
83 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
84 #include "llvm/Transforms/Instrumentation.h"
85 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
86 #include "llvm/Transforms/Utils/Cloning.h"
87 #include "llvm/Transforms/Utils/SampleProfileInference.h"
88 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
89 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <map>
96 #include <memory>
97 #include <queue>
98 #include <string>
99 #include <system_error>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace sampleprof;
105 using namespace llvm::sampleprofutil;
106 using ProfileCount = Function::ProfileCount;
107 #define DEBUG_TYPE "sample-profile"
108 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
109 
110 STATISTIC(NumCSInlined,
111           "Number of functions inlined with context sensitive profile");
112 STATISTIC(NumCSNotInlined,
113           "Number of functions not inlined with context sensitive profile");
114 STATISTIC(NumMismatchedProfile,
115           "Number of functions with CFG mismatched profile");
116 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
117 STATISTIC(NumDuplicatedInlinesite,
118           "Number of inlined callsites with a partial distribution factor");
119 
120 STATISTIC(NumCSInlinedHitMinLimit,
121           "Number of functions with FDO inline stopped due to min size limit");
122 STATISTIC(NumCSInlinedHitMaxLimit,
123           "Number of functions with FDO inline stopped due to max size limit");
124 STATISTIC(
125     NumCSInlinedHitGrowthLimit,
126     "Number of functions with FDO inline stopped due to growth size limit");
127 
128 // Command line option to specify the file to read samples from. This is
129 // mainly used for debugging.
130 static cl::opt<std::string> SampleProfileFile(
131     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
132     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
133 
134 // The named file contains a set of transformations that may have been applied
135 // to the symbol names between the program from which the sample data was
136 // collected and the current program's symbols.
137 static cl::opt<std::string> SampleProfileRemappingFile(
138     "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
139     cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
140 
141 static cl::opt<bool> ProfileSampleAccurate(
142     "profile-sample-accurate", cl::Hidden, cl::init(false),
143     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
144              "callsite and function as having 0 samples. Otherwise, treat "
145              "un-sampled callsites and functions conservatively as unknown. "));
146 
147 static cl::opt<bool> ProfileSampleBlockAccurate(
148     "profile-sample-block-accurate", cl::Hidden, cl::init(false),
149     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
150              "branches and calls as having 0 samples. Otherwise, treat "
151              "them conservatively as unknown. "));
152 
153 static cl::opt<bool> ProfileAccurateForSymsInList(
154     "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
155     cl::init(true),
156     cl::desc("For symbols in profile symbol list, regard their profiles to "
157              "be accurate. It may be overriden by profile-sample-accurate. "));
158 
159 static cl::opt<bool> ProfileMergeInlinee(
160     "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
161     cl::desc("Merge past inlinee's profile to outline version if sample "
162              "profile loader decided not to inline a call site. It will "
163              "only be enabled when top-down order of profile loading is "
164              "enabled. "));
165 
166 static cl::opt<bool> ProfileTopDownLoad(
167     "sample-profile-top-down-load", cl::Hidden, cl::init(true),
168     cl::desc("Do profile annotation and inlining for functions in top-down "
169              "order of call graph during sample profile loading. It only "
170              "works for new pass manager. "));
171 
172 static cl::opt<bool>
173     UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
174                          cl::desc("Process functions in a top-down order "
175                                   "defined by the profiled call graph when "
176                                   "-sample-profile-top-down-load is on."));
177 cl::opt<bool>
178     SortProfiledSCC("sort-profiled-scc-member", cl::init(true), cl::Hidden,
179                     cl::desc("Sort profiled recursion by edge weights."));
180 
181 static cl::opt<bool> ProfileSizeInline(
182     "sample-profile-inline-size", cl::Hidden, cl::init(false),
183     cl::desc("Inline cold call sites in profile loader if it's beneficial "
184              "for code size."));
185 
186 static cl::opt<bool> DisableSampleLoaderInlining(
187     "disable-sample-loader-inlining", cl::Hidden, cl::init(false),
188     cl::desc("If true, turn off inliner in sample profile loader. Used for "
189              "evaluation or debugging."));
190 
191 cl::opt<int> ProfileInlineGrowthLimit(
192     "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
193     cl::desc("The size growth ratio limit for proirity-based sample profile "
194              "loader inlining."));
195 
196 cl::opt<int> ProfileInlineLimitMin(
197     "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
198     cl::desc("The lower bound of size growth limit for "
199              "proirity-based sample profile loader inlining."));
200 
201 cl::opt<int> ProfileInlineLimitMax(
202     "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
203     cl::desc("The upper bound of size growth limit for "
204              "proirity-based sample profile loader inlining."));
205 
206 cl::opt<int> SampleHotCallSiteThreshold(
207     "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
208     cl::desc("Hot callsite threshold for proirity-based sample profile loader "
209              "inlining."));
210 
211 cl::opt<int> SampleColdCallSiteThreshold(
212     "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
213     cl::desc("Threshold for inlining cold callsites"));
214 
215 static cl::opt<unsigned> ProfileICPRelativeHotness(
216     "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25),
217     cl::desc(
218         "Relative hotness percentage threshold for indirect "
219         "call promotion in proirity-based sample profile loader inlining."));
220 
221 static cl::opt<unsigned> ProfileICPRelativeHotnessSkip(
222     "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1),
223     cl::desc(
224         "Skip relative hotness check for ICP up to given number of targets."));
225 
226 static cl::opt<bool> CallsitePrioritizedInline(
227     "sample-profile-prioritized-inline", cl::Hidden, cl::ZeroOrMore,
228     cl::init(false),
229     cl::desc("Use call site prioritized inlining for sample profile loader."
230              "Currently only CSSPGO is supported."));
231 
232 static cl::opt<bool> UsePreInlinerDecision(
233     "sample-profile-use-preinliner", cl::Hidden, cl::ZeroOrMore,
234     cl::init(false),
235     cl::desc("Use the preinliner decisions stored in profile context."));
236 
237 static cl::opt<bool> AllowRecursiveInline(
238     "sample-profile-recursive-inline", cl::Hidden, cl::ZeroOrMore,
239     cl::init(false),
240     cl::desc("Allow sample loader inliner to inline recursive calls."));
241 
242 static cl::opt<std::string> ProfileInlineReplayFile(
243     "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
244     cl::desc(
245         "Optimization remarks file containing inline remarks to be replayed "
246         "by inlining from sample profile loader."),
247     cl::Hidden);
248 
249 static cl::opt<ReplayInlinerSettings::Scope> ProfileInlineReplayScope(
250     "sample-profile-inline-replay-scope",
251     cl::init(ReplayInlinerSettings::Scope::Function),
252     cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function, "Function",
253                           "Replay on functions that have remarks associated "
254                           "with them (default)"),
255                clEnumValN(ReplayInlinerSettings::Scope::Module, "Module",
256                           "Replay on the entire module")),
257     cl::desc("Whether inline replay should be applied to the entire "
258              "Module or just the Functions (default) that are present as "
259              "callers in remarks during sample profile inlining."),
260     cl::Hidden);
261 
262 static cl::opt<ReplayInlinerSettings::Fallback> ProfileInlineReplayFallback(
263     "sample-profile-inline-replay-fallback",
264     cl::init(ReplayInlinerSettings::Fallback::Original),
265     cl::values(
266         clEnumValN(
267             ReplayInlinerSettings::Fallback::Original, "Original",
268             "All decisions not in replay send to original advisor (default)"),
269         clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline,
270                    "AlwaysInline", "All decisions not in replay are inlined"),
271         clEnumValN(ReplayInlinerSettings::Fallback::NeverInline, "NeverInline",
272                    "All decisions not in replay are not inlined")),
273     cl::desc("How sample profile inline replay treats sites that don't come "
274              "from the replay. Original: defers to original advisor, "
275              "AlwaysInline: inline all sites not in replay, NeverInline: "
276              "inline no sites not in replay"),
277     cl::Hidden);
278 
279 static cl::opt<CallSiteFormat::Format> ProfileInlineReplayFormat(
280     "sample-profile-inline-replay-format",
281     cl::init(CallSiteFormat::Format::LineColumnDiscriminator),
282     cl::values(
283         clEnumValN(CallSiteFormat::Format::Line, "Line", "<Line Number>"),
284         clEnumValN(CallSiteFormat::Format::LineColumn, "LineColumn",
285                    "<Line Number>:<Column Number>"),
286         clEnumValN(CallSiteFormat::Format::LineDiscriminator,
287                    "LineDiscriminator", "<Line Number>.<Discriminator>"),
288         clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator,
289                    "LineColumnDiscriminator",
290                    "<Line Number>:<Column Number>.<Discriminator> (default)")),
291     cl::desc("How sample profile inline replay file is formatted"), cl::Hidden);
292 
293 static cl::opt<unsigned>
294     MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
295                      cl::ZeroOrMore,
296                      cl::desc("Max number of promotions for a single indirect "
297                               "call callsite in sample profile loader"));
298 
299 static cl::opt<bool> OverwriteExistingWeights(
300     "overwrite-existing-weights", cl::Hidden, cl::init(false),
301     cl::desc("Ignore existing branch weights on IR and always overwrite."));
302 
303 extern cl::opt<bool> EnableExtTspBlockPlacement;
304 
305 namespace {
306 
307 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
308 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
309 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
310 using EdgeWeightMap = DenseMap<Edge, uint64_t>;
311 using BlockEdgeMap =
312     DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
313 
314 class GUIDToFuncNameMapper {
315 public:
316   GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
317                        DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
318       : CurrentReader(Reader), CurrentModule(M),
319         CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
320     if (!CurrentReader.useMD5())
321       return;
322 
323     for (const auto &F : CurrentModule) {
324       StringRef OrigName = F.getName();
325       CurrentGUIDToFuncNameMap.insert(
326           {Function::getGUID(OrigName), OrigName});
327 
328       // Local to global var promotion used by optimization like thinlto
329       // will rename the var and add suffix like ".llvm.xxx" to the
330       // original local name. In sample profile, the suffixes of function
331       // names are all stripped. Since it is possible that the mapper is
332       // built in post-thin-link phase and var promotion has been done,
333       // we need to add the substring of function name without the suffix
334       // into the GUIDToFuncNameMap.
335       StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
336       if (CanonName != OrigName)
337         CurrentGUIDToFuncNameMap.insert(
338             {Function::getGUID(CanonName), CanonName});
339     }
340 
341     // Update GUIDToFuncNameMap for each function including inlinees.
342     SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
343   }
344 
345   ~GUIDToFuncNameMapper() {
346     if (!CurrentReader.useMD5())
347       return;
348 
349     CurrentGUIDToFuncNameMap.clear();
350 
351     // Reset GUIDToFuncNameMap for of each function as they're no
352     // longer valid at this point.
353     SetGUIDToFuncNameMapForAll(nullptr);
354   }
355 
356 private:
357   void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
358     std::queue<FunctionSamples *> FSToUpdate;
359     for (auto &IFS : CurrentReader.getProfiles()) {
360       FSToUpdate.push(&IFS.second);
361     }
362 
363     while (!FSToUpdate.empty()) {
364       FunctionSamples *FS = FSToUpdate.front();
365       FSToUpdate.pop();
366       FS->GUIDToFuncNameMap = Map;
367       for (const auto &ICS : FS->getCallsiteSamples()) {
368         const FunctionSamplesMap &FSMap = ICS.second;
369         for (auto &IFS : FSMap) {
370           FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
371           FSToUpdate.push(&FS);
372         }
373       }
374     }
375   }
376 
377   SampleProfileReader &CurrentReader;
378   Module &CurrentModule;
379   DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
380 };
381 
382 // Inline candidate used by iterative callsite prioritized inliner
383 struct InlineCandidate {
384   CallBase *CallInstr;
385   const FunctionSamples *CalleeSamples;
386   // Prorated callsite count, which will be used to guide inlining. For example,
387   // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
388   // copies will get their own distribution factors and their prorated counts
389   // will be used to decide if they should be inlined independently.
390   uint64_t CallsiteCount;
391   // Call site distribution factor to prorate the profile samples for a
392   // duplicated callsite. Default value is 1.0.
393   float CallsiteDistribution;
394 };
395 
396 // Inline candidate comparer using call site weight
397 struct CandidateComparer {
398   bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
399     if (LHS.CallsiteCount != RHS.CallsiteCount)
400       return LHS.CallsiteCount < RHS.CallsiteCount;
401 
402     const FunctionSamples *LCS = LHS.CalleeSamples;
403     const FunctionSamples *RCS = RHS.CalleeSamples;
404     assert(LCS && RCS && "Expect non-null FunctionSamples");
405 
406     // Tie breaker using number of samples try to favor smaller functions first
407     if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
408       return LCS->getBodySamples().size() > RCS->getBodySamples().size();
409 
410     // Tie breaker using GUID so we have stable/deterministic inlining order
411     return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName());
412   }
413 };
414 
415 using CandidateQueue =
416     PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
417                   CandidateComparer>;
418 
419 /// Sample profile pass.
420 ///
421 /// This pass reads profile data from the file specified by
422 /// -sample-profile-file and annotates every affected function with the
423 /// profile information found in that file.
424 class SampleProfileLoader final
425     : public SampleProfileLoaderBaseImpl<BasicBlock> {
426 public:
427   SampleProfileLoader(
428       StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
429       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
430       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
431       std::function<const TargetLibraryInfo &(Function &)> GetTLI)
432       : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName)),
433         GetAC(std::move(GetAssumptionCache)),
434         GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
435         LTOPhase(LTOPhase) {}
436 
437   bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
438   bool runOnModule(Module &M, ModuleAnalysisManager *AM,
439                    ProfileSummaryInfo *_PSI, CallGraph *CG);
440 
441 protected:
442   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
443   bool emitAnnotations(Function &F);
444   ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
445   ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
446   const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
447   const FunctionSamples *
448   findFunctionSamples(const Instruction &I) const override;
449   std::vector<const FunctionSamples *>
450   findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
451   void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
452                                    DenseSet<GlobalValue::GUID> &InlinedGUIDs,
453                                    const StringMap<Function *> &SymbolMap,
454                                    uint64_t Threshold);
455   // Attempt to promote indirect call and also inline the promoted call
456   bool tryPromoteAndInlineCandidate(
457       Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
458       uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
459 
460   bool inlineHotFunctions(Function &F,
461                           DenseSet<GlobalValue::GUID> &InlinedGUIDs);
462   Optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
463   bool getExternalInlineAdvisorShouldInline(CallBase &CB);
464   InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
465   bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
466   bool
467   tryInlineCandidate(InlineCandidate &Candidate,
468                      SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
469   bool
470   inlineHotFunctionsWithPriority(Function &F,
471                                  DenseSet<GlobalValue::GUID> &InlinedGUIDs);
472   // Inline cold/small functions in addition to hot ones
473   bool shouldInlineColdCallee(CallBase &CallInst);
474   void emitOptimizationRemarksForInlineCandidates(
475       const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
476       bool Hot);
477   void promoteMergeNotInlinedContextSamples(
478       DenseMap<CallBase *, const FunctionSamples *> NonInlinedCallSites,
479       const Function &F);
480   std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
481   std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG);
482   void generateMDProfMetadata(Function &F);
483 
484   /// Map from function name to Function *. Used to find the function from
485   /// the function name. If the function name contains suffix, additional
486   /// entry is added to map from the stripped name to the function if there
487   /// is one-to-one mapping.
488   StringMap<Function *> SymbolMap;
489 
490   std::function<AssumptionCache &(Function &)> GetAC;
491   std::function<TargetTransformInfo &(Function &)> GetTTI;
492   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
493 
494   /// Profile tracker for different context.
495   std::unique_ptr<SampleContextTracker> ContextTracker;
496 
497   /// Flag indicating whether input profile is context-sensitive
498   bool ProfileIsCSFlat = false;
499 
500   /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
501   ///
502   /// We need to know the LTO phase because for example in ThinLTOPrelink
503   /// phase, in annotation, we should not promote indirect calls. Instead,
504   /// we will mark GUIDs that needs to be annotated to the function.
505   ThinOrFullLTOPhase LTOPhase;
506 
507   /// Profle Symbol list tells whether a function name appears in the binary
508   /// used to generate the current profile.
509   std::unique_ptr<ProfileSymbolList> PSL;
510 
511   /// Total number of samples collected in this profile.
512   ///
513   /// This is the sum of all the samples collected in all the functions executed
514   /// at runtime.
515   uint64_t TotalCollectedSamples = 0;
516 
517   // Information recorded when we declined to inline a call site
518   // because we have determined it is too cold is accumulated for
519   // each callee function. Initially this is just the entry count.
520   struct NotInlinedProfileInfo {
521     uint64_t entryCount;
522   };
523   DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
524 
525   // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
526   // all the function symbols defined or declared in current module.
527   DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
528 
529   // All the Names used in FunctionSamples including outline function
530   // names, inline instance names and call target names.
531   StringSet<> NamesInProfile;
532 
533   // For symbol in profile symbol list, whether to regard their profiles
534   // to be accurate. It is mainly decided by existance of profile symbol
535   // list and -profile-accurate-for-symsinlist flag, but it can be
536   // overriden by -profile-sample-accurate or profile-sample-accurate
537   // attribute.
538   bool ProfAccForSymsInList;
539 
540   // External inline advisor used to replay inline decision from remarks.
541   std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
542 
543   // A pseudo probe helper to correlate the imported sample counts.
544   std::unique_ptr<PseudoProbeManager> ProbeManager;
545 };
546 
547 class SampleProfileLoaderLegacyPass : public ModulePass {
548 public:
549   // Class identification, replacement for typeinfo
550   static char ID;
551 
552   SampleProfileLoaderLegacyPass(
553       StringRef Name = SampleProfileFile,
554       ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None)
555       : ModulePass(ID), SampleLoader(
556                             Name, SampleProfileRemappingFile, LTOPhase,
557                             [&](Function &F) -> AssumptionCache & {
558                               return ACT->getAssumptionCache(F);
559                             },
560                             [&](Function &F) -> TargetTransformInfo & {
561                               return TTIWP->getTTI(F);
562                             },
563                             [&](Function &F) -> TargetLibraryInfo & {
564                               return TLIWP->getTLI(F);
565                             }) {
566     initializeSampleProfileLoaderLegacyPassPass(
567         *PassRegistry::getPassRegistry());
568   }
569 
570   void dump() { SampleLoader.dump(); }
571 
572   bool doInitialization(Module &M) override {
573     return SampleLoader.doInitialization(M);
574   }
575 
576   StringRef getPassName() const override { return "Sample profile pass"; }
577   bool runOnModule(Module &M) override;
578 
579   void getAnalysisUsage(AnalysisUsage &AU) const override {
580     AU.addRequired<AssumptionCacheTracker>();
581     AU.addRequired<TargetTransformInfoWrapperPass>();
582     AU.addRequired<TargetLibraryInfoWrapperPass>();
583     AU.addRequired<ProfileSummaryInfoWrapperPass>();
584   }
585 
586 private:
587   SampleProfileLoader SampleLoader;
588   AssumptionCacheTracker *ACT = nullptr;
589   TargetTransformInfoWrapperPass *TTIWP = nullptr;
590   TargetLibraryInfoWrapperPass *TLIWP = nullptr;
591 };
592 
593 } // end anonymous namespace
594 
595 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
596   if (FunctionSamples::ProfileIsProbeBased)
597     return getProbeWeight(Inst);
598 
599   const DebugLoc &DLoc = Inst.getDebugLoc();
600   if (!DLoc)
601     return std::error_code();
602 
603   // Ignore all intrinsics, phinodes and branch instructions.
604   // Branch and phinodes instruction usually contains debug info from sources
605   // outside of the residing basic block, thus we ignore them during annotation.
606   if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
607     return std::error_code();
608 
609   // For non-CS profile, if a direct call/invoke instruction is inlined in
610   // profile (findCalleeFunctionSamples returns non-empty result), but not
611   // inlined here, it means that the inlined callsite has no sample, thus the
612   // call instruction should have 0 count.
613   // For CS profile, the callsite count of previously inlined callees is
614   // populated with the entry count of the callees.
615   if (!ProfileIsCSFlat)
616     if (const auto *CB = dyn_cast<CallBase>(&Inst))
617       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
618         return 0;
619 
620   return getInstWeightImpl(Inst);
621 }
622 
623 // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight
624 // of non-probe instruction. So if all instructions of the BB give error_code,
625 // tell the inference algorithm to infer the BB weight.
626 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
627   assert(FunctionSamples::ProfileIsProbeBased &&
628          "Profile is not pseudo probe based");
629   Optional<PseudoProbe> Probe = extractProbe(Inst);
630   // Ignore the non-probe instruction. If none of the instruction in the BB is
631   // probe, we choose to infer the BB's weight.
632   if (!Probe)
633     return std::error_code();
634 
635   const FunctionSamples *FS = findFunctionSamples(Inst);
636   // If none of the instruction has FunctionSample, we choose to return zero
637   // value sample to indicate the BB is cold. This could happen when the
638   // instruction is from inlinee and no profile data is found.
639   // FIXME: This should not be affected by the source drift issue as 1) if the
640   // newly added function is top-level inliner, it won't match the CFG checksum
641   // in the function profile or 2) if it's the inlinee, the inlinee should have
642   // a profile, otherwise it wouldn't be inlined. For non-probe based profile,
643   // we can improve it by adding a switch for profile-sample-block-accurate for
644   // block level counts in the future.
645   if (!FS)
646     return 0;
647 
648   // For non-CS profile, If a direct call/invoke instruction is inlined in
649   // profile (findCalleeFunctionSamples returns non-empty result), but not
650   // inlined here, it means that the inlined callsite has no sample, thus the
651   // call instruction should have 0 count.
652   // For CS profile, the callsite count of previously inlined callees is
653   // populated with the entry count of the callees.
654   if (!ProfileIsCSFlat)
655     if (const auto *CB = dyn_cast<CallBase>(&Inst))
656       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
657         return 0;
658 
659   const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
660   if (R) {
661     uint64_t Samples = R.get() * Probe->Factor;
662     bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
663     if (FirstMark) {
664       ORE->emit([&]() {
665         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
666         Remark << "Applied " << ore::NV("NumSamples", Samples);
667         Remark << " samples from profile (ProbeId=";
668         Remark << ore::NV("ProbeId", Probe->Id);
669         Remark << ", Factor=";
670         Remark << ore::NV("Factor", Probe->Factor);
671         Remark << ", OriginalSamples=";
672         Remark << ore::NV("OriginalSamples", R.get());
673         Remark << ")";
674         return Remark;
675       });
676     }
677     LLVM_DEBUG(dbgs() << "    " << Probe->Id << ":" << Inst
678                       << " - weight: " << R.get() << " - factor: "
679                       << format("%0.2f", Probe->Factor) << ")\n");
680     return Samples;
681   }
682   return R;
683 }
684 
685 /// Get the FunctionSamples for a call instruction.
686 ///
687 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
688 /// instance in which that call instruction is calling to. It contains
689 /// all samples that resides in the inlined instance. We first find the
690 /// inlined instance in which the call instruction is from, then we
691 /// traverse its children to find the callsite with the matching
692 /// location.
693 ///
694 /// \param Inst Call/Invoke instruction to query.
695 ///
696 /// \returns The FunctionSamples pointer to the inlined instance.
697 const FunctionSamples *
698 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
699   const DILocation *DIL = Inst.getDebugLoc();
700   if (!DIL) {
701     return nullptr;
702   }
703 
704   StringRef CalleeName;
705   if (Function *Callee = Inst.getCalledFunction())
706     CalleeName = Callee->getName();
707 
708   if (ProfileIsCSFlat)
709     return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
710 
711   const FunctionSamples *FS = findFunctionSamples(Inst);
712   if (FS == nullptr)
713     return nullptr;
714 
715   return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
716                                    CalleeName, Reader->getRemapper());
717 }
718 
719 /// Returns a vector of FunctionSamples that are the indirect call targets
720 /// of \p Inst. The vector is sorted by the total number of samples. Stores
721 /// the total call count of the indirect call in \p Sum.
722 std::vector<const FunctionSamples *>
723 SampleProfileLoader::findIndirectCallFunctionSamples(
724     const Instruction &Inst, uint64_t &Sum) const {
725   const DILocation *DIL = Inst.getDebugLoc();
726   std::vector<const FunctionSamples *> R;
727 
728   if (!DIL) {
729     return R;
730   }
731 
732   auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
733     assert(L && R && "Expect non-null FunctionSamples");
734     if (L->getEntrySamples() != R->getEntrySamples())
735       return L->getEntrySamples() > R->getEntrySamples();
736     return FunctionSamples::getGUID(L->getName()) <
737            FunctionSamples::getGUID(R->getName());
738   };
739 
740   if (ProfileIsCSFlat) {
741     auto CalleeSamples =
742         ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
743     if (CalleeSamples.empty())
744       return R;
745 
746     // For CSSPGO, we only use target context profile's entry count
747     // as that already includes both inlined callee and non-inlined ones..
748     Sum = 0;
749     for (const auto *const FS : CalleeSamples) {
750       Sum += FS->getEntrySamples();
751       R.push_back(FS);
752     }
753     llvm::sort(R, FSCompare);
754     return R;
755   }
756 
757   const FunctionSamples *FS = findFunctionSamples(Inst);
758   if (FS == nullptr)
759     return R;
760 
761   auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
762   auto T = FS->findCallTargetMapAt(CallSite);
763   Sum = 0;
764   if (T)
765     for (const auto &T_C : T.get())
766       Sum += T_C.second;
767   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
768     if (M->empty())
769       return R;
770     for (const auto &NameFS : *M) {
771       Sum += NameFS.second.getEntrySamples();
772       R.push_back(&NameFS.second);
773     }
774     llvm::sort(R, FSCompare);
775   }
776   return R;
777 }
778 
779 const FunctionSamples *
780 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
781   if (FunctionSamples::ProfileIsProbeBased) {
782     Optional<PseudoProbe> Probe = extractProbe(Inst);
783     if (!Probe)
784       return nullptr;
785   }
786 
787   const DILocation *DIL = Inst.getDebugLoc();
788   if (!DIL)
789     return Samples;
790 
791   auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
792   if (it.second) {
793     if (ProfileIsCSFlat)
794       it.first->second = ContextTracker->getContextSamplesFor(DIL);
795     else
796       it.first->second =
797           Samples->findFunctionSamples(DIL, Reader->getRemapper());
798   }
799   return it.first->second;
800 }
801 
802 /// Check whether the indirect call promotion history of \p Inst allows
803 /// the promotion for \p Candidate.
804 /// If the profile count for the promotion candidate \p Candidate is
805 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
806 /// for \p Inst. If we already have at least MaxNumPromotions
807 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
808 /// cannot promote for \p Inst anymore.
809 static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
810   uint32_t NumVals = 0;
811   uint64_t TotalCount = 0;
812   std::unique_ptr<InstrProfValueData[]> ValueData =
813       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
814   bool Valid =
815       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
816                                ValueData.get(), NumVals, TotalCount, true);
817   // No valid value profile so no promoted targets have been recorded
818   // before. Ok to do ICP.
819   if (!Valid)
820     return true;
821 
822   unsigned NumPromoted = 0;
823   for (uint32_t I = 0; I < NumVals; I++) {
824     if (ValueData[I].Count != NOMORE_ICP_MAGICNUM)
825       continue;
826 
827     // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
828     // metadata, it means the candidate has been promoted for this
829     // indirect call.
830     if (ValueData[I].Value == Function::getGUID(Candidate))
831       return false;
832     NumPromoted++;
833     // If already have MaxNumPromotions promotion, don't do it anymore.
834     if (NumPromoted == MaxNumPromotions)
835       return false;
836   }
837   return true;
838 }
839 
840 /// Update indirect call target profile metadata for \p Inst.
841 /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
842 /// If it is 0, it means updateIDTMetaData is used to mark a
843 /// certain target to be promoted already. If it is not zero,
844 /// we expect to use it to update the total count in the value profile.
845 static void
846 updateIDTMetaData(Instruction &Inst,
847                   const SmallVectorImpl<InstrProfValueData> &CallTargets,
848                   uint64_t Sum) {
849   // Bail out early if MaxNumPromotions is zero.
850   // This prevents allocating an array of zero length below.
851   //
852   // Note `updateIDTMetaData` is called in two places so check
853   // `MaxNumPromotions` inside it.
854   if (MaxNumPromotions == 0)
855     return;
856   uint32_t NumVals = 0;
857   // OldSum is the existing total count in the value profile data.
858   uint64_t OldSum = 0;
859   std::unique_ptr<InstrProfValueData[]> ValueData =
860       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
861   bool Valid =
862       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
863                                ValueData.get(), NumVals, OldSum, true);
864 
865   DenseMap<uint64_t, uint64_t> ValueCountMap;
866   if (Sum == 0) {
867     assert((CallTargets.size() == 1 &&
868             CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
869            "If sum is 0, assume only one element in CallTargets "
870            "with count being NOMORE_ICP_MAGICNUM");
871     // Initialize ValueCountMap with existing value profile data.
872     if (Valid) {
873       for (uint32_t I = 0; I < NumVals; I++)
874         ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
875     }
876     auto Pair =
877         ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
878     // If the target already exists in value profile, decrease the total
879     // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
880     if (!Pair.second) {
881       OldSum -= Pair.first->second;
882       Pair.first->second = NOMORE_ICP_MAGICNUM;
883     }
884     Sum = OldSum;
885   } else {
886     // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
887     // counts in the value profile.
888     if (Valid) {
889       for (uint32_t I = 0; I < NumVals; I++) {
890         if (ValueData[I].Count == NOMORE_ICP_MAGICNUM)
891           ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
892       }
893     }
894 
895     for (const auto &Data : CallTargets) {
896       auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
897       if (Pair.second)
898         continue;
899       // The target represented by Data.Value has already been promoted.
900       // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
901       // Sum by Data.Count.
902       assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
903       Sum -= Data.Count;
904     }
905   }
906 
907   SmallVector<InstrProfValueData, 8> NewCallTargets;
908   for (const auto &ValueCount : ValueCountMap) {
909     NewCallTargets.emplace_back(
910         InstrProfValueData{ValueCount.first, ValueCount.second});
911   }
912 
913   llvm::sort(NewCallTargets,
914              [](const InstrProfValueData &L, const InstrProfValueData &R) {
915                if (L.Count != R.Count)
916                  return L.Count > R.Count;
917                return L.Value > R.Value;
918              });
919 
920   uint32_t MaxMDCount =
921       std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
922   annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
923                     NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
924 }
925 
926 /// Attempt to promote indirect call and also inline the promoted call.
927 ///
928 /// \param F  Caller function.
929 /// \param Candidate  ICP and inline candidate.
930 /// \param SumOrigin  Original sum of target counts for indirect call before
931 ///                   promoting given candidate.
932 /// \param Sum        Prorated sum of remaining target counts for indirect call
933 ///                   after promoting given candidate.
934 /// \param InlinedCallSite  Output vector for new call sites exposed after
935 /// inlining.
936 bool SampleProfileLoader::tryPromoteAndInlineCandidate(
937     Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
938     SmallVector<CallBase *, 8> *InlinedCallSite) {
939   // Bail out early if MaxNumPromotions is zero.
940   // This prevents allocating an array of zero length in callees below.
941   if (MaxNumPromotions == 0)
942     return false;
943   auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName();
944   auto R = SymbolMap.find(CalleeFunctionName);
945   if (R == SymbolMap.end() || !R->getValue())
946     return false;
947 
948   auto &CI = *Candidate.CallInstr;
949   if (!doesHistoryAllowICP(CI, R->getValue()->getName()))
950     return false;
951 
952   const char *Reason = "Callee function not available";
953   // R->getValue() != &F is to prevent promoting a recursive call.
954   // If it is a recursive call, we do not inline it as it could bloat
955   // the code exponentially. There is way to better handle this, e.g.
956   // clone the caller first, and inline the cloned caller if it is
957   // recursive. As llvm does not inline recursive calls, we will
958   // simply ignore it instead of handling it explicitly.
959   if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() &&
960       R->getValue()->hasFnAttribute("use-sample-profile") &&
961       R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) {
962     // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
963     // in the value profile metadata so the target won't be promoted again.
964     SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
965         Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}};
966     updateIDTMetaData(CI, SortedCallTargets, 0);
967 
968     auto *DI = &pgo::promoteIndirectCall(
969         CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE);
970     if (DI) {
971       Sum -= Candidate.CallsiteCount;
972       // Do not prorate the indirect callsite distribution since the original
973       // distribution will be used to scale down non-promoted profile target
974       // counts later. By doing this we lose track of the real callsite count
975       // for the leftover indirect callsite as a trade off for accurate call
976       // target counts.
977       // TODO: Ideally we would have two separate factors, one for call site
978       // counts and one is used to prorate call target counts.
979       // Do not update the promoted direct callsite distribution at this
980       // point since the original distribution combined with the callee profile
981       // will be used to prorate callsites from the callee if inlined. Once not
982       // inlined, the direct callsite distribution should be prorated so that
983       // the it will reflect the real callsite counts.
984       Candidate.CallInstr = DI;
985       if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
986         bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
987         if (!Inlined) {
988           // Prorate the direct callsite distribution so that it reflects real
989           // callsite counts.
990           setProbeDistributionFactor(
991               *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
992         }
993         return Inlined;
994       }
995     }
996   } else {
997     LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
998                       << Candidate.CalleeSamples->getFuncName() << " because "
999                       << Reason << "\n");
1000   }
1001   return false;
1002 }
1003 
1004 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
1005   if (!ProfileSizeInline)
1006     return false;
1007 
1008   Function *Callee = CallInst.getCalledFunction();
1009   if (Callee == nullptr)
1010     return false;
1011 
1012   InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
1013                                   GetAC, GetTLI);
1014 
1015   if (Cost.isNever())
1016     return false;
1017 
1018   if (Cost.isAlways())
1019     return true;
1020 
1021   return Cost.getCost() <= SampleColdCallSiteThreshold;
1022 }
1023 
1024 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
1025     const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
1026     bool Hot) {
1027   for (auto I : Candidates) {
1028     Function *CalledFunction = I->getCalledFunction();
1029     if (CalledFunction) {
1030       ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
1031                                            I->getDebugLoc(), I->getParent())
1032                 << "previous inlining reattempted for "
1033                 << (Hot ? "hotness: '" : "size: '")
1034                 << ore::NV("Callee", CalledFunction) << "' into '"
1035                 << ore::NV("Caller", &F) << "'");
1036     }
1037   }
1038 }
1039 
1040 void SampleProfileLoader::findExternalInlineCandidate(
1041     CallBase *CB, const FunctionSamples *Samples,
1042     DenseSet<GlobalValue::GUID> &InlinedGUIDs,
1043     const StringMap<Function *> &SymbolMap, uint64_t Threshold) {
1044 
1045   // If ExternalInlineAdvisor wants to inline an external function
1046   // make sure it's imported
1047   if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
1048     // Samples may not exist for replayed function, if so
1049     // just add the direct GUID and move on
1050     if (!Samples) {
1051       InlinedGUIDs.insert(
1052           FunctionSamples::getGUID(CB->getCalledFunction()->getName()));
1053       return;
1054     }
1055     // Otherwise, drop the threshold to import everything that we can
1056     Threshold = 0;
1057   }
1058 
1059   assert(Samples && "expect non-null caller profile");
1060 
1061   // For AutoFDO profile, retrieve candidate profiles by walking over
1062   // the nested inlinee profiles.
1063   if (!ProfileIsCSFlat) {
1064     Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold);
1065     return;
1066   }
1067 
1068   ContextTrieNode *Caller =
1069       ContextTracker->getContextFor(Samples->getContext());
1070   std::queue<ContextTrieNode *> CalleeList;
1071   CalleeList.push(Caller);
1072   while (!CalleeList.empty()) {
1073     ContextTrieNode *Node = CalleeList.front();
1074     CalleeList.pop();
1075     FunctionSamples *CalleeSample = Node->getFunctionSamples();
1076     // For CSSPGO profile, retrieve candidate profile by walking over the
1077     // trie built for context profile. Note that also take call targets
1078     // even if callee doesn't have a corresponding context profile.
1079     if (!CalleeSample)
1080       continue;
1081 
1082     // If pre-inliner decision is used, honor that for importing as well.
1083     bool PreInline =
1084         UsePreInlinerDecision &&
1085         CalleeSample->getContext().hasAttribute(ContextShouldBeInlined);
1086     if (!PreInline && CalleeSample->getEntrySamples() < Threshold)
1087       continue;
1088 
1089     StringRef Name = CalleeSample->getFuncName();
1090     Function *Func = SymbolMap.lookup(Name);
1091     // Add to the import list only when it's defined out of module.
1092     if (!Func || Func->isDeclaration())
1093       InlinedGUIDs.insert(FunctionSamples::getGUID(CalleeSample->getName()));
1094 
1095     // Import hot CallTargets, which may not be available in IR because full
1096     // profile annotation cannot be done until backend compilation in ThinLTO.
1097     for (const auto &BS : CalleeSample->getBodySamples())
1098       for (const auto &TS : BS.second.getCallTargets())
1099         if (TS.getValue() > Threshold) {
1100           StringRef CalleeName = CalleeSample->getFuncName(TS.getKey());
1101           const Function *Callee = SymbolMap.lookup(CalleeName);
1102           if (!Callee || Callee->isDeclaration())
1103             InlinedGUIDs.insert(FunctionSamples::getGUID(TS.getKey()));
1104         }
1105 
1106     // Import hot child context profile associted with callees. Note that this
1107     // may have some overlap with the call target loop above, but doing this
1108     // based child context profile again effectively allow us to use the max of
1109     // entry count and call target count to determine importing.
1110     for (auto &Child : Node->getAllChildContext()) {
1111       ContextTrieNode *CalleeNode = &Child.second;
1112       CalleeList.push(CalleeNode);
1113     }
1114   }
1115 }
1116 
1117 /// Iteratively inline hot callsites of a function.
1118 ///
1119 /// Iteratively traverse all callsites of the function \p F, and find if
1120 /// the corresponding inlined instance exists and is hot in profile. If
1121 /// it is hot enough, inline the callsites and adds new callsites of the
1122 /// callee into the caller. If the call is an indirect call, first promote
1123 /// it to direct call. Each indirect call is limited with a single target.
1124 ///
1125 /// \param F function to perform iterative inlining.
1126 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1127 ///     inlined in the profiled binary.
1128 ///
1129 /// \returns True if there is any inline happened.
1130 bool SampleProfileLoader::inlineHotFunctions(
1131     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1132   if (DisableSampleLoaderInlining)
1133     return false;
1134   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1135   // Profile symbol list is ignored when profile-sample-accurate is on.
1136   assert((!ProfAccForSymsInList ||
1137           (!ProfileSampleAccurate &&
1138            !F.hasFnAttribute("profile-sample-accurate"))) &&
1139          "ProfAccForSymsInList should be false when profile-sample-accurate "
1140          "is enabled");
1141 
1142   DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1143   bool Changed = false;
1144   bool LocalChanged = true;
1145   while (LocalChanged) {
1146     LocalChanged = false;
1147     SmallVector<CallBase *, 10> CIS;
1148     for (auto &BB : F) {
1149       bool Hot = false;
1150       SmallVector<CallBase *, 10> AllCandidates;
1151       SmallVector<CallBase *, 10> ColdCandidates;
1152       for (auto &I : BB.getInstList()) {
1153         const FunctionSamples *FS = nullptr;
1154         if (auto *CB = dyn_cast<CallBase>(&I)) {
1155           if (!isa<IntrinsicInst>(I)) {
1156             if ((FS = findCalleeFunctionSamples(*CB))) {
1157               assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1158                      "GUIDToFuncNameMap has to be populated");
1159               AllCandidates.push_back(CB);
1160               if (FS->getEntrySamples() > 0 || ProfileIsCSFlat)
1161                 LocalNotInlinedCallSites.try_emplace(CB, FS);
1162               if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1163                 Hot = true;
1164               else if (shouldInlineColdCallee(*CB))
1165                 ColdCandidates.push_back(CB);
1166             } else if (getExternalInlineAdvisorShouldInline(*CB)) {
1167               AllCandidates.push_back(CB);
1168             }
1169           }
1170         }
1171       }
1172       if (Hot || ExternalInlineAdvisor) {
1173         CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1174         emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
1175       } else {
1176         CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1177         emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
1178       }
1179     }
1180     for (CallBase *I : CIS) {
1181       Function *CalledFunction = I->getCalledFunction();
1182       InlineCandidate Candidate = {I, LocalNotInlinedCallSites.lookup(I),
1183                                    0 /* dummy count */,
1184                                    1.0 /* dummy distribution factor */};
1185       // Do not inline recursive calls.
1186       if (CalledFunction == &F)
1187         continue;
1188       if (I->isIndirectCall()) {
1189         uint64_t Sum;
1190         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1191           uint64_t SumOrigin = Sum;
1192           if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1193             findExternalInlineCandidate(I, FS, InlinedGUIDs, SymbolMap,
1194                                         PSI->getOrCompHotCountThreshold());
1195             continue;
1196           }
1197           if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1198             continue;
1199 
1200           Candidate = {I, FS, FS->getEntrySamples(), 1.0};
1201           if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1202             LocalNotInlinedCallSites.erase(I);
1203             LocalChanged = true;
1204           }
1205         }
1206       } else if (CalledFunction && CalledFunction->getSubprogram() &&
1207                  !CalledFunction->isDeclaration()) {
1208         if (tryInlineCandidate(Candidate)) {
1209           LocalNotInlinedCallSites.erase(I);
1210           LocalChanged = true;
1211         }
1212       } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1213         findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
1214                                     InlinedGUIDs, SymbolMap,
1215                                     PSI->getOrCompHotCountThreshold());
1216       }
1217     }
1218     Changed |= LocalChanged;
1219   }
1220 
1221   // For CS profile, profile for not inlined context will be merged when
1222   // base profile is being retrieved.
1223   if (!FunctionSamples::ProfileIsCSFlat)
1224     promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1225   return Changed;
1226 }
1227 
1228 bool SampleProfileLoader::tryInlineCandidate(
1229     InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1230 
1231   CallBase &CB = *Candidate.CallInstr;
1232   Function *CalledFunction = CB.getCalledFunction();
1233   assert(CalledFunction && "Expect a callee with definition");
1234   DebugLoc DLoc = CB.getDebugLoc();
1235   BasicBlock *BB = CB.getParent();
1236 
1237   InlineCost Cost = shouldInlineCandidate(Candidate);
1238   if (Cost.isNever()) {
1239     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
1240               << "incompatible inlining");
1241     return false;
1242   }
1243 
1244   if (!Cost)
1245     return false;
1246 
1247   InlineFunctionInfo IFI(nullptr, GetAC);
1248   IFI.UpdateProfile = false;
1249   if (!InlineFunction(CB, IFI).isSuccess())
1250     return false;
1251 
1252   // Merge the attributes based on the inlining.
1253   AttributeFuncs::mergeAttributesForInlining(*BB->getParent(),
1254                                              *CalledFunction);
1255 
1256   // The call to InlineFunction erases I, so we can't pass it here.
1257   emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction,
1258                              *BB->getParent(), Cost, true, CSINLINE_DEBUG);
1259 
1260   // Now populate the list of newly exposed call sites.
1261   if (InlinedCallSites) {
1262     InlinedCallSites->clear();
1263     for (auto &I : IFI.InlinedCallSites)
1264       InlinedCallSites->push_back(I);
1265   }
1266 
1267   if (ProfileIsCSFlat)
1268     ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1269   ++NumCSInlined;
1270 
1271   // Prorate inlined probes for a duplicated inlining callsite which probably
1272   // has a distribution less than 100%. Samples for an inlinee should be
1273   // distributed among the copies of the original callsite based on each
1274   // callsite's distribution factor for counts accuracy. Note that an inlined
1275   // probe may come with its own distribution factor if it has been duplicated
1276   // in the inlinee body. The two factor are multiplied to reflect the
1277   // aggregation of duplication.
1278   if (Candidate.CallsiteDistribution < 1) {
1279     for (auto &I : IFI.InlinedCallSites) {
1280       if (Optional<PseudoProbe> Probe = extractProbe(*I))
1281         setProbeDistributionFactor(*I, Probe->Factor *
1282                                    Candidate.CallsiteDistribution);
1283     }
1284     NumDuplicatedInlinesite++;
1285   }
1286 
1287   return true;
1288 }
1289 
1290 bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1291                                              CallBase *CB) {
1292   assert(CB && "Expect non-null call instruction");
1293 
1294   if (isa<IntrinsicInst>(CB))
1295     return false;
1296 
1297   // Find the callee's profile. For indirect call, find hottest target profile.
1298   const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1299   // If ExternalInlineAdvisor wants to inline this site, do so even
1300   // if Samples are not present.
1301   if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
1302     return false;
1303 
1304   float Factor = 1.0;
1305   if (Optional<PseudoProbe> Probe = extractProbe(*CB))
1306     Factor = Probe->Factor;
1307 
1308   uint64_t CallsiteCount = 0;
1309   ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent());
1310   if (Weight)
1311     CallsiteCount = Weight.get();
1312   if (CalleeSamples)
1313     CallsiteCount = std::max(
1314         CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor));
1315 
1316   *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1317   return true;
1318 }
1319 
1320 Optional<InlineCost>
1321 SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
1322   std::unique_ptr<InlineAdvice> Advice = nullptr;
1323   if (ExternalInlineAdvisor) {
1324     Advice = ExternalInlineAdvisor->getAdvice(CB);
1325     if (Advice) {
1326       if (!Advice->isInliningRecommended()) {
1327         Advice->recordUnattemptedInlining();
1328         return InlineCost::getNever("not previously inlined");
1329       }
1330       Advice->recordInlining();
1331       return InlineCost::getAlways("previously inlined");
1332     }
1333   }
1334 
1335   return {};
1336 }
1337 
1338 bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
1339   Optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
1340   return Cost ? !!Cost.getValue() : false;
1341 }
1342 
1343 InlineCost
1344 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1345   if (Optional<InlineCost> ReplayCost =
1346           getExternalInlineAdvisorCost(*Candidate.CallInstr))
1347     return ReplayCost.getValue();
1348   // Adjust threshold based on call site hotness, only do this for callsite
1349   // prioritized inliner because otherwise cost-benefit check is done earlier.
1350   int SampleThreshold = SampleColdCallSiteThreshold;
1351   if (CallsitePrioritizedInline) {
1352     if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1353       SampleThreshold = SampleHotCallSiteThreshold;
1354     else if (!ProfileSizeInline)
1355       return InlineCost::getNever("cold callsite");
1356   }
1357 
1358   Function *Callee = Candidate.CallInstr->getCalledFunction();
1359   assert(Callee && "Expect a definition for inline candidate of direct call");
1360 
1361   InlineParams Params = getInlineParams();
1362   // We will ignore the threshold from inline cost, so always get full cost.
1363   Params.ComputeFullInlineCost = true;
1364   Params.AllowRecursiveCall = AllowRecursiveInline;
1365   // Checks if there is anything in the reachable portion of the callee at
1366   // this callsite that makes this inlining potentially illegal. Need to
1367   // set ComputeFullInlineCost, otherwise getInlineCost may return early
1368   // when cost exceeds threshold without checking all IRs in the callee.
1369   // The acutal cost does not matter because we only checks isNever() to
1370   // see if it is legal to inline the callsite.
1371   InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1372                                   GetTTI(*Callee), GetAC, GetTLI);
1373 
1374   // Honor always inline and never inline from call analyzer
1375   if (Cost.isNever() || Cost.isAlways())
1376     return Cost;
1377 
1378   // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1379   // decisions based on hotness as well as accurate function byte sizes for
1380   // given context using function/inlinee sizes from previous build. It
1381   // stores the decision in profile, and also adjust/merge context profile
1382   // aiming at better context-sensitive post-inline profile quality, assuming
1383   // all inline decision estimates are going to be honored by compiler. Here
1384   // we replay that inline decision under `sample-profile-use-preinliner`.
1385   // Note that we don't need to handle negative decision from preinliner as
1386   // context profile for not inlined calls are merged by preinliner already.
1387   if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1388     // Once two node are merged due to promotion, we're losing some context
1389     // so the original context-sensitive preinliner decision should be ignored
1390     // for SyntheticContext.
1391     SampleContext &Context = Candidate.CalleeSamples->getContext();
1392     if (!Context.hasState(SyntheticContext) &&
1393         Context.hasAttribute(ContextShouldBeInlined))
1394       return InlineCost::getAlways("preinliner");
1395   }
1396 
1397   // For old FDO inliner, we inline the call site as long as cost is not
1398   // "Never". The cost-benefit check is done earlier.
1399   if (!CallsitePrioritizedInline) {
1400     return InlineCost::get(Cost.getCost(), INT_MAX);
1401   }
1402 
1403   // Otherwise only use the cost from call analyzer, but overwite threshold with
1404   // Sample PGO threshold.
1405   return InlineCost::get(Cost.getCost(), SampleThreshold);
1406 }
1407 
1408 bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1409     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1410   if (DisableSampleLoaderInlining)
1411     return false;
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 profile is available.
2005   if (Reader->profileIsCSFlat() || Reader->profileIsCSNested()) {
2006     ProfileIsCSFlat = Reader->profileIsCSFlat();
2007     // Enable priority-base inliner and size inline by default for CSSPGO.
2008     if (!ProfileSizeInline.getNumOccurrences())
2009       ProfileSizeInline = true;
2010     if (!CallsitePrioritizedInline.getNumOccurrences())
2011       CallsitePrioritizedInline = true;
2012 
2013     // For CSSPGO, use preinliner decision by default when available.
2014     if (!UsePreInlinerDecision.getNumOccurrences())
2015       UsePreInlinerDecision = true;
2016 
2017     // For CSSPGO, we also allow recursive inline to best use context profile.
2018     if (!AllowRecursiveInline.getNumOccurrences())
2019       AllowRecursiveInline = true;
2020 
2021     // Enable iterative-BFI by default for CSSPGO.
2022     if (!UseIterativeBFIInference.getNumOccurrences())
2023       UseIterativeBFIInference = true;
2024     // Enable Profi by default for CSSPGO.
2025     if (!SampleProfileUseProfi.getNumOccurrences())
2026       SampleProfileUseProfi = true;
2027 
2028     // Enable EXT-TSP block layout for CSSPGO.
2029     if (!EnableExtTspBlockPlacement.getNumOccurrences())
2030       EnableExtTspBlockPlacement = true;
2031 
2032     if (FunctionSamples::ProfileIsCSFlat) {
2033       // Tracker for profiles under different context
2034       ContextTracker = std::make_unique<SampleContextTracker>(
2035           Reader->getProfiles(), &GUIDToFuncNameMap);
2036     }
2037   }
2038 
2039   // Load pseudo probe descriptors for probe-based function samples.
2040   if (Reader->profileIsProbeBased()) {
2041     ProbeManager = std::make_unique<PseudoProbeManager>(M);
2042     if (!ProbeManager->moduleIsProbed(M)) {
2043       const char *Msg =
2044           "Pseudo-probe-based profile requires SampleProfileProbePass";
2045       Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg,
2046                                                DS_Warning));
2047       return false;
2048     }
2049   }
2050 
2051   return true;
2052 }
2053 
2054 ModulePass *llvm::createSampleProfileLoaderPass() {
2055   return new SampleProfileLoaderLegacyPass();
2056 }
2057 
2058 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
2059   return new SampleProfileLoaderLegacyPass(Name);
2060 }
2061 
2062 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
2063                                       ProfileSummaryInfo *_PSI, CallGraph *CG) {
2064   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
2065 
2066   PSI = _PSI;
2067   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
2068     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
2069                         ProfileSummary::PSK_Sample);
2070     PSI->refresh();
2071   }
2072   // Compute the total number of samples collected in this profile.
2073   for (const auto &I : Reader->getProfiles())
2074     TotalCollectedSamples += I.second.getTotalSamples();
2075 
2076   auto Remapper = Reader->getRemapper();
2077   // Populate the symbol map.
2078   for (const auto &N_F : M.getValueSymbolTable()) {
2079     StringRef OrigName = N_F.getKey();
2080     Function *F = dyn_cast<Function>(N_F.getValue());
2081     if (F == nullptr || OrigName.empty())
2082       continue;
2083     SymbolMap[OrigName] = F;
2084     StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
2085     if (OrigName != NewName && !NewName.empty()) {
2086       auto r = SymbolMap.insert(std::make_pair(NewName, F));
2087       // Failiing to insert means there is already an entry in SymbolMap,
2088       // thus there are multiple functions that are mapped to the same
2089       // stripped name. In this case of name conflicting, set the value
2090       // to nullptr to avoid confusion.
2091       if (!r.second)
2092         r.first->second = nullptr;
2093       OrigName = NewName;
2094     }
2095     // Insert the remapped names into SymbolMap.
2096     if (Remapper) {
2097       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2098         if (*MapName != OrigName && !MapName->empty())
2099           SymbolMap.insert(std::make_pair(*MapName, F));
2100       }
2101     }
2102   }
2103   assert(SymbolMap.count(StringRef()) == 0 &&
2104          "No empty StringRef should be added in SymbolMap");
2105 
2106   bool retval = false;
2107   for (auto F : buildFunctionOrder(M, CG)) {
2108     assert(!F->isDeclaration());
2109     clearFunctionData();
2110     retval |= runOnFunction(*F, AM);
2111   }
2112 
2113   // Account for cold calls not inlined....
2114   if (!ProfileIsCSFlat)
2115     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
2116          notInlinedCallInfo)
2117       updateProfileCallee(pair.first, pair.second.entryCount);
2118 
2119   return retval;
2120 }
2121 
2122 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
2123   ACT = &getAnalysis<AssumptionCacheTracker>();
2124   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
2125   TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
2126   ProfileSummaryInfo *PSI =
2127       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2128   return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
2129 }
2130 
2131 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
2132   LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
2133   DILocation2SampleMap.clear();
2134   // By default the entry count is initialized to -1, which will be treated
2135   // conservatively by getEntryCount as the same as unknown (None). This is
2136   // to avoid newly added code to be treated as cold. If we have samples
2137   // this will be overwritten in emitAnnotations.
2138   uint64_t initialEntryCount = -1;
2139 
2140   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
2141   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
2142     // initialize all the function entry counts to 0. It means all the
2143     // functions without profile will be regarded as cold.
2144     initialEntryCount = 0;
2145     // profile-sample-accurate is a user assertion which has a higher precedence
2146     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2147     ProfAccForSymsInList = false;
2148   }
2149   CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
2150 
2151   // PSL -- profile symbol list include all the symbols in sampled binary.
2152   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2153   // old functions without samples being cold, without having to worry
2154   // about new and hot functions being mistakenly treated as cold.
2155   if (ProfAccForSymsInList) {
2156     // Initialize the entry count to 0 for functions in the list.
2157     if (PSL->contains(F.getName()))
2158       initialEntryCount = 0;
2159 
2160     // Function in the symbol list but without sample will be regarded as
2161     // cold. To minimize the potential negative performance impact it could
2162     // have, we want to be a little conservative here saying if a function
2163     // shows up in the profile, no matter as outline function, inline instance
2164     // or call targets, treat the function as not being cold. This will handle
2165     // the cases such as most callsites of a function are inlined in sampled
2166     // binary but not inlined in current build (because of source code drift,
2167     // imprecise debug information, or the callsites are all cold individually
2168     // but not cold accumulatively...), so the outline function showing up as
2169     // cold in sampled binary will actually not be cold after current build.
2170     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2171     if (NamesInProfile.count(CanonName))
2172       initialEntryCount = -1;
2173   }
2174 
2175   // Initialize entry count when the function has no existing entry
2176   // count value.
2177   if (!F.getEntryCount().hasValue())
2178     F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
2179   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
2180   if (AM) {
2181     auto &FAM =
2182         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
2183             .getManager();
2184     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2185   } else {
2186     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2187     ORE = OwnedORE.get();
2188   }
2189 
2190   if (ProfileIsCSFlat)
2191     Samples = ContextTracker->getBaseSamplesFor(F);
2192   else
2193     Samples = Reader->getSamplesFor(F);
2194 
2195   if (Samples && !Samples->empty())
2196     return emitAnnotations(F);
2197   return false;
2198 }
2199 
2200 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
2201                                                ModuleAnalysisManager &AM) {
2202   FunctionAnalysisManager &FAM =
2203       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2204 
2205   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2206     return FAM.getResult<AssumptionAnalysis>(F);
2207   };
2208   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
2209     return FAM.getResult<TargetIRAnalysis>(F);
2210   };
2211   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2212     return FAM.getResult<TargetLibraryAnalysis>(F);
2213   };
2214 
2215   SampleProfileLoader SampleLoader(
2216       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
2217       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
2218                                        : ProfileRemappingFileName,
2219       LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
2220 
2221   if (!SampleLoader.doInitialization(M, &FAM))
2222     return PreservedAnalyses::all();
2223 
2224   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2225   CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
2226   if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
2227     return PreservedAnalyses::all();
2228 
2229   return PreservedAnalyses::none();
2230 }
2231