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