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