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