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