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/SCCIterator.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringMap.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/AssumptionCache.h"
38 #include "llvm/Analysis/CallGraph.h"
39 #include "llvm/Analysis/CallGraphSCCPass.h"
40 #include "llvm/Analysis/InlineAdvisor.h"
41 #include "llvm/Analysis/InlineCost.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
44 #include "llvm/Analysis/PostDominators.h"
45 #include "llvm/Analysis/ProfileSummaryInfo.h"
46 #include "llvm/Analysis/ReplayInlineAdvisor.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/IR/BasicBlock.h"
50 #include "llvm/IR/CFG.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DiagnosticInfo.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/Function.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/InstrTypes.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/LLVMContext.h"
62 #include "llvm/IR/MDBuilder.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/PassManager.h"
65 #include "llvm/IR/ValueSymbolTable.h"
66 #include "llvm/InitializePasses.h"
67 #include "llvm/Pass.h"
68 #include "llvm/ProfileData/InstrProf.h"
69 #include "llvm/ProfileData/SampleProf.h"
70 #include "llvm/ProfileData/SampleProfReader.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/ErrorOr.h"
76 #include "llvm/Support/GenericDomTree.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/IPO.h"
79 #include "llvm/Transforms/IPO/SampleContextTracker.h"
80 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
81 #include "llvm/Transforms/Instrumentation.h"
82 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
83 #include "llvm/Transforms/Utils/Cloning.h"
84 #include <algorithm>
85 #include <cassert>
86 #include <cstdint>
87 #include <functional>
88 #include <limits>
89 #include <map>
90 #include <memory>
91 #include <queue>
92 #include <string>
93 #include <system_error>
94 #include <utility>
95 #include <vector>
96 
97 using namespace llvm;
98 using namespace sampleprof;
99 using ProfileCount = Function::ProfileCount;
100 #define DEBUG_TYPE "sample-profile"
101 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
102 
103 STATISTIC(NumCSInlined,
104           "Number of functions inlined with context sensitive profile");
105 STATISTIC(NumCSNotInlined,
106           "Number of functions not inlined with context sensitive profile");
107 STATISTIC(NumMismatchedProfile,
108           "Number of functions with CFG mismatched profile");
109 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
110 
111 // Command line option to specify the file to read samples from. This is
112 // mainly used for debugging.
113 static cl::opt<std::string> SampleProfileFile(
114     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
115     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
116 
117 // The named file contains a set of transformations that may have been applied
118 // to the symbol names between the program from which the sample data was
119 // collected and the current program's symbols.
120 static cl::opt<std::string> SampleProfileRemappingFile(
121     "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
122     cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
123 
124 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
125     "sample-profile-max-propagate-iterations", cl::init(100),
126     cl::desc("Maximum number of iterations to go through when propagating "
127              "sample block/edge weights through the CFG."));
128 
129 static cl::opt<unsigned> SampleProfileRecordCoverage(
130     "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
131     cl::desc("Emit a warning if less than N% of records in the input profile "
132              "are matched to the IR."));
133 
134 static cl::opt<unsigned> SampleProfileSampleCoverage(
135     "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
136     cl::desc("Emit a warning if less than N% of samples in the input profile "
137              "are matched to the IR."));
138 
139 static cl::opt<bool> NoWarnSampleUnused(
140     "no-warn-sample-unused", cl::init(false), cl::Hidden,
141     cl::desc("Use this option to turn off/on warnings about function with "
142              "samples but without debug information to use those samples. "));
143 
144 static cl::opt<bool> ProfileSampleAccurate(
145     "profile-sample-accurate", cl::Hidden, cl::init(false),
146     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
147              "callsite and function as having 0 samples. Otherwise, treat "
148              "un-sampled callsites and functions conservatively as unknown. "));
149 
150 static cl::opt<bool> ProfileAccurateForSymsInList(
151     "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
152     cl::init(true),
153     cl::desc("For symbols in profile symbol list, regard their profiles to "
154              "be accurate. It may be overriden by profile-sample-accurate. "));
155 
156 static cl::opt<bool> ProfileMergeInlinee(
157     "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
158     cl::desc("Merge past inlinee's profile to outline version if sample "
159              "profile loader decided not to inline a call site. It will "
160              "only be enabled when top-down order of profile loading is "
161              "enabled. "));
162 
163 static cl::opt<bool> ProfileTopDownLoad(
164     "sample-profile-top-down-load", cl::Hidden, cl::init(true),
165     cl::desc("Do profile annotation and inlining for functions in top-down "
166              "order of call graph during sample profile loading. It only "
167              "works for new pass manager. "));
168 
169 static cl::opt<bool> ProfileSizeInline(
170     "sample-profile-inline-size", cl::Hidden, cl::init(false),
171     cl::desc("Inline cold call sites in profile loader if it's beneficial "
172              "for code size."));
173 
174 static cl::opt<int> SampleColdCallSiteThreshold(
175     "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
176     cl::desc("Threshold for inlining cold callsites"));
177 
178 static cl::opt<std::string> ProfileInlineReplayFile(
179     "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
180     cl::desc(
181         "Optimization remarks file containing inline remarks to be replayed "
182         "by inlining from sample profile loader."),
183     cl::Hidden);
184 
185 namespace {
186 
187 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
188 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
189 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
190 using EdgeWeightMap = DenseMap<Edge, uint64_t>;
191 using BlockEdgeMap =
192     DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
193 
194 class SampleProfileLoader;
195 
196 class SampleCoverageTracker {
197 public:
198   SampleCoverageTracker(SampleProfileLoader &SPL) : SPLoader(SPL){};
199 
200   bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
201                        uint32_t Discriminator, uint64_t Samples);
202   unsigned computeCoverage(unsigned Used, unsigned Total) const;
203   unsigned countUsedRecords(const FunctionSamples *FS,
204                             ProfileSummaryInfo *PSI) const;
205   unsigned countBodyRecords(const FunctionSamples *FS,
206                             ProfileSummaryInfo *PSI) const;
207   uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
208   uint64_t countBodySamples(const FunctionSamples *FS,
209                             ProfileSummaryInfo *PSI) const;
210 
211   void clear() {
212     SampleCoverage.clear();
213     TotalUsedSamples = 0;
214   }
215 
216 private:
217   using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
218   using FunctionSamplesCoverageMap =
219       DenseMap<const FunctionSamples *, BodySampleCoverageMap>;
220 
221   /// Coverage map for sampling records.
222   ///
223   /// This map keeps a record of sampling records that have been matched to
224   /// an IR instruction. This is used to detect some form of staleness in
225   /// profiles (see flag -sample-profile-check-coverage).
226   ///
227   /// Each entry in the map corresponds to a FunctionSamples instance.  This is
228   /// another map that counts how many times the sample record at the
229   /// given location has been used.
230   FunctionSamplesCoverageMap SampleCoverage;
231 
232   /// Number of samples used from the profile.
233   ///
234   /// When a sampling record is used for the first time, the samples from
235   /// that record are added to this accumulator.  Coverage is later computed
236   /// based on the total number of samples available in this function and
237   /// its callsites.
238   ///
239   /// Note that this accumulator tracks samples used from a single function
240   /// and all the inlined callsites. Strictly, we should have a map of counters
241   /// keyed by FunctionSamples pointers, but these stats are cleared after
242   /// every function, so we just need to keep a single counter.
243   uint64_t TotalUsedSamples = 0;
244 
245   SampleProfileLoader &SPLoader;
246 };
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 /// Sample profile pass.
317 ///
318 /// This pass reads profile data from the file specified by
319 /// -sample-profile-file and annotates every affected function with the
320 /// profile information found in that file.
321 class SampleProfileLoader {
322 public:
323   SampleProfileLoader(
324       StringRef Name, StringRef RemapName, bool IsThinLTOPreLink,
325       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
326       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
327       std::function<const TargetLibraryInfo &(Function &)> GetTLI)
328       : GetAC(std::move(GetAssumptionCache)),
329         GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
330         CoverageTracker(*this), Filename(std::string(Name)),
331         RemappingFilename(std::string(RemapName)),
332         IsThinLTOPreLink(IsThinLTOPreLink) {}
333 
334   bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
335   bool runOnModule(Module &M, ModuleAnalysisManager *AM,
336                    ProfileSummaryInfo *_PSI, CallGraph *CG);
337 
338   void dump() { Reader->dump(); }
339 
340 protected:
341   friend class SampleCoverageTracker;
342 
343   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
344   unsigned getFunctionLoc(Function &F);
345   bool emitAnnotations(Function &F);
346   ErrorOr<uint64_t> getInstWeight(const Instruction &I);
347   ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
348   ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
349   const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
350   std::vector<const FunctionSamples *>
351   findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
352   mutable DenseMap<const DILocation *, const FunctionSamples *> DILocation2SampleMap;
353   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
354   bool inlineCallInstruction(CallBase &CB);
355   bool inlineHotFunctions(Function &F,
356                           DenseSet<GlobalValue::GUID> &InlinedGUIDs);
357   // Inline cold/small functions in addition to hot ones
358   bool shouldInlineColdCallee(CallBase &CallInst);
359   void emitOptimizationRemarksForInlineCandidates(
360       const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
361       bool Hot);
362   void printEdgeWeight(raw_ostream &OS, Edge E);
363   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
364   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
365   bool computeBlockWeights(Function &F);
366   void findEquivalenceClasses(Function &F);
367   template <bool IsPostDom>
368   void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
369                            DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
370 
371   void propagateWeights(Function &F);
372   uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
373   void buildEdges(Function &F);
374   std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
375   bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
376   void computeDominanceAndLoopInfo(Function &F);
377   void clearFunctionData();
378   bool callsiteIsHot(const FunctionSamples *CallsiteFS,
379                      ProfileSummaryInfo *PSI);
380 
381   /// Map basic blocks to their computed weights.
382   ///
383   /// The weight of a basic block is defined to be the maximum
384   /// of all the instruction weights in that block.
385   BlockWeightMap BlockWeights;
386 
387   /// Map edges to their computed weights.
388   ///
389   /// Edge weights are computed by propagating basic block weights in
390   /// SampleProfile::propagateWeights.
391   EdgeWeightMap EdgeWeights;
392 
393   /// Set of visited blocks during propagation.
394   SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
395 
396   /// Set of visited edges during propagation.
397   SmallSet<Edge, 32> VisitedEdges;
398 
399   /// Equivalence classes for block weights.
400   ///
401   /// Two blocks BB1 and BB2 are in the same equivalence class if they
402   /// dominate and post-dominate each other, and they are in the same loop
403   /// nest. When this happens, the two blocks are guaranteed to execute
404   /// the same number of times.
405   EquivalenceClassMap EquivalenceClass;
406 
407   /// Map from function name to Function *. Used to find the function from
408   /// the function name. If the function name contains suffix, additional
409   /// entry is added to map from the stripped name to the function if there
410   /// is one-to-one mapping.
411   StringMap<Function *> SymbolMap;
412 
413   /// Dominance, post-dominance and loop information.
414   std::unique_ptr<DominatorTree> DT;
415   std::unique_ptr<PostDominatorTree> PDT;
416   std::unique_ptr<LoopInfo> LI;
417 
418   std::function<AssumptionCache &(Function &)> GetAC;
419   std::function<TargetTransformInfo &(Function &)> GetTTI;
420   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
421 
422   /// Predecessors for each basic block in the CFG.
423   BlockEdgeMap Predecessors;
424 
425   /// Successors for each basic block in the CFG.
426   BlockEdgeMap Successors;
427 
428   SampleCoverageTracker CoverageTracker;
429 
430   /// Profile reader object.
431   std::unique_ptr<SampleProfileReader> Reader;
432 
433   /// Profile tracker for different context.
434   std::unique_ptr<SampleContextTracker> ContextTracker;
435 
436   /// Samples collected for the body of this function.
437   FunctionSamples *Samples = nullptr;
438 
439   /// Name of the profile file to load.
440   std::string Filename;
441 
442   /// Name of the profile remapping file to load.
443   std::string RemappingFilename;
444 
445   /// Flag indicating whether the profile input loaded successfully.
446   bool ProfileIsValid = false;
447 
448   /// Flag indicating whether input profile is context-sensitive
449   bool ProfileIsCS = false;
450 
451   /// Flag indicating if the pass is invoked in ThinLTO compile phase.
452   ///
453   /// In this phase, in annotation, we should not promote indirect calls.
454   /// Instead, we will mark GUIDs that needs to be annotated to the function.
455   bool IsThinLTOPreLink;
456 
457   /// Profile Summary Info computed from sample profile.
458   ProfileSummaryInfo *PSI = nullptr;
459 
460   /// Profle Symbol list tells whether a function name appears in the binary
461   /// used to generate the current profile.
462   std::unique_ptr<ProfileSymbolList> PSL;
463 
464   /// Total number of samples collected in this profile.
465   ///
466   /// This is the sum of all the samples collected in all the functions executed
467   /// at runtime.
468   uint64_t TotalCollectedSamples = 0;
469 
470   /// Optimization Remark Emitter used to emit diagnostic remarks.
471   OptimizationRemarkEmitter *ORE = nullptr;
472 
473   // Information recorded when we declined to inline a call site
474   // because we have determined it is too cold is accumulated for
475   // each callee function. Initially this is just the entry count.
476   struct NotInlinedProfileInfo {
477     uint64_t entryCount;
478   };
479   DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
480 
481   // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
482   // all the function symbols defined or declared in current module.
483   DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
484 
485   // All the Names used in FunctionSamples including outline function
486   // names, inline instance names and call target names.
487   StringSet<> NamesInProfile;
488 
489   // For symbol in profile symbol list, whether to regard their profiles
490   // to be accurate. It is mainly decided by existance of profile symbol
491   // list and -profile-accurate-for-symsinlist flag, but it can be
492   // overriden by -profile-sample-accurate or profile-sample-accurate
493   // attribute.
494   bool ProfAccForSymsInList;
495 
496   // External inline advisor used to replay inline decision from remarks.
497   std::unique_ptr<ReplayInlineAdvisor> ExternalInlineAdvisor;
498 
499   // A pseudo probe helper to correlate the imported sample counts.
500   std::unique_ptr<PseudoProbeManager> ProbeManager;
501 };
502 
503 class SampleProfileLoaderLegacyPass : public ModulePass {
504 public:
505   // Class identification, replacement for typeinfo
506   static char ID;
507 
508   SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile,
509                                 bool IsThinLTOPreLink = false)
510       : ModulePass(ID), SampleLoader(
511                             Name, SampleProfileRemappingFile, IsThinLTOPreLink,
512                             [&](Function &F) -> AssumptionCache & {
513                               return ACT->getAssumptionCache(F);
514                             },
515                             [&](Function &F) -> TargetTransformInfo & {
516                               return TTIWP->getTTI(F);
517                             },
518                             [&](Function &F) -> TargetLibraryInfo & {
519                               return TLIWP->getTLI(F);
520                             }) {
521     initializeSampleProfileLoaderLegacyPassPass(
522         *PassRegistry::getPassRegistry());
523   }
524 
525   void dump() { SampleLoader.dump(); }
526 
527   bool doInitialization(Module &M) override {
528     return SampleLoader.doInitialization(M);
529   }
530 
531   StringRef getPassName() const override { return "Sample profile pass"; }
532   bool runOnModule(Module &M) override;
533 
534   void getAnalysisUsage(AnalysisUsage &AU) const override {
535     AU.addRequired<AssumptionCacheTracker>();
536     AU.addRequired<TargetTransformInfoWrapperPass>();
537     AU.addRequired<TargetLibraryInfoWrapperPass>();
538     AU.addRequired<ProfileSummaryInfoWrapperPass>();
539   }
540 
541 private:
542   SampleProfileLoader SampleLoader;
543   AssumptionCacheTracker *ACT = nullptr;
544   TargetTransformInfoWrapperPass *TTIWP = nullptr;
545   TargetLibraryInfoWrapperPass *TLIWP = nullptr;
546 };
547 
548 } // end anonymous namespace
549 
550 /// Return true if the given callsite is hot wrt to hot cutoff threshold.
551 ///
552 /// Functions that were inlined in the original binary will be represented
553 /// in the inline stack in the sample profile. If the profile shows that
554 /// the original inline decision was "good" (i.e., the callsite is executed
555 /// frequently), then we will recreate the inline decision and apply the
556 /// profile from the inlined callsite.
557 ///
558 /// To decide whether an inlined callsite is hot, we compare the callsite
559 /// sample count with the hot cutoff computed by ProfileSummaryInfo, it is
560 /// regarded as hot if the count is above the cutoff value.
561 ///
562 /// When ProfileAccurateForSymsInList is enabled and profile symbol list
563 /// is present, functions in the profile symbol list but without profile will
564 /// be regarded as cold and much less inlining will happen in CGSCC inlining
565 /// pass, so we tend to lower the hot criteria here to allow more early
566 /// inlining to happen for warm callsites and it is helpful for performance.
567 bool SampleProfileLoader::callsiteIsHot(const FunctionSamples *CallsiteFS,
568                                         ProfileSummaryInfo *PSI) {
569   if (!CallsiteFS)
570     return false; // The callsite was not inlined in the original binary.
571 
572   assert(PSI && "PSI is expected to be non null");
573   uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
574   if (ProfAccForSymsInList)
575     return !PSI->isColdCount(CallsiteTotalSamples);
576   else
577     return PSI->isHotCount(CallsiteTotalSamples);
578 }
579 
580 /// Mark as used the sample record for the given function samples at
581 /// (LineOffset, Discriminator).
582 ///
583 /// \returns true if this is the first time we mark the given record.
584 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
585                                             uint32_t LineOffset,
586                                             uint32_t Discriminator,
587                                             uint64_t Samples) {
588   LineLocation Loc(LineOffset, Discriminator);
589   unsigned &Count = SampleCoverage[FS][Loc];
590   bool FirstTime = (++Count == 1);
591   if (FirstTime)
592     TotalUsedSamples += Samples;
593   return FirstTime;
594 }
595 
596 /// Return the number of sample records that were applied from this profile.
597 ///
598 /// This count does not include records from cold inlined callsites.
599 unsigned
600 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS,
601                                         ProfileSummaryInfo *PSI) const {
602   auto I = SampleCoverage.find(FS);
603 
604   // The size of the coverage map for FS represents the number of records
605   // that were marked used at least once.
606   unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
607 
608   // If there are inlined callsites in this function, count the samples found
609   // in the respective bodies. However, do not bother counting callees with 0
610   // total samples, these are callees that were never invoked at runtime.
611   for (const auto &I : FS->getCallsiteSamples())
612     for (const auto &J : I.second) {
613       const FunctionSamples *CalleeSamples = &J.second;
614       if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
615         Count += countUsedRecords(CalleeSamples, PSI);
616     }
617 
618   return Count;
619 }
620 
621 /// Return the number of sample records in the body of this profile.
622 ///
623 /// This count does not include records from cold inlined callsites.
624 unsigned
625 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS,
626                                         ProfileSummaryInfo *PSI) const {
627   unsigned Count = FS->getBodySamples().size();
628 
629   // Only count records in hot callsites.
630   for (const auto &I : FS->getCallsiteSamples())
631     for (const auto &J : I.second) {
632       const FunctionSamples *CalleeSamples = &J.second;
633       if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
634         Count += countBodyRecords(CalleeSamples, PSI);
635     }
636 
637   return Count;
638 }
639 
640 /// Return the number of samples collected in the body of this profile.
641 ///
642 /// This count does not include samples from cold inlined callsites.
643 uint64_t
644 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS,
645                                         ProfileSummaryInfo *PSI) const {
646   uint64_t Total = 0;
647   for (const auto &I : FS->getBodySamples())
648     Total += I.second.getSamples();
649 
650   // Only count samples in hot callsites.
651   for (const auto &I : FS->getCallsiteSamples())
652     for (const auto &J : I.second) {
653       const FunctionSamples *CalleeSamples = &J.second;
654       if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
655         Total += countBodySamples(CalleeSamples, PSI);
656     }
657 
658   return Total;
659 }
660 
661 /// Return the fraction of sample records used in this profile.
662 ///
663 /// The returned value is an unsigned integer in the range 0-100 indicating
664 /// the percentage of sample records that were used while applying this
665 /// profile to the associated function.
666 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
667                                                 unsigned Total) const {
668   assert(Used <= Total &&
669          "number of used records cannot exceed the total number of records");
670   return Total > 0 ? Used * 100 / Total : 100;
671 }
672 
673 /// Clear all the per-function data used to load samples and propagate weights.
674 void SampleProfileLoader::clearFunctionData() {
675   BlockWeights.clear();
676   EdgeWeights.clear();
677   VisitedBlocks.clear();
678   VisitedEdges.clear();
679   EquivalenceClass.clear();
680   DT = nullptr;
681   PDT = nullptr;
682   LI = nullptr;
683   Predecessors.clear();
684   Successors.clear();
685   CoverageTracker.clear();
686 }
687 
688 #ifndef NDEBUG
689 /// Print the weight of edge \p E on stream \p OS.
690 ///
691 /// \param OS  Stream to emit the output to.
692 /// \param E  Edge to print.
693 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
694   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
695      << "]: " << EdgeWeights[E] << "\n";
696 }
697 
698 /// Print the equivalence class of block \p BB on stream \p OS.
699 ///
700 /// \param OS  Stream to emit the output to.
701 /// \param BB  Block to print.
702 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
703                                                 const BasicBlock *BB) {
704   const BasicBlock *Equiv = EquivalenceClass[BB];
705   OS << "equivalence[" << BB->getName()
706      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
707 }
708 
709 /// Print the weight of block \p BB on stream \p OS.
710 ///
711 /// \param OS  Stream to emit the output to.
712 /// \param BB  Block to print.
713 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
714                                            const BasicBlock *BB) const {
715   const auto &I = BlockWeights.find(BB);
716   uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
717   OS << "weight[" << BB->getName() << "]: " << W << "\n";
718 }
719 #endif
720 
721 /// Get the weight for an instruction.
722 ///
723 /// The "weight" of an instruction \p Inst is the number of samples
724 /// collected on that instruction at runtime. To retrieve it, we
725 /// need to compute the line number of \p Inst relative to the start of its
726 /// function. We use HeaderLineno to compute the offset. We then
727 /// look up the samples collected for \p Inst using BodySamples.
728 ///
729 /// \param Inst Instruction to query.
730 ///
731 /// \returns the weight of \p Inst.
732 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
733   if (FunctionSamples::ProfileIsProbeBased)
734     return getProbeWeight(Inst);
735 
736   const DebugLoc &DLoc = Inst.getDebugLoc();
737   if (!DLoc)
738     return std::error_code();
739 
740   const FunctionSamples *FS = findFunctionSamples(Inst);
741   if (!FS)
742     return std::error_code();
743 
744   // Ignore all intrinsics, phinodes and branch instructions.
745   // Branch and phinodes instruction usually contains debug info from sources outside of
746   // the residing basic block, thus we ignore them during annotation.
747   if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
748     return std::error_code();
749 
750   // If a direct call/invoke instruction is inlined in profile
751   // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
752   // it means that the inlined callsite has no sample, thus the call
753   // instruction should have 0 count.
754   if (!ProfileIsCS)
755     if (const auto *CB = dyn_cast<CallBase>(&Inst))
756       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
757         return 0;
758 
759   const DILocation *DIL = DLoc;
760   uint32_t LineOffset = FunctionSamples::getOffset(DIL);
761   uint32_t Discriminator = DIL->getBaseDiscriminator();
762   ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
763   if (R) {
764     bool FirstMark =
765         CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
766     if (FirstMark) {
767       ORE->emit([&]() {
768         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
769         Remark << "Applied " << ore::NV("NumSamples", *R);
770         Remark << " samples from profile (offset: ";
771         Remark << ore::NV("LineOffset", LineOffset);
772         if (Discriminator) {
773           Remark << ".";
774           Remark << ore::NV("Discriminator", Discriminator);
775         }
776         Remark << ")";
777         return Remark;
778       });
779     }
780     LLVM_DEBUG(dbgs() << "    " << DLoc.getLine() << "."
781                       << DIL->getBaseDiscriminator() << ":" << Inst
782                       << " (line offset: " << LineOffset << "."
783                       << DIL->getBaseDiscriminator() << " - weight: " << R.get()
784                       << ")\n");
785   }
786   return R;
787 }
788 
789 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
790   assert(FunctionSamples::ProfileIsProbeBased &&
791          "Profile is not pseudo probe based");
792   Optional<PseudoProbe> Probe = extractProbe(Inst);
793   if (!Probe)
794     return std::error_code();
795 
796   const FunctionSamples *FS = findFunctionSamples(Inst);
797   if (!FS)
798     return std::error_code();
799 
800   // If a direct call/invoke instruction is inlined in profile
801   // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
802   // it means that the inlined callsite has no sample, thus the call
803   // instruction should have 0 count.
804   if (const auto *CB = dyn_cast<CallBase>(&Inst))
805     if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
806       return 0;
807 
808   const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
809   if (R) {
810     uint64_t Samples = R.get();
811     bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
812     if (FirstMark) {
813       ORE->emit([&]() {
814         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
815         Remark << "Applied " << ore::NV("NumSamples", Samples);
816         Remark << " samples from profile (ProbeId=";
817         Remark << ore::NV("ProbeId", Probe->Id);
818         Remark << ")";
819         return Remark;
820       });
821     }
822 
823     LLVM_DEBUG(dbgs() << "    " << Probe->Id << ":" << Inst
824                       << " - weight: " << R.get() << ")\n");
825     return Samples;
826   }
827   return R;
828 }
829 
830 /// Compute the weight of a basic block.
831 ///
832 /// The weight of basic block \p BB is the maximum weight of all the
833 /// instructions in BB.
834 ///
835 /// \param BB The basic block to query.
836 ///
837 /// \returns the weight for \p BB.
838 ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
839   uint64_t Max = 0;
840   bool HasWeight = false;
841   for (auto &I : BB->getInstList()) {
842     const ErrorOr<uint64_t> &R = getInstWeight(I);
843     if (R) {
844       Max = std::max(Max, R.get());
845       HasWeight = true;
846     }
847   }
848   return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
849 }
850 
851 /// Compute and store the weights of every basic block.
852 ///
853 /// This populates the BlockWeights map by computing
854 /// the weights of every basic block in the CFG.
855 ///
856 /// \param F The function to query.
857 bool SampleProfileLoader::computeBlockWeights(Function &F) {
858   bool Changed = false;
859   LLVM_DEBUG(dbgs() << "Block weights\n");
860   for (const auto &BB : F) {
861     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
862     if (Weight) {
863       BlockWeights[&BB] = Weight.get();
864       VisitedBlocks.insert(&BB);
865       Changed = true;
866     }
867     LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
868   }
869 
870   return Changed;
871 }
872 
873 /// Get the FunctionSamples for a call instruction.
874 ///
875 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
876 /// instance in which that call instruction is calling to. It contains
877 /// all samples that resides in the inlined instance. We first find the
878 /// inlined instance in which the call instruction is from, then we
879 /// traverse its children to find the callsite with the matching
880 /// location.
881 ///
882 /// \param Inst Call/Invoke instruction to query.
883 ///
884 /// \returns The FunctionSamples pointer to the inlined instance.
885 const FunctionSamples *
886 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
887   const DILocation *DIL = Inst.getDebugLoc();
888   if (!DIL) {
889     return nullptr;
890   }
891 
892   StringRef CalleeName;
893   if (Function *Callee = Inst.getCalledFunction())
894     CalleeName = FunctionSamples::getCanonicalFnName(*Callee);
895 
896   if (ProfileIsCS)
897     return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
898 
899   const FunctionSamples *FS = findFunctionSamples(Inst);
900   if (FS == nullptr)
901     return nullptr;
902 
903   return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
904                                    CalleeName, Reader->getRemapper());
905 }
906 
907 /// Returns a vector of FunctionSamples that are the indirect call targets
908 /// of \p Inst. The vector is sorted by the total number of samples. Stores
909 /// the total call count of the indirect call in \p Sum.
910 std::vector<const FunctionSamples *>
911 SampleProfileLoader::findIndirectCallFunctionSamples(
912     const Instruction &Inst, uint64_t &Sum) const {
913   const DILocation *DIL = Inst.getDebugLoc();
914   std::vector<const FunctionSamples *> R;
915 
916   if (!DIL) {
917     return R;
918   }
919 
920   const FunctionSamples *FS = findFunctionSamples(Inst);
921   if (FS == nullptr)
922     return R;
923 
924   auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
925   auto T = FS->findCallTargetMapAt(CallSite);
926   Sum = 0;
927   if (T)
928     for (const auto &T_C : T.get())
929       Sum += T_C.second;
930   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
931     if (M->empty())
932       return R;
933     for (const auto &NameFS : *M) {
934       Sum += NameFS.second.getEntrySamples();
935       R.push_back(&NameFS.second);
936     }
937     llvm::sort(R, [](const FunctionSamples *L, const FunctionSamples *R) {
938       if (L->getEntrySamples() != R->getEntrySamples())
939         return L->getEntrySamples() > R->getEntrySamples();
940       return FunctionSamples::getGUID(L->getName()) <
941              FunctionSamples::getGUID(R->getName());
942     });
943   }
944   return R;
945 }
946 
947 /// Get the FunctionSamples for an instruction.
948 ///
949 /// The FunctionSamples of an instruction \p Inst is the inlined instance
950 /// in which that instruction is coming from. We traverse the inline stack
951 /// of that instruction, and match it with the tree nodes in the profile.
952 ///
953 /// \param Inst Instruction to query.
954 ///
955 /// \returns the FunctionSamples pointer to the inlined instance.
956 const FunctionSamples *
957 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
958   if (FunctionSamples::ProfileIsProbeBased) {
959     Optional<PseudoProbe> Probe = extractProbe(Inst);
960     if (!Probe)
961       return nullptr;
962   }
963 
964   const DILocation *DIL = Inst.getDebugLoc();
965   if (!DIL)
966     return Samples;
967 
968   auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
969   if (it.second) {
970     if (ProfileIsCS)
971       it.first->second = ContextTracker->getContextSamplesFor(DIL);
972     else
973       it.first->second =
974           Samples->findFunctionSamples(DIL, Reader->getRemapper());
975   }
976   return it.first->second;
977 }
978 
979 bool SampleProfileLoader::inlineCallInstruction(CallBase &CB) {
980   if (ExternalInlineAdvisor) {
981     auto Advice = ExternalInlineAdvisor->getAdvice(CB);
982     if (!Advice->isInliningRecommended()) {
983       Advice->recordUnattemptedInlining();
984       return false;
985     }
986     // Dummy record, we don't use it for replay.
987     Advice->recordInlining();
988   }
989 
990   Function *CalledFunction = CB.getCalledFunction();
991   assert(CalledFunction);
992   DebugLoc DLoc = CB.getDebugLoc();
993   BasicBlock *BB = CB.getParent();
994   InlineParams Params = getInlineParams();
995   Params.ComputeFullInlineCost = true;
996   // Checks if there is anything in the reachable portion of the callee at
997   // this callsite that makes this inlining potentially illegal. Need to
998   // set ComputeFullInlineCost, otherwise getInlineCost may return early
999   // when cost exceeds threshold without checking all IRs in the callee.
1000   // The acutal cost does not matter because we only checks isNever() to
1001   // see if it is legal to inline the callsite.
1002   InlineCost Cost =
1003       getInlineCost(CB, Params, GetTTI(*CalledFunction), GetAC, GetTLI);
1004   if (Cost.isNever()) {
1005     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
1006               << "incompatible inlining");
1007     return false;
1008   }
1009   InlineFunctionInfo IFI(nullptr, GetAC);
1010   if (InlineFunction(CB, IFI).isSuccess()) {
1011     // The call to InlineFunction erases I, so we can't pass it here.
1012     emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost,
1013                     true, CSINLINE_DEBUG);
1014     return true;
1015   }
1016   return false;
1017 }
1018 
1019 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
1020   if (!ProfileSizeInline)
1021     return false;
1022 
1023   Function *Callee = CallInst.getCalledFunction();
1024   if (Callee == nullptr)
1025     return false;
1026 
1027   InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
1028                                   GetAC, GetTLI);
1029 
1030   if (Cost.isNever())
1031     return false;
1032 
1033   if (Cost.isAlways())
1034     return true;
1035 
1036   return Cost.getCost() <= SampleColdCallSiteThreshold;
1037 }
1038 
1039 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
1040     const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
1041     bool Hot) {
1042   for (auto I : Candidates) {
1043     Function *CalledFunction = I->getCalledFunction();
1044     if (CalledFunction) {
1045       ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
1046                                            I->getDebugLoc(), I->getParent())
1047                 << "previous inlining reattempted for "
1048                 << (Hot ? "hotness: '" : "size: '")
1049                 << ore::NV("Callee", CalledFunction) << "' into '"
1050                 << ore::NV("Caller", &F) << "'");
1051     }
1052   }
1053 }
1054 
1055 /// Iteratively inline hot callsites of a function.
1056 ///
1057 /// Iteratively traverse all callsites of the function \p F, and find if
1058 /// the corresponding inlined instance exists and is hot in profile. If
1059 /// it is hot enough, inline the callsites and adds new callsites of the
1060 /// callee into the caller. If the call is an indirect call, first promote
1061 /// it to direct call. Each indirect call is limited with a single target.
1062 ///
1063 /// \param F function to perform iterative inlining.
1064 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1065 ///     inlined in the profiled binary.
1066 ///
1067 /// \returns True if there is any inline happened.
1068 bool SampleProfileLoader::inlineHotFunctions(
1069     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1070   DenseSet<Instruction *> PromotedInsns;
1071 
1072   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1073   // Profile symbol list is ignored when profile-sample-accurate is on.
1074   assert((!ProfAccForSymsInList ||
1075           (!ProfileSampleAccurate &&
1076            !F.hasFnAttribute("profile-sample-accurate"))) &&
1077          "ProfAccForSymsInList should be false when profile-sample-accurate "
1078          "is enabled");
1079 
1080   DenseMap<CallBase *, const FunctionSamples *> localNotInlinedCallSites;
1081   bool Changed = false;
1082   while (true) {
1083     bool LocalChanged = false;
1084     SmallVector<CallBase *, 10> CIS;
1085     for (auto &BB : F) {
1086       bool Hot = false;
1087       SmallVector<CallBase *, 10> AllCandidates;
1088       SmallVector<CallBase *, 10> ColdCandidates;
1089       for (auto &I : BB.getInstList()) {
1090         const FunctionSamples *FS = nullptr;
1091         if (auto *CB = dyn_cast<CallBase>(&I)) {
1092           if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) {
1093             assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1094                    "GUIDToFuncNameMap has to be populated");
1095             AllCandidates.push_back(CB);
1096             if (FS->getEntrySamples() > 0 || ProfileIsCS)
1097               localNotInlinedCallSites.try_emplace(CB, FS);
1098             if (callsiteIsHot(FS, PSI))
1099               Hot = true;
1100             else if (shouldInlineColdCallee(*CB))
1101               ColdCandidates.push_back(CB);
1102           }
1103         }
1104       }
1105       if (Hot || ExternalInlineAdvisor) {
1106         CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1107         emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
1108       } else {
1109         CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1110         emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
1111       }
1112     }
1113     for (CallBase *I : CIS) {
1114       Function *CalledFunction = I->getCalledFunction();
1115       // Do not inline recursive calls.
1116       if (CalledFunction == &F)
1117         continue;
1118       if (I->isIndirectCall()) {
1119         if (PromotedInsns.count(I))
1120           continue;
1121         uint64_t Sum;
1122         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1123           if (IsThinLTOPreLink) {
1124             FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
1125                                      PSI->getOrCompHotCountThreshold());
1126             continue;
1127           }
1128           if (!callsiteIsHot(FS, PSI))
1129             continue;
1130 
1131           const char *Reason = "Callee function not available";
1132           // R->getValue() != &F is to prevent promoting a recursive call.
1133           // If it is a recursive call, we do not inline it as it could bloat
1134           // the code exponentially. There is way to better handle this, e.g.
1135           // clone the caller first, and inline the cloned caller if it is
1136           // recursive. As llvm does not inline recursive calls, we will
1137           // simply ignore it instead of handling it explicitly.
1138           auto CalleeFunctionName = FS->getFuncName();
1139           auto R = SymbolMap.find(CalleeFunctionName);
1140           if (R != SymbolMap.end() && R->getValue() &&
1141               !R->getValue()->isDeclaration() &&
1142               R->getValue()->getSubprogram() &&
1143               R->getValue()->hasFnAttribute("use-sample-profile") &&
1144               R->getValue() != &F &&
1145               isLegalToPromote(*I, R->getValue(), &Reason)) {
1146             uint64_t C = FS->getEntrySamples();
1147             auto &DI =
1148                 pgo::promoteIndirectCall(*I, R->getValue(), C, Sum, false, ORE);
1149             Sum -= C;
1150             PromotedInsns.insert(I);
1151             // If profile mismatches, we should not attempt to inline DI.
1152             if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
1153                 inlineCallInstruction(cast<CallBase>(DI))) {
1154               if (ProfileIsCS)
1155                 ContextTracker->markContextSamplesInlined(FS);
1156               localNotInlinedCallSites.erase(I);
1157               LocalChanged = true;
1158               ++NumCSInlined;
1159             }
1160           } else {
1161             LLVM_DEBUG(dbgs()
1162                        << "\nFailed to promote indirect call to "
1163                        << CalleeFunctionName << " because " << Reason << "\n");
1164           }
1165         }
1166       } else if (CalledFunction && CalledFunction->getSubprogram() &&
1167                  !CalledFunction->isDeclaration()) {
1168         if (inlineCallInstruction(*I)) {
1169           if (ProfileIsCS)
1170             ContextTracker->markContextSamplesInlined(
1171                 localNotInlinedCallSites[I]);
1172           localNotInlinedCallSites.erase(I);
1173           LocalChanged = true;
1174           ++NumCSInlined;
1175         }
1176       } else if (IsThinLTOPreLink) {
1177         findCalleeFunctionSamples(*I)->findInlinedFunctions(
1178             InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
1179       }
1180     }
1181     if (LocalChanged) {
1182       Changed = true;
1183     } else {
1184       break;
1185     }
1186   }
1187 
1188   // Accumulate not inlined callsite information into notInlinedSamples
1189   for (const auto &Pair : localNotInlinedCallSites) {
1190     CallBase *I = Pair.getFirst();
1191     Function *Callee = I->getCalledFunction();
1192     if (!Callee || Callee->isDeclaration())
1193       continue;
1194 
1195     ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline",
1196                                          I->getDebugLoc(), I->getParent())
1197               << "previous inlining not repeated: '"
1198               << ore::NV("Callee", Callee) << "' into '"
1199               << ore::NV("Caller", &F) << "'");
1200 
1201     ++NumCSNotInlined;
1202     const FunctionSamples *FS = Pair.getSecond();
1203     if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) {
1204       continue;
1205     }
1206 
1207     if (ProfileMergeInlinee) {
1208       // A function call can be replicated by optimizations like callsite
1209       // splitting or jump threading and the replicates end up sharing the
1210       // sample nested callee profile instead of slicing the original inlinee's
1211       // profile. We want to do merge exactly once by filtering out callee
1212       // profiles with a non-zero head sample count.
1213       if (FS->getHeadSamples() == 0) {
1214         // Use entry samples as head samples during the merge, as inlinees
1215         // don't have head samples.
1216         const_cast<FunctionSamples *>(FS)->addHeadSamples(
1217             FS->getEntrySamples());
1218 
1219         // Note that we have to do the merge right after processing function.
1220         // This allows OutlineFS's profile to be used for annotation during
1221         // top-down processing of functions' annotation.
1222         FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
1223         OutlineFS->merge(*FS);
1224       }
1225     } else {
1226       auto pair =
1227           notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1228       pair.first->second.entryCount += FS->getEntrySamples();
1229     }
1230   }
1231   return Changed;
1232 }
1233 
1234 /// Find equivalence classes for the given block.
1235 ///
1236 /// This finds all the blocks that are guaranteed to execute the same
1237 /// number of times as \p BB1. To do this, it traverses all the
1238 /// descendants of \p BB1 in the dominator or post-dominator tree.
1239 ///
1240 /// A block BB2 will be in the same equivalence class as \p BB1 if
1241 /// the following holds:
1242 ///
1243 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
1244 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
1245 ///    dominate BB1 in the post-dominator tree.
1246 ///
1247 /// 2- Both BB2 and \p BB1 must be in the same loop.
1248 ///
1249 /// For every block BB2 that meets those two requirements, we set BB2's
1250 /// equivalence class to \p BB1.
1251 ///
1252 /// \param BB1  Block to check.
1253 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
1254 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
1255 ///                 with blocks from \p BB1's dominator tree, then
1256 ///                 this is the post-dominator tree, and vice versa.
1257 template <bool IsPostDom>
1258 void SampleProfileLoader::findEquivalencesFor(
1259     BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
1260     DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
1261   const BasicBlock *EC = EquivalenceClass[BB1];
1262   uint64_t Weight = BlockWeights[EC];
1263   for (const auto *BB2 : Descendants) {
1264     bool IsDomParent = DomTree->dominates(BB2, BB1);
1265     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
1266     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
1267       EquivalenceClass[BB2] = EC;
1268       // If BB2 is visited, then the entire EC should be marked as visited.
1269       if (VisitedBlocks.count(BB2)) {
1270         VisitedBlocks.insert(EC);
1271       }
1272 
1273       // If BB2 is heavier than BB1, make BB2 have the same weight
1274       // as BB1.
1275       //
1276       // Note that we don't worry about the opposite situation here
1277       // (when BB2 is lighter than BB1). We will deal with this
1278       // during the propagation phase. Right now, we just want to
1279       // make sure that BB1 has the largest weight of all the
1280       // members of its equivalence set.
1281       Weight = std::max(Weight, BlockWeights[BB2]);
1282     }
1283   }
1284   if (EC == &EC->getParent()->getEntryBlock()) {
1285     BlockWeights[EC] = Samples->getHeadSamples() + 1;
1286   } else {
1287     BlockWeights[EC] = Weight;
1288   }
1289 }
1290 
1291 /// Find equivalence classes.
1292 ///
1293 /// Since samples may be missing from blocks, we can fill in the gaps by setting
1294 /// the weights of all the blocks in the same equivalence class to the same
1295 /// weight. To compute the concept of equivalence, we use dominance and loop
1296 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
1297 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
1298 ///
1299 /// \param F The function to query.
1300 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
1301   SmallVector<BasicBlock *, 8> DominatedBBs;
1302   LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
1303   // Find equivalence sets based on dominance and post-dominance information.
1304   for (auto &BB : F) {
1305     BasicBlock *BB1 = &BB;
1306 
1307     // Compute BB1's equivalence class once.
1308     if (EquivalenceClass.count(BB1)) {
1309       LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
1310       continue;
1311     }
1312 
1313     // By default, blocks are in their own equivalence class.
1314     EquivalenceClass[BB1] = BB1;
1315 
1316     // Traverse all the blocks dominated by BB1. We are looking for
1317     // every basic block BB2 such that:
1318     //
1319     // 1- BB1 dominates BB2.
1320     // 2- BB2 post-dominates BB1.
1321     // 3- BB1 and BB2 are in the same loop nest.
1322     //
1323     // If all those conditions hold, it means that BB2 is executed
1324     // as many times as BB1, so they are placed in the same equivalence
1325     // class by making BB2's equivalence class be BB1.
1326     DominatedBBs.clear();
1327     DT->getDescendants(BB1, DominatedBBs);
1328     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
1329 
1330     LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
1331   }
1332 
1333   // Assign weights to equivalence classes.
1334   //
1335   // All the basic blocks in the same equivalence class will execute
1336   // the same number of times. Since we know that the head block in
1337   // each equivalence class has the largest weight, assign that weight
1338   // to all the blocks in that equivalence class.
1339   LLVM_DEBUG(
1340       dbgs() << "\nAssign the same weight to all blocks in the same class\n");
1341   for (auto &BI : F) {
1342     const BasicBlock *BB = &BI;
1343     const BasicBlock *EquivBB = EquivalenceClass[BB];
1344     if (BB != EquivBB)
1345       BlockWeights[BB] = BlockWeights[EquivBB];
1346     LLVM_DEBUG(printBlockWeight(dbgs(), BB));
1347   }
1348 }
1349 
1350 /// Visit the given edge to decide if it has a valid weight.
1351 ///
1352 /// If \p E has not been visited before, we copy to \p UnknownEdge
1353 /// and increment the count of unknown edges.
1354 ///
1355 /// \param E  Edge to visit.
1356 /// \param NumUnknownEdges  Current number of unknown edges.
1357 /// \param UnknownEdge  Set if E has not been visited before.
1358 ///
1359 /// \returns E's weight, if known. Otherwise, return 0.
1360 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
1361                                         Edge *UnknownEdge) {
1362   if (!VisitedEdges.count(E)) {
1363     (*NumUnknownEdges)++;
1364     *UnknownEdge = E;
1365     return 0;
1366   }
1367 
1368   return EdgeWeights[E];
1369 }
1370 
1371 /// Propagate weights through incoming/outgoing edges.
1372 ///
1373 /// If the weight of a basic block is known, and there is only one edge
1374 /// with an unknown weight, we can calculate the weight of that edge.
1375 ///
1376 /// Similarly, if all the edges have a known count, we can calculate the
1377 /// count of the basic block, if needed.
1378 ///
1379 /// \param F  Function to process.
1380 /// \param UpdateBlockCount  Whether we should update basic block counts that
1381 ///                          has already been annotated.
1382 ///
1383 /// \returns  True if new weights were assigned to edges or blocks.
1384 bool SampleProfileLoader::propagateThroughEdges(Function &F,
1385                                                 bool UpdateBlockCount) {
1386   bool Changed = false;
1387   LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
1388   for (const auto &BI : F) {
1389     const BasicBlock *BB = &BI;
1390     const BasicBlock *EC = EquivalenceClass[BB];
1391 
1392     // Visit all the predecessor and successor edges to determine
1393     // which ones have a weight assigned already. Note that it doesn't
1394     // matter that we only keep track of a single unknown edge. The
1395     // only case we are interested in handling is when only a single
1396     // edge is unknown (see setEdgeOrBlockWeight).
1397     for (unsigned i = 0; i < 2; i++) {
1398       uint64_t TotalWeight = 0;
1399       unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1400       Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
1401 
1402       if (i == 0) {
1403         // First, visit all predecessor edges.
1404         NumTotalEdges = Predecessors[BB].size();
1405         for (auto *Pred : Predecessors[BB]) {
1406           Edge E = std::make_pair(Pred, BB);
1407           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1408           if (E.first == E.second)
1409             SelfReferentialEdge = E;
1410         }
1411         if (NumTotalEdges == 1) {
1412           SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1413         }
1414       } else {
1415         // On the second round, visit all successor edges.
1416         NumTotalEdges = Successors[BB].size();
1417         for (auto *Succ : Successors[BB]) {
1418           Edge E = std::make_pair(BB, Succ);
1419           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1420         }
1421         if (NumTotalEdges == 1) {
1422           SingleEdge = std::make_pair(BB, Successors[BB][0]);
1423         }
1424       }
1425 
1426       // After visiting all the edges, there are three cases that we
1427       // can handle immediately:
1428       //
1429       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
1430       //   In this case, we simply check that the sum of all the edges
1431       //   is the same as BB's weight. If not, we change BB's weight
1432       //   to match. Additionally, if BB had not been visited before,
1433       //   we mark it visited.
1434       //
1435       // - Only one edge is unknown and BB has already been visited.
1436       //   In this case, we can compute the weight of the edge by
1437       //   subtracting the total block weight from all the known
1438       //   edge weights. If the edges weight more than BB, then the
1439       //   edge of the last remaining edge is set to zero.
1440       //
1441       // - There exists a self-referential edge and the weight of BB is
1442       //   known. In this case, this edge can be based on BB's weight.
1443       //   We add up all the other known edges and set the weight on
1444       //   the self-referential edge as we did in the previous case.
1445       //
1446       // In any other case, we must continue iterating. Eventually,
1447       // all edges will get a weight, or iteration will stop when
1448       // it reaches SampleProfileMaxPropagateIterations.
1449       if (NumUnknownEdges <= 1) {
1450         uint64_t &BBWeight = BlockWeights[EC];
1451         if (NumUnknownEdges == 0) {
1452           if (!VisitedBlocks.count(EC)) {
1453             // If we already know the weight of all edges, the weight of the
1454             // basic block can be computed. It should be no larger than the sum
1455             // of all edge weights.
1456             if (TotalWeight > BBWeight) {
1457               BBWeight = TotalWeight;
1458               Changed = true;
1459               LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
1460                                 << " known. Set weight for block: ";
1461                          printBlockWeight(dbgs(), BB););
1462             }
1463           } else if (NumTotalEdges == 1 &&
1464                      EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1465             // If there is only one edge for the visited basic block, use the
1466             // block weight to adjust edge weight if edge weight is smaller.
1467             EdgeWeights[SingleEdge] = BlockWeights[EC];
1468             Changed = true;
1469           }
1470         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
1471           // If there is a single unknown edge and the block has been
1472           // visited, then we can compute E's weight.
1473           if (BBWeight >= TotalWeight)
1474             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1475           else
1476             EdgeWeights[UnknownEdge] = 0;
1477           const BasicBlock *OtherEC;
1478           if (i == 0)
1479             OtherEC = EquivalenceClass[UnknownEdge.first];
1480           else
1481             OtherEC = EquivalenceClass[UnknownEdge.second];
1482           // Edge weights should never exceed the BB weights it connects.
1483           if (VisitedBlocks.count(OtherEC) &&
1484               EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1485             EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
1486           VisitedEdges.insert(UnknownEdge);
1487           Changed = true;
1488           LLVM_DEBUG(dbgs() << "Set weight for edge: ";
1489                      printEdgeWeight(dbgs(), UnknownEdge));
1490         }
1491       } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1492         // If a block Weights 0, all its in/out edges should weight 0.
1493         if (i == 0) {
1494           for (auto *Pred : Predecessors[BB]) {
1495             Edge E = std::make_pair(Pred, BB);
1496             EdgeWeights[E] = 0;
1497             VisitedEdges.insert(E);
1498           }
1499         } else {
1500           for (auto *Succ : Successors[BB]) {
1501             Edge E = std::make_pair(BB, Succ);
1502             EdgeWeights[E] = 0;
1503             VisitedEdges.insert(E);
1504           }
1505         }
1506       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
1507         uint64_t &BBWeight = BlockWeights[BB];
1508         // We have a self-referential edge and the weight of BB is known.
1509         if (BBWeight >= TotalWeight)
1510           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1511         else
1512           EdgeWeights[SelfReferentialEdge] = 0;
1513         VisitedEdges.insert(SelfReferentialEdge);
1514         Changed = true;
1515         LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
1516                    printEdgeWeight(dbgs(), SelfReferentialEdge));
1517       }
1518       if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1519         BlockWeights[EC] = TotalWeight;
1520         VisitedBlocks.insert(EC);
1521         Changed = true;
1522       }
1523     }
1524   }
1525 
1526   return Changed;
1527 }
1528 
1529 /// Build in/out edge lists for each basic block in the CFG.
1530 ///
1531 /// We are interested in unique edges. If a block B1 has multiple
1532 /// edges to another block B2, we only add a single B1->B2 edge.
1533 void SampleProfileLoader::buildEdges(Function &F) {
1534   for (auto &BI : F) {
1535     BasicBlock *B1 = &BI;
1536 
1537     // Add predecessors for B1.
1538     SmallPtrSet<BasicBlock *, 16> Visited;
1539     if (!Predecessors[B1].empty())
1540       llvm_unreachable("Found a stale predecessors list in a basic block.");
1541     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
1542       BasicBlock *B2 = *PI;
1543       if (Visited.insert(B2).second)
1544         Predecessors[B1].push_back(B2);
1545     }
1546 
1547     // Add successors for B1.
1548     Visited.clear();
1549     if (!Successors[B1].empty())
1550       llvm_unreachable("Found a stale successors list in a basic block.");
1551     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
1552       BasicBlock *B2 = *SI;
1553       if (Visited.insert(B2).second)
1554         Successors[B1].push_back(B2);
1555     }
1556   }
1557 }
1558 
1559 /// Returns the sorted CallTargetMap \p M by count in descending order.
1560 static SmallVector<InstrProfValueData, 2> GetSortedValueDataFromCallTargets(
1561     const SampleRecord::CallTargetMap & M) {
1562   SmallVector<InstrProfValueData, 2> R;
1563   for (const auto &I : SampleRecord::SortCallTargets(M)) {
1564     R.emplace_back(InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
1565   }
1566   return R;
1567 }
1568 
1569 /// Propagate weights into edges
1570 ///
1571 /// The following rules are applied to every block BB in the CFG:
1572 ///
1573 /// - If BB has a single predecessor/successor, then the weight
1574 ///   of that edge is the weight of the block.
1575 ///
1576 /// - If all incoming or outgoing edges are known except one, and the
1577 ///   weight of the block is already known, the weight of the unknown
1578 ///   edge will be the weight of the block minus the sum of all the known
1579 ///   edges. If the sum of all the known edges is larger than BB's weight,
1580 ///   we set the unknown edge weight to zero.
1581 ///
1582 /// - If there is a self-referential edge, and the weight of the block is
1583 ///   known, the weight for that edge is set to the weight of the block
1584 ///   minus the weight of the other incoming edges to that block (if
1585 ///   known).
1586 void SampleProfileLoader::propagateWeights(Function &F) {
1587   bool Changed = true;
1588   unsigned I = 0;
1589 
1590   // If BB weight is larger than its corresponding loop's header BB weight,
1591   // use the BB weight to replace the loop header BB weight.
1592   for (auto &BI : F) {
1593     BasicBlock *BB = &BI;
1594     Loop *L = LI->getLoopFor(BB);
1595     if (!L) {
1596       continue;
1597     }
1598     BasicBlock *Header = L->getHeader();
1599     if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1600       BlockWeights[Header] = BlockWeights[BB];
1601     }
1602   }
1603 
1604   // Before propagation starts, build, for each block, a list of
1605   // unique predecessors and successors. This is necessary to handle
1606   // identical edges in multiway branches. Since we visit all blocks and all
1607   // edges of the CFG, it is cleaner to build these lists once at the start
1608   // of the pass.
1609   buildEdges(F);
1610 
1611   // Propagate until we converge or we go past the iteration limit.
1612   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1613     Changed = propagateThroughEdges(F, false);
1614   }
1615 
1616   // The first propagation propagates BB counts from annotated BBs to unknown
1617   // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
1618   // to propagate edge weights.
1619   VisitedEdges.clear();
1620   Changed = true;
1621   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1622     Changed = propagateThroughEdges(F, false);
1623   }
1624 
1625   // The 3rd propagation pass allows adjust annotated BB weights that are
1626   // obviously wrong.
1627   Changed = true;
1628   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1629     Changed = propagateThroughEdges(F, true);
1630   }
1631 
1632   // Generate MD_prof metadata for every branch instruction using the
1633   // edge weights computed during propagation.
1634   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1635   LLVMContext &Ctx = F.getContext();
1636   MDBuilder MDB(Ctx);
1637   for (auto &BI : F) {
1638     BasicBlock *BB = &BI;
1639 
1640     if (BlockWeights[BB]) {
1641       for (auto &I : BB->getInstList()) {
1642         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1643           continue;
1644         if (!cast<CallBase>(I).getCalledFunction()) {
1645           const DebugLoc &DLoc = I.getDebugLoc();
1646           if (!DLoc)
1647             continue;
1648           const DILocation *DIL = DLoc;
1649           const FunctionSamples *FS = findFunctionSamples(I);
1650           if (!FS)
1651             continue;
1652           auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1653           auto T = FS->findCallTargetMapAt(CallSite);
1654           if (!T || T.get().empty())
1655             continue;
1656           SmallVector<InstrProfValueData, 2> SortedCallTargets =
1657               GetSortedValueDataFromCallTargets(T.get());
1658           uint64_t Sum;
1659           findIndirectCallFunctionSamples(I, Sum);
1660           annotateValueSite(*I.getParent()->getParent()->getParent(), I,
1661                             SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1662                             SortedCallTargets.size());
1663         } else if (!isa<IntrinsicInst>(&I)) {
1664           I.setMetadata(LLVMContext::MD_prof,
1665                         MDB.createBranchWeights(
1666                             {static_cast<uint32_t>(BlockWeights[BB])}));
1667         }
1668       }
1669     }
1670     Instruction *TI = BB->getTerminator();
1671     if (TI->getNumSuccessors() == 1)
1672       continue;
1673     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1674       continue;
1675 
1676     DebugLoc BranchLoc = TI->getDebugLoc();
1677     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1678                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
1679                                       : Twine("<UNKNOWN LOCATION>"))
1680                       << ".\n");
1681     SmallVector<uint32_t, 4> Weights;
1682     uint32_t MaxWeight = 0;
1683     Instruction *MaxDestInst;
1684     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1685       BasicBlock *Succ = TI->getSuccessor(I);
1686       Edge E = std::make_pair(BB, Succ);
1687       uint64_t Weight = EdgeWeights[E];
1688       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1689       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1690       // if needed. Sample counts in profiles are 64-bit unsigned values,
1691       // but internally branch weights are expressed as 32-bit values.
1692       if (Weight > std::numeric_limits<uint32_t>::max()) {
1693         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1694         Weight = std::numeric_limits<uint32_t>::max();
1695       }
1696       // Weight is added by one to avoid propagation errors introduced by
1697       // 0 weights.
1698       Weights.push_back(static_cast<uint32_t>(Weight + 1));
1699       if (Weight != 0) {
1700         if (Weight > MaxWeight) {
1701           MaxWeight = Weight;
1702           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1703         }
1704       }
1705     }
1706 
1707     uint64_t TempWeight;
1708     // Only set weights if there is at least one non-zero weight.
1709     // In any other case, let the analyzer set weights.
1710     // Do not set weights if the weights are present. In ThinLTO, the profile
1711     // annotation is done twice. If the first annotation already set the
1712     // weights, the second pass does not need to set it.
1713     if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
1714       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1715       TI->setMetadata(LLVMContext::MD_prof,
1716                       MDB.createBranchWeights(Weights));
1717       ORE->emit([&]() {
1718         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1719                << "most popular destination for conditional branches at "
1720                << ore::NV("CondBranchesLoc", BranchLoc);
1721       });
1722     } else {
1723       LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1724     }
1725   }
1726 }
1727 
1728 /// Get the line number for the function header.
1729 ///
1730 /// This looks up function \p F in the current compilation unit and
1731 /// retrieves the line number where the function is defined. This is
1732 /// line 0 for all the samples read from the profile file. Every line
1733 /// number is relative to this line.
1734 ///
1735 /// \param F  Function object to query.
1736 ///
1737 /// \returns the line number where \p F is defined. If it returns 0,
1738 ///          it means that there is no debug information available for \p F.
1739 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1740   if (DISubprogram *S = F.getSubprogram())
1741     return S->getLine();
1742 
1743   if (NoWarnSampleUnused)
1744     return 0;
1745 
1746   // If the start of \p F is missing, emit a diagnostic to inform the user
1747   // about the missed opportunity.
1748   F.getContext().diagnose(DiagnosticInfoSampleProfile(
1749       "No debug information found in function " + F.getName() +
1750           ": Function profile not used",
1751       DS_Warning));
1752   return 0;
1753 }
1754 
1755 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1756   DT.reset(new DominatorTree);
1757   DT->recalculate(F);
1758 
1759   PDT.reset(new PostDominatorTree(F));
1760 
1761   LI.reset(new LoopInfo);
1762   LI->analyze(*DT);
1763 }
1764 
1765 /// Generate branch weight metadata for all branches in \p F.
1766 ///
1767 /// Branch weights are computed out of instruction samples using a
1768 /// propagation heuristic. Propagation proceeds in 3 phases:
1769 ///
1770 /// 1- Assignment of block weights. All the basic blocks in the function
1771 ///    are initial assigned the same weight as their most frequently
1772 ///    executed instruction.
1773 ///
1774 /// 2- Creation of equivalence classes. Since samples may be missing from
1775 ///    blocks, we can fill in the gaps by setting the weights of all the
1776 ///    blocks in the same equivalence class to the same weight. To compute
1777 ///    the concept of equivalence, we use dominance and loop information.
1778 ///    Two blocks B1 and B2 are in the same equivalence class if B1
1779 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
1780 ///
1781 /// 3- Propagation of block weights into edges. This uses a simple
1782 ///    propagation heuristic. The following rules are applied to every
1783 ///    block BB in the CFG:
1784 ///
1785 ///    - If BB has a single predecessor/successor, then the weight
1786 ///      of that edge is the weight of the block.
1787 ///
1788 ///    - If all the edges are known except one, and the weight of the
1789 ///      block is already known, the weight of the unknown edge will
1790 ///      be the weight of the block minus the sum of all the known
1791 ///      edges. If the sum of all the known edges is larger than BB's weight,
1792 ///      we set the unknown edge weight to zero.
1793 ///
1794 ///    - If there is a self-referential edge, and the weight of the block is
1795 ///      known, the weight for that edge is set to the weight of the block
1796 ///      minus the weight of the other incoming edges to that block (if
1797 ///      known).
1798 ///
1799 /// Since this propagation is not guaranteed to finalize for every CFG, we
1800 /// only allow it to proceed for a limited number of iterations (controlled
1801 /// by -sample-profile-max-propagate-iterations).
1802 ///
1803 /// FIXME: Try to replace this propagation heuristic with a scheme
1804 /// that is guaranteed to finalize. A work-list approach similar to
1805 /// the standard value propagation algorithm used by SSA-CCP might
1806 /// work here.
1807 ///
1808 /// Once all the branch weights are computed, we emit the MD_prof
1809 /// metadata on BB using the computed values for each of its branches.
1810 ///
1811 /// \param F The function to query.
1812 ///
1813 /// \returns true if \p F was modified. Returns false, otherwise.
1814 bool SampleProfileLoader::emitAnnotations(Function &F) {
1815   bool Changed = false;
1816 
1817   if (FunctionSamples::ProfileIsProbeBased) {
1818     if (!ProbeManager->profileIsValid(F, *Samples)) {
1819       LLVM_DEBUG(
1820           dbgs() << "Profile is invalid due to CFG mismatch for Function "
1821                  << F.getName());
1822       ++NumMismatchedProfile;
1823       return false;
1824     }
1825     ++NumMatchedProfile;
1826   } else {
1827     if (getFunctionLoc(F) == 0)
1828       return false;
1829 
1830     LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1831                       << F.getName() << ": " << getFunctionLoc(F) << "\n");
1832   }
1833 
1834   DenseSet<GlobalValue::GUID> InlinedGUIDs;
1835   Changed |= inlineHotFunctions(F, InlinedGUIDs);
1836 
1837   // Compute basic block weights.
1838   Changed |= computeBlockWeights(F);
1839 
1840   if (Changed) {
1841     // Add an entry count to the function using the samples gathered at the
1842     // function entry.
1843     // Sets the GUIDs that are inlined in the profiled binary. This is used
1844     // for ThinLink to make correct liveness analysis, and also make the IR
1845     // match the profiled binary before annotation.
1846     F.setEntryCount(
1847         ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
1848         &InlinedGUIDs);
1849 
1850     // Compute dominance and loop info needed for propagation.
1851     computeDominanceAndLoopInfo(F);
1852 
1853     // Find equivalence classes.
1854     findEquivalenceClasses(F);
1855 
1856     // Propagate weights to all edges.
1857     propagateWeights(F);
1858   }
1859 
1860   // If coverage checking was requested, compute it now.
1861   if (SampleProfileRecordCoverage) {
1862     unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1863     unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
1864     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1865     if (Coverage < SampleProfileRecordCoverage) {
1866       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1867           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1868           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1869               Twine(Coverage) + "%) were applied",
1870           DS_Warning));
1871     }
1872   }
1873 
1874   if (SampleProfileSampleCoverage) {
1875     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1876     uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
1877     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1878     if (Coverage < SampleProfileSampleCoverage) {
1879       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1880           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1881           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1882               Twine(Coverage) + "%) were applied",
1883           DS_Warning));
1884     }
1885   }
1886   return Changed;
1887 }
1888 
1889 char SampleProfileLoaderLegacyPass::ID = 0;
1890 
1891 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1892                       "Sample Profile loader", false, false)
1893 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1894 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1895 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1896 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1897 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1898                     "Sample Profile loader", false, false)
1899 
1900 std::vector<Function *>
1901 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1902   std::vector<Function *> FunctionOrderList;
1903   FunctionOrderList.reserve(M.size());
1904 
1905   if (!ProfileTopDownLoad || CG == nullptr) {
1906     if (ProfileMergeInlinee) {
1907       // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1908       // because the profile for a function may be used for the profile
1909       // annotation of its outline copy before the profile merging of its
1910       // non-inlined inline instances, and that is not the way how
1911       // ProfileMergeInlinee is supposed to work.
1912       ProfileMergeInlinee = false;
1913     }
1914 
1915     for (Function &F : M)
1916       if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1917         FunctionOrderList.push_back(&F);
1918     return FunctionOrderList;
1919   }
1920 
1921   assert(&CG->getModule() == &M);
1922   scc_iterator<CallGraph *> CGI = scc_begin(CG);
1923   while (!CGI.isAtEnd()) {
1924     for (CallGraphNode *node : *CGI) {
1925       auto F = node->getFunction();
1926       if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1927         FunctionOrderList.push_back(F);
1928     }
1929     ++CGI;
1930   }
1931 
1932   std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1933   return FunctionOrderList;
1934 }
1935 
1936 bool SampleProfileLoader::doInitialization(Module &M,
1937                                            FunctionAnalysisManager *FAM) {
1938   auto &Ctx = M.getContext();
1939 
1940   auto ReaderOrErr =
1941       SampleProfileReader::create(Filename, Ctx, RemappingFilename);
1942   if (std::error_code EC = ReaderOrErr.getError()) {
1943     std::string Msg = "Could not open profile: " + EC.message();
1944     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1945     return false;
1946   }
1947   Reader = std::move(ReaderOrErr.get());
1948   Reader->collectFuncsFrom(M);
1949   ProfileIsValid = (Reader->read() == sampleprof_error::success);
1950   PSL = Reader->getProfileSymbolList();
1951 
1952   // While profile-sample-accurate is on, ignore symbol list.
1953   ProfAccForSymsInList =
1954       ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1955   if (ProfAccForSymsInList) {
1956     NamesInProfile.clear();
1957     if (auto NameTable = Reader->getNameTable())
1958       NamesInProfile.insert(NameTable->begin(), NameTable->end());
1959   }
1960 
1961   if (FAM && !ProfileInlineReplayFile.empty()) {
1962     ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>(
1963         *FAM, Ctx, ProfileInlineReplayFile);
1964     if (!ExternalInlineAdvisor->areReplayRemarksLoaded())
1965       ExternalInlineAdvisor.reset();
1966   }
1967 
1968   // Apply tweaks if context-sensitive profile is available.
1969   if (Reader->profileIsCS()) {
1970     ProfileIsCS = true;
1971     FunctionSamples::ProfileIsCS = true;
1972 
1973     // Tracker for profiles under different context
1974     ContextTracker =
1975         std::make_unique<SampleContextTracker>(Reader->getProfiles());
1976   }
1977 
1978   // Load pseudo probe descriptors for probe-based function samples.
1979   if (Reader->profileIsProbeBased()) {
1980     ProbeManager = std::make_unique<PseudoProbeManager>(M);
1981     if (!ProbeManager->moduleIsProbed(M)) {
1982       const char *Msg =
1983           "Pseudo-probe-based profile requires SampleProfileProbePass";
1984       Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1985       return false;
1986     }
1987   }
1988 
1989   return true;
1990 }
1991 
1992 ModulePass *llvm::createSampleProfileLoaderPass() {
1993   return new SampleProfileLoaderLegacyPass();
1994 }
1995 
1996 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1997   return new SampleProfileLoaderLegacyPass(Name);
1998 }
1999 
2000 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
2001                                       ProfileSummaryInfo *_PSI, CallGraph *CG) {
2002   if (!ProfileIsValid)
2003     return false;
2004   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
2005 
2006   PSI = _PSI;
2007   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
2008     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
2009                         ProfileSummary::PSK_Sample);
2010     PSI->refresh();
2011   }
2012   // Compute the total number of samples collected in this profile.
2013   for (const auto &I : Reader->getProfiles())
2014     TotalCollectedSamples += I.second.getTotalSamples();
2015 
2016   auto Remapper = Reader->getRemapper();
2017   // Populate the symbol map.
2018   for (const auto &N_F : M.getValueSymbolTable()) {
2019     StringRef OrigName = N_F.getKey();
2020     Function *F = dyn_cast<Function>(N_F.getValue());
2021     if (F == nullptr)
2022       continue;
2023     SymbolMap[OrigName] = F;
2024     auto pos = OrigName.find('.');
2025     if (pos != StringRef::npos) {
2026       StringRef NewName = OrigName.substr(0, pos);
2027       auto r = SymbolMap.insert(std::make_pair(NewName, F));
2028       // Failiing to insert means there is already an entry in SymbolMap,
2029       // thus there are multiple functions that are mapped to the same
2030       // stripped name. In this case of name conflicting, set the value
2031       // to nullptr to avoid confusion.
2032       if (!r.second)
2033         r.first->second = nullptr;
2034       OrigName = NewName;
2035     }
2036     // Insert the remapped names into SymbolMap.
2037     if (Remapper) {
2038       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2039         if (*MapName == OrigName)
2040           continue;
2041         SymbolMap.insert(std::make_pair(*MapName, F));
2042       }
2043     }
2044   }
2045 
2046   bool retval = false;
2047   for (auto F : buildFunctionOrder(M, CG)) {
2048     assert(!F->isDeclaration());
2049     clearFunctionData();
2050     retval |= runOnFunction(*F, AM);
2051   }
2052 
2053   // Account for cold calls not inlined....
2054   if (!ProfileIsCS)
2055     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
2056          notInlinedCallInfo)
2057       updateProfileCallee(pair.first, pair.second.entryCount);
2058 
2059   return retval;
2060 }
2061 
2062 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
2063   ACT = &getAnalysis<AssumptionCacheTracker>();
2064   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
2065   TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
2066   ProfileSummaryInfo *PSI =
2067       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2068   return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
2069 }
2070 
2071 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
2072   DILocation2SampleMap.clear();
2073   // By default the entry count is initialized to -1, which will be treated
2074   // conservatively by getEntryCount as the same as unknown (None). This is
2075   // to avoid newly added code to be treated as cold. If we have samples
2076   // this will be overwritten in emitAnnotations.
2077   uint64_t initialEntryCount = -1;
2078 
2079   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
2080   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
2081     // initialize all the function entry counts to 0. It means all the
2082     // functions without profile will be regarded as cold.
2083     initialEntryCount = 0;
2084     // profile-sample-accurate is a user assertion which has a higher precedence
2085     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2086     ProfAccForSymsInList = false;
2087   }
2088 
2089   // PSL -- profile symbol list include all the symbols in sampled binary.
2090   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2091   // old functions without samples being cold, without having to worry
2092   // about new and hot functions being mistakenly treated as cold.
2093   if (ProfAccForSymsInList) {
2094     // Initialize the entry count to 0 for functions in the list.
2095     if (PSL->contains(F.getName()))
2096       initialEntryCount = 0;
2097 
2098     // Function in the symbol list but without sample will be regarded as
2099     // cold. To minimize the potential negative performance impact it could
2100     // have, we want to be a little conservative here saying if a function
2101     // shows up in the profile, no matter as outline function, inline instance
2102     // or call targets, treat the function as not being cold. This will handle
2103     // the cases such as most callsites of a function are inlined in sampled
2104     // binary but not inlined in current build (because of source code drift,
2105     // imprecise debug information, or the callsites are all cold individually
2106     // but not cold accumulatively...), so the outline function showing up as
2107     // cold in sampled binary will actually not be cold after current build.
2108     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2109     if (NamesInProfile.count(CanonName))
2110       initialEntryCount = -1;
2111   }
2112 
2113   F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
2114   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
2115   if (AM) {
2116     auto &FAM =
2117         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
2118             .getManager();
2119     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2120   } else {
2121     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2122     ORE = OwnedORE.get();
2123   }
2124 
2125   if (ProfileIsCS)
2126     Samples = ContextTracker->getBaseSamplesFor(F);
2127   else
2128     Samples = Reader->getSamplesFor(F);
2129 
2130   if (Samples && !Samples->empty())
2131     return emitAnnotations(F);
2132   return false;
2133 }
2134 
2135 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
2136                                                ModuleAnalysisManager &AM) {
2137   FunctionAnalysisManager &FAM =
2138       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2139 
2140   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2141     return FAM.getResult<AssumptionAnalysis>(F);
2142   };
2143   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
2144     return FAM.getResult<TargetIRAnalysis>(F);
2145   };
2146   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2147     return FAM.getResult<TargetLibraryAnalysis>(F);
2148   };
2149 
2150   SampleProfileLoader SampleLoader(
2151       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
2152       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
2153                                        : ProfileRemappingFileName,
2154       IsThinLTOPreLink, GetAssumptionCache, GetTTI, GetTLI);
2155 
2156   if (!SampleLoader.doInitialization(M, &FAM))
2157     return PreservedAnalyses::all();
2158 
2159   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2160   CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
2161   if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
2162     return PreservedAnalyses::all();
2163 
2164   return PreservedAnalyses::none();
2165 }
2166