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