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