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