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