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