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