14d71113cSDiego Novillo //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
24d71113cSDiego Novillo //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64d71113cSDiego Novillo //
74d71113cSDiego Novillo //===----------------------------------------------------------------------===//
84d71113cSDiego Novillo //
94d71113cSDiego Novillo // This file implements the SampleProfileLoader transformation. This pass
104d71113cSDiego Novillo // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
114d71113cSDiego Novillo // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
124d71113cSDiego Novillo // profile information in the given profile.
134d71113cSDiego Novillo //
144d71113cSDiego Novillo // This pass generates branch weight annotations on the IR:
154d71113cSDiego Novillo //
164d71113cSDiego Novillo // - prof: Represents branch weights. This annotation is added to branches
174d71113cSDiego Novillo //      to indicate the weights of each edge coming out of the branch.
184d71113cSDiego Novillo //      The weight of each edge is the weight of the target block for
194d71113cSDiego Novillo //      that edge. The weight of a block B is computed as the maximum
204d71113cSDiego Novillo //      number of samples found in B.
214d71113cSDiego Novillo //
224d71113cSDiego Novillo //===----------------------------------------------------------------------===//
234d71113cSDiego Novillo 
24301627f8SDavid Blaikie #include "llvm/Transforms/IPO/SampleProfile.h"
25f27d161bSEugene Zelenko #include "llvm/ADT/ArrayRef.h"
264d71113cSDiego Novillo #include "llvm/ADT/DenseMap.h"
27f27d161bSEugene Zelenko #include "llvm/ADT/DenseSet.h"
286bae5973SWenlei He #include "llvm/ADT/PriorityQueue.h"
29532196d8SWenlei He #include "llvm/ADT/SCCIterator.h"
30f27d161bSEugene Zelenko #include "llvm/ADT/SmallVector.h"
31d275a064SWenlei He #include "llvm/ADT/Statistic.h"
32f27d161bSEugene Zelenko #include "llvm/ADT/StringMap.h"
334d71113cSDiego Novillo #include "llvm/ADT/StringRef.h"
34f27d161bSEugene Zelenko #include "llvm/ADT/Twine.h"
35aec2fa35SDaniel Jasper #include "llvm/Analysis/AssumptionCache.h"
36f9f3c34eSWenlei He #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
37532196d8SWenlei He #include "llvm/Analysis/CallGraph.h"
387c8a6936SWenlei He #include "llvm/Analysis/InlineAdvisor.h"
393a81f84dSDehao Chen #include "llvm/Analysis/InlineCost.h"
400965da20SAdam Nemet #include "llvm/Analysis/OptimizationRemarkEmitter.h"
410c2f6be6SWei Mi #include "llvm/Analysis/ProfileSummaryInfo.h"
425caad9b5Smodimo #include "llvm/Analysis/ReplayInlineAdvisor.h"
43f9ca75f1STeresa Johnson #include "llvm/Analysis/TargetLibraryInfo.h"
443a81f84dSDehao Chen #include "llvm/Analysis/TargetTransformInfo.h"
45f27d161bSEugene Zelenko #include "llvm/IR/BasicBlock.h"
46f27d161bSEugene Zelenko #include "llvm/IR/DebugLoc.h"
474d71113cSDiego Novillo #include "llvm/IR/DiagnosticInfo.h"
484d71113cSDiego Novillo #include "llvm/IR/Function.h"
4977079003SDehao Chen #include "llvm/IR/GlobalValue.h"
50f27d161bSEugene Zelenko #include "llvm/IR/InstrTypes.h"
51f27d161bSEugene Zelenko #include "llvm/IR/Instruction.h"
524d71113cSDiego Novillo #include "llvm/IR/Instructions.h"
53d38392ecSXinliang David Li #include "llvm/IR/IntrinsicInst.h"
544d71113cSDiego Novillo #include "llvm/IR/LLVMContext.h"
554d71113cSDiego Novillo #include "llvm/IR/MDBuilder.h"
564d71113cSDiego Novillo #include "llvm/IR/Module.h"
57f27d161bSEugene Zelenko #include "llvm/IR/PassManager.h"
58f1985a3fSserge-sans-paille #include "llvm/IR/PseudoProbe.h"
591ea8bd81SDehao Chen #include "llvm/IR/ValueSymbolTable.h"
6005da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
614d71113cSDiego Novillo #include "llvm/Pass.h"
6277079003SDehao Chen #include "llvm/ProfileData/InstrProf.h"
63f27d161bSEugene Zelenko #include "llvm/ProfileData/SampleProf.h"
644d71113cSDiego Novillo #include "llvm/ProfileData/SampleProfReader.h"
65f27d161bSEugene Zelenko #include "llvm/Support/Casting.h"
664d71113cSDiego Novillo #include "llvm/Support/CommandLine.h"
674d71113cSDiego Novillo #include "llvm/Support/Debug.h"
688e7df83eSDehao Chen #include "llvm/Support/ErrorOr.h"
694d71113cSDiego Novillo #include "llvm/Support/raw_ostream.h"
704d71113cSDiego Novillo #include "llvm/Transforms/IPO.h"
713e3fc431SHongtao Yu #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
726b989a17SWenlei He #include "llvm/Transforms/IPO/SampleContextTracker.h"
73ac068e01SHongtao Yu #include "llvm/Transforms/IPO/SampleProfileProbe.h"
74274df5eaSDehao Chen #include "llvm/Transforms/Instrumentation.h"
75e363d2ceSMatthew Simpson #include "llvm/Transforms/Utils/CallPromotionUtils.h"
7657d1dda5SDehao Chen #include "llvm/Transforms/Utils/Cloning.h"
777397905aSRong Xu #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
787397905aSRong Xu #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
79f27d161bSEugene Zelenko #include <algorithm>
80f27d161bSEugene Zelenko #include <cassert>
81f27d161bSEugene Zelenko #include <cstdint>
82f27d161bSEugene Zelenko #include <functional>
83f27d161bSEugene Zelenko #include <limits>
84f27d161bSEugene Zelenko #include <map>
85f27d161bSEugene Zelenko #include <memory>
864b99b58aSWenlei He #include <queue>
87f27d161bSEugene Zelenko #include <string>
88f27d161bSEugene Zelenko #include <system_error>
89f27d161bSEugene Zelenko #include <utility>
90f27d161bSEugene Zelenko #include <vector>
914d71113cSDiego Novillo 
924d71113cSDiego Novillo using namespace llvm;
934d71113cSDiego Novillo using namespace sampleprof;
947397905aSRong Xu using namespace llvm::sampleprofutil;
95e5b8de2fSEaswaran Raman using ProfileCount = Function::ProfileCount;
964d71113cSDiego Novillo #define DEBUG_TYPE "sample-profile"
97d275a064SWenlei He #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
98d275a064SWenlei He 
99d275a064SWenlei He STATISTIC(NumCSInlined,
100d275a064SWenlei He           "Number of functions inlined with context sensitive profile");
101d275a064SWenlei He STATISTIC(NumCSNotInlined,
102d275a064SWenlei He           "Number of functions not inlined with context sensitive profile");
103ac068e01SHongtao Yu STATISTIC(NumMismatchedProfile,
104ac068e01SHongtao Yu           "Number of functions with CFG mismatched profile");
105ac068e01SHongtao Yu STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
1063d89b3cbSHongtao Yu STATISTIC(NumDuplicatedInlinesite,
1073d89b3cbSHongtao Yu           "Number of inlined callsites with a partial distribution factor");
1084d71113cSDiego Novillo 
1096bae5973SWenlei He STATISTIC(NumCSInlinedHitMinLimit,
1106bae5973SWenlei He           "Number of functions with FDO inline stopped due to min size limit");
1116bae5973SWenlei He STATISTIC(NumCSInlinedHitMaxLimit,
1126bae5973SWenlei He           "Number of functions with FDO inline stopped due to max size limit");
1136bae5973SWenlei He STATISTIC(
1146bae5973SWenlei He     NumCSInlinedHitGrowthLimit,
1156bae5973SWenlei He     "Number of functions with FDO inline stopped due to growth size limit");
1166bae5973SWenlei He 
1174d71113cSDiego Novillo // Command line option to specify the file to read samples from. This is
1184d71113cSDiego Novillo // mainly used for debugging.
1194d71113cSDiego Novillo static cl::opt<std::string> SampleProfileFile(
1204d71113cSDiego Novillo     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
1214d71113cSDiego Novillo     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
122f27d161bSEugene Zelenko 
1236c676628SRichard Smith // The named file contains a set of transformations that may have been applied
1246c676628SRichard Smith // to the symbol names between the program from which the sample data was
1256c676628SRichard Smith // collected and the current program's symbols.
1266c676628SRichard Smith static cl::opt<std::string> SampleProfileRemappingFile(
1276c676628SRichard Smith     "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
1286c676628SRichard Smith     cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
1296c676628SRichard Smith 
13066c6c5abSWei Mi static cl::opt<bool> ProfileSampleAccurate(
13166c6c5abSWei Mi     "profile-sample-accurate", cl::Hidden, cl::init(false),
13266c6c5abSWei Mi     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
13366c6c5abSWei Mi              "callsite and function as having 0 samples. Otherwise, treat "
13466c6c5abSWei Mi              "un-sampled callsites and functions conservatively as unknown. "));
13566c6c5abSWei Mi 
1365f187f0aSWenlei He static cl::opt<bool> ProfileSampleBlockAccurate(
1375f187f0aSWenlei He     "profile-sample-block-accurate", cl::Hidden, cl::init(false),
1385f187f0aSWenlei He     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
1395f187f0aSWenlei He              "branches and calls as having 0 samples. Otherwise, treat "
1405f187f0aSWenlei He              "them conservatively as unknown. "));
1415f187f0aSWenlei He 
142f0c4e70eSWei Mi static cl::opt<bool> ProfileAccurateForSymsInList(
143557efc9aSFangrui Song     "profile-accurate-for-symsinlist", cl::Hidden, cl::init(true),
144f0c4e70eSWei Mi     cl::desc("For symbols in profile symbol list, regard their profiles to "
145f0c4e70eSWei Mi              "be accurate. It may be overriden by profile-sample-accurate. "));
146f0c4e70eSWei Mi 
147e503fd85SWenlei He static cl::opt<bool> ProfileMergeInlinee(
148e32469a1SWei Mi     "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
149e503fd85SWenlei He     cl::desc("Merge past inlinee's profile to outline version if sample "
150e32469a1SWei Mi              "profile loader decided not to inline a call site. It will "
151e32469a1SWei Mi              "only be enabled when top-down order of profile loading is "
152e32469a1SWei Mi              "enabled. "));
153e503fd85SWenlei He 
154532196d8SWenlei He static cl::opt<bool> ProfileTopDownLoad(
155e32469a1SWei Mi     "sample-profile-top-down-load", cl::Hidden, cl::init(true),
156532196d8SWenlei He     cl::desc("Do profile annotation and inlining for functions in top-down "
157e32469a1SWei Mi              "order of call graph during sample profile loading. It only "
158e32469a1SWei Mi              "works for new pass manager. "));
159532196d8SWenlei He 
1603e3fc431SHongtao Yu static cl::opt<bool>
1613e3fc431SHongtao Yu     UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
1623e3fc431SHongtao Yu                          cl::desc("Process functions in a top-down order "
1633e3fc431SHongtao Yu                                   "defined by the profiled call graph when "
1643e3fc431SHongtao Yu                                   "-sample-profile-top-down-load is on."));
165bf317f66SHongtao Yu cl::opt<bool>
166bf317f66SHongtao Yu     SortProfiledSCC("sort-profiled-scc-member", cl::init(true), cl::Hidden,
167bf317f66SHongtao Yu                     cl::desc("Sort profiled recursion by edge weights."));
168de40f6d6SHongtao Yu 
1697b61ae68SWenlei He static cl::opt<bool> ProfileSizeInline(
1707b61ae68SWenlei He     "sample-profile-inline-size", cl::Hidden, cl::init(false),
1717b61ae68SWenlei He     cl::desc("Inline cold call sites in profile loader if it's beneficial "
1727b61ae68SWenlei He              "for code size."));
1737b61ae68SWenlei He 
174e2074de6Sminglotus-6 // Since profiles are consumed by many passes, turning on this option has
175e2074de6Sminglotus-6 // side effects. For instance, pre-link SCC inliner would see merged profiles
176e2074de6Sminglotus-6 // and inline the hot functions (that are skipped in this pass).
177142cedc2Sminglotus-6 static cl::opt<bool> DisableSampleLoaderInlining(
178142cedc2Sminglotus-6     "disable-sample-loader-inlining", cl::Hidden, cl::init(false),
179e2074de6Sminglotus-6     cl::desc("If true, artifically skip inline transformation in sample-loader "
180e2074de6Sminglotus-6              "pass, and merge (or scale) profiles (as configured by "
181e2074de6Sminglotus-6              "--sample-profile-merge-inlinee)."));
182142cedc2Sminglotus-6 
18330b02323SWenlei He cl::opt<int> ProfileInlineGrowthLimit(
1846bae5973SWenlei He     "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
1856bae5973SWenlei He     cl::desc("The size growth ratio limit for proirity-based sample profile "
1866bae5973SWenlei He              "loader inlining."));
1876bae5973SWenlei He 
18830b02323SWenlei He cl::opt<int> ProfileInlineLimitMin(
1896bae5973SWenlei He     "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
1906bae5973SWenlei He     cl::desc("The lower bound of size growth limit for "
1916bae5973SWenlei He              "proirity-based sample profile loader inlining."));
1926bae5973SWenlei He 
19330b02323SWenlei He cl::opt<int> ProfileInlineLimitMax(
1946bae5973SWenlei He     "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
1956bae5973SWenlei He     cl::desc("The upper bound of size growth limit for "
1966bae5973SWenlei He              "proirity-based sample profile loader inlining."));
1976bae5973SWenlei He 
19830b02323SWenlei He cl::opt<int> SampleHotCallSiteThreshold(
19930b02323SWenlei He     "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
20030b02323SWenlei He     cl::desc("Hot callsite threshold for proirity-based sample profile loader "
20130b02323SWenlei He              "inlining."));
20230b02323SWenlei He 
20330b02323SWenlei He cl::opt<int> SampleColdCallSiteThreshold(
20430b02323SWenlei He     "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
20530b02323SWenlei He     cl::desc("Threshold for inlining cold callsites"));
20630b02323SWenlei He 
207f0d41b58Swlei static cl::opt<unsigned> ProfileICPRelativeHotness(
208f0d41b58Swlei     "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25),
2096bae5973SWenlei He     cl::desc(
210f0d41b58Swlei         "Relative hotness percentage threshold for indirect "
2116bae5973SWenlei He         "call promotion in proirity-based sample profile loader inlining."));
2126bae5973SWenlei He 
213f0d41b58Swlei static cl::opt<unsigned> ProfileICPRelativeHotnessSkip(
214f0d41b58Swlei     "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1),
215f0d41b58Swlei     cl::desc(
216f0d41b58Swlei         "Skip relative hotness check for ICP up to given number of targets."));
217f0d41b58Swlei 
2186bae5973SWenlei He static cl::opt<bool> CallsitePrioritizedInline(
219557efc9aSFangrui Song     "sample-profile-prioritized-inline", cl::Hidden,
220557efc9aSFangrui Song 
2216bae5973SWenlei He     cl::desc("Use call site prioritized inlining for sample profile loader."
2226bae5973SWenlei He              "Currently only CSSPGO is supported."));
2236bae5973SWenlei He 
224a45d72e0SWenlei He static cl::opt<bool> UsePreInlinerDecision(
225557efc9aSFangrui Song     "sample-profile-use-preinliner", cl::Hidden,
226557efc9aSFangrui Song 
227a45d72e0SWenlei He     cl::desc("Use the preinliner decisions stored in profile context."));
228a45d72e0SWenlei He 
229f7fff46aSWenlei He static cl::opt<bool> AllowRecursiveInline(
230557efc9aSFangrui Song     "sample-profile-recursive-inline", cl::Hidden,
231557efc9aSFangrui Song 
232f7fff46aSWenlei He     cl::desc("Allow sample loader inliner to inline recursive calls."));
233f7fff46aSWenlei He 
234577e58bcSWenlei He static cl::opt<std::string> ProfileInlineReplayFile(
235577e58bcSWenlei He     "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
236577e58bcSWenlei He     cl::desc(
237577e58bcSWenlei He         "Optimization remarks file containing inline remarks to be replayed "
238577e58bcSWenlei He         "by inlining from sample profile loader."),
239577e58bcSWenlei He     cl::Hidden);
240577e58bcSWenlei He 
2415caad9b5Smodimo static cl::opt<ReplayInlinerSettings::Scope> ProfileInlineReplayScope(
2425caad9b5Smodimo     "sample-profile-inline-replay-scope",
2435caad9b5Smodimo     cl::init(ReplayInlinerSettings::Scope::Function),
2445caad9b5Smodimo     cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function, "Function",
245313c657fSmodimo                           "Replay on functions that have remarks associated "
246313c657fSmodimo                           "with them (default)"),
2475caad9b5Smodimo                clEnumValN(ReplayInlinerSettings::Scope::Module, "Module",
248313c657fSmodimo                           "Replay on the entire module")),
249313c657fSmodimo     cl::desc("Whether inline replay should be applied to the entire "
250313c657fSmodimo              "Module or just the Functions (default) that are present as "
251313c657fSmodimo              "callers in remarks during sample profile inlining."),
252313c657fSmodimo     cl::Hidden);
253313c657fSmodimo 
2545caad9b5Smodimo static cl::opt<ReplayInlinerSettings::Fallback> ProfileInlineReplayFallback(
2555caad9b5Smodimo     "sample-profile-inline-replay-fallback",
2565caad9b5Smodimo     cl::init(ReplayInlinerSettings::Fallback::Original),
2575caad9b5Smodimo     cl::values(
2585caad9b5Smodimo         clEnumValN(
2595caad9b5Smodimo             ReplayInlinerSettings::Fallback::Original, "Original",
2605caad9b5Smodimo             "All decisions not in replay send to original advisor (default)"),
2615caad9b5Smodimo         clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline,
2625caad9b5Smodimo                    "AlwaysInline", "All decisions not in replay are inlined"),
2635caad9b5Smodimo         clEnumValN(ReplayInlinerSettings::Fallback::NeverInline, "NeverInline",
2645caad9b5Smodimo                    "All decisions not in replay are not inlined")),
2655caad9b5Smodimo     cl::desc("How sample profile inline replay treats sites that don't come "
2665caad9b5Smodimo              "from the replay. Original: defers to original advisor, "
2675caad9b5Smodimo              "AlwaysInline: inline all sites not in replay, NeverInline: "
2685caad9b5Smodimo              "inline no sites not in replay"),
2695caad9b5Smodimo     cl::Hidden);
2705caad9b5Smodimo 
2715caad9b5Smodimo static cl::opt<CallSiteFormat::Format> ProfileInlineReplayFormat(
2725caad9b5Smodimo     "sample-profile-inline-replay-format",
2735caad9b5Smodimo     cl::init(CallSiteFormat::Format::LineColumnDiscriminator),
2745caad9b5Smodimo     cl::values(
2755caad9b5Smodimo         clEnumValN(CallSiteFormat::Format::Line, "Line", "<Line Number>"),
2765caad9b5Smodimo         clEnumValN(CallSiteFormat::Format::LineColumn, "LineColumn",
2775caad9b5Smodimo                    "<Line Number>:<Column Number>"),
2785caad9b5Smodimo         clEnumValN(CallSiteFormat::Format::LineDiscriminator,
2795caad9b5Smodimo                    "LineDiscriminator", "<Line Number>.<Discriminator>"),
2805caad9b5Smodimo         clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator,
2815caad9b5Smodimo                    "LineColumnDiscriminator",
2825caad9b5Smodimo                    "<Line Number>:<Column Number>.<Discriminator> (default)")),
2835caad9b5Smodimo     cl::desc("How sample profile inline replay file is formatted"), cl::Hidden);
2845caad9b5Smodimo 
2852357d293SWei Mi static cl::opt<unsigned>
2862357d293SWei Mi     MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
2872357d293SWei Mi                      cl::desc("Max number of promotions for a single indirect "
2882357d293SWei Mi                               "call callsite in sample profile loader"));
2895fb65c02SWei Mi 
2904ca6e37bSHongtao Yu static cl::opt<bool> OverwriteExistingWeights(
2914ca6e37bSHongtao Yu     "overwrite-existing-weights", cl::Hidden, cl::init(false),
2924ca6e37bSHongtao Yu     cl::desc("Ignore existing branch weights on IR and always overwrite."));
2934ca6e37bSHongtao Yu 
294bc856eb3SMingming Liu static cl::opt<bool> AnnotateSampleProfileInlinePhase(
295bc856eb3SMingming Liu     "annotate-sample-profile-inline-phase", cl::Hidden, cl::init(false),
296bc856eb3SMingming Liu     cl::desc("Annotate LTO phase (prelink / postlink), or main (no LTO) for "
297bc856eb3SMingming Liu              "sample-profile inline pass name."));
298bc856eb3SMingming Liu 
299dee058c6SHongtao Yu extern cl::opt<bool> EnableExtTspBlockPlacement;
300dee058c6SHongtao Yu 
3014d71113cSDiego Novillo namespace {
302f27d161bSEugene Zelenko 
303f27d161bSEugene Zelenko using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
304f27d161bSEugene Zelenko using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
305f27d161bSEugene Zelenko using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
306f27d161bSEugene Zelenko using EdgeWeightMap = DenseMap<Edge, uint64_t>;
307f27d161bSEugene Zelenko using BlockEdgeMap =
308f27d161bSEugene Zelenko     DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
3094d71113cSDiego Novillo 
3104b99b58aSWenlei He class GUIDToFuncNameMapper {
3114b99b58aSWenlei He public:
GUIDToFuncNameMapper(Module & M,SampleProfileReader & Reader,DenseMap<uint64_t,StringRef> & GUIDToFuncNameMap)3124b99b58aSWenlei He   GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
3134b99b58aSWenlei He                        DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
3144b99b58aSWenlei He       : CurrentReader(Reader), CurrentModule(M),
3154b99b58aSWenlei He         CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
316ebad6788SWei Mi     if (!CurrentReader.useMD5())
3174b99b58aSWenlei He       return;
3184b99b58aSWenlei He 
3194b99b58aSWenlei He     for (const auto &F : CurrentModule) {
3204b99b58aSWenlei He       StringRef OrigName = F.getName();
3214b99b58aSWenlei He       CurrentGUIDToFuncNameMap.insert(
3224b99b58aSWenlei He           {Function::getGUID(OrigName), OrigName});
3234b99b58aSWenlei He 
3244b99b58aSWenlei He       // Local to global var promotion used by optimization like thinlto
3254b99b58aSWenlei He       // will rename the var and add suffix like ".llvm.xxx" to the
3264b99b58aSWenlei He       // original local name. In sample profile, the suffixes of function
3274b99b58aSWenlei He       // names are all stripped. Since it is possible that the mapper is
3284b99b58aSWenlei He       // built in post-thin-link phase and var promotion has been done,
3294b99b58aSWenlei He       // we need to add the substring of function name without the suffix
3304b99b58aSWenlei He       // into the GUIDToFuncNameMap.
3314b99b58aSWenlei He       StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
3324b99b58aSWenlei He       if (CanonName != OrigName)
3334b99b58aSWenlei He         CurrentGUIDToFuncNameMap.insert(
3344b99b58aSWenlei He             {Function::getGUID(CanonName), CanonName});
3354b99b58aSWenlei He     }
3364b99b58aSWenlei He 
3374b99b58aSWenlei He     // Update GUIDToFuncNameMap for each function including inlinees.
3384b99b58aSWenlei He     SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
3394b99b58aSWenlei He   }
3404b99b58aSWenlei He 
~GUIDToFuncNameMapper()3414b99b58aSWenlei He   ~GUIDToFuncNameMapper() {
342ebad6788SWei Mi     if (!CurrentReader.useMD5())
3434b99b58aSWenlei He       return;
3444b99b58aSWenlei He 
3454b99b58aSWenlei He     CurrentGUIDToFuncNameMap.clear();
3464b99b58aSWenlei He 
3474b99b58aSWenlei He     // Reset GUIDToFuncNameMap for of each function as they're no
3484b99b58aSWenlei He     // longer valid at this point.
3494b99b58aSWenlei He     SetGUIDToFuncNameMapForAll(nullptr);
3504b99b58aSWenlei He   }
3514b99b58aSWenlei He 
3524b99b58aSWenlei He private:
SetGUIDToFuncNameMapForAll(DenseMap<uint64_t,StringRef> * Map)3534b99b58aSWenlei He   void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
3544b99b58aSWenlei He     std::queue<FunctionSamples *> FSToUpdate;
3554b99b58aSWenlei He     for (auto &IFS : CurrentReader.getProfiles()) {
3564b99b58aSWenlei He       FSToUpdate.push(&IFS.second);
3574b99b58aSWenlei He     }
3584b99b58aSWenlei He 
3594b99b58aSWenlei He     while (!FSToUpdate.empty()) {
3604b99b58aSWenlei He       FunctionSamples *FS = FSToUpdate.front();
3614b99b58aSWenlei He       FSToUpdate.pop();
3624b99b58aSWenlei He       FS->GUIDToFuncNameMap = Map;
3634b99b58aSWenlei He       for (const auto &ICS : FS->getCallsiteSamples()) {
3644b99b58aSWenlei He         const FunctionSamplesMap &FSMap = ICS.second;
3654b99b58aSWenlei He         for (auto &IFS : FSMap) {
3664b99b58aSWenlei He           FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
3674b99b58aSWenlei He           FSToUpdate.push(&FS);
3684b99b58aSWenlei He         }
3694b99b58aSWenlei He       }
3704b99b58aSWenlei He     }
3714b99b58aSWenlei He   }
3724b99b58aSWenlei He 
3734b99b58aSWenlei He   SampleProfileReader &CurrentReader;
3744b99b58aSWenlei He   Module &CurrentModule;
3754b99b58aSWenlei He   DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
3764b99b58aSWenlei He };
3774b99b58aSWenlei He 
3786bae5973SWenlei He // Inline candidate used by iterative callsite prioritized inliner
3796bae5973SWenlei He struct InlineCandidate {
3806bae5973SWenlei He   CallBase *CallInstr;
3816bae5973SWenlei He   const FunctionSamples *CalleeSamples;
3823d89b3cbSHongtao Yu   // Prorated callsite count, which will be used to guide inlining. For example,
3833d89b3cbSHongtao Yu   // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
3843d89b3cbSHongtao Yu   // copies will get their own distribution factors and their prorated counts
3853d89b3cbSHongtao Yu   // will be used to decide if they should be inlined independently.
3866bae5973SWenlei He   uint64_t CallsiteCount;
3873d89b3cbSHongtao Yu   // Call site distribution factor to prorate the profile samples for a
3883d89b3cbSHongtao Yu   // duplicated callsite. Default value is 1.0.
3893d89b3cbSHongtao Yu   float CallsiteDistribution;
3906bae5973SWenlei He };
3916bae5973SWenlei He 
3926bae5973SWenlei He // Inline candidate comparer using call site weight
3936bae5973SWenlei He struct CandidateComparer {
operator ()__anonb9d8ce480111::CandidateComparer3946bae5973SWenlei He   bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
3956bae5973SWenlei He     if (LHS.CallsiteCount != RHS.CallsiteCount)
3966bae5973SWenlei He       return LHS.CallsiteCount < RHS.CallsiteCount;
3976bae5973SWenlei He 
3985f59f407SWenlei He     const FunctionSamples *LCS = LHS.CalleeSamples;
3995f59f407SWenlei He     const FunctionSamples *RCS = RHS.CalleeSamples;
4005f59f407SWenlei He     assert(LCS && RCS && "Expect non-null FunctionSamples");
4015f59f407SWenlei He 
4025f59f407SWenlei He     // Tie breaker using number of samples try to favor smaller functions first
4035f59f407SWenlei He     if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
4045f59f407SWenlei He       return LCS->getBodySamples().size() > RCS->getBodySamples().size();
4055f59f407SWenlei He 
4066bae5973SWenlei He     // Tie breaker using GUID so we have stable/deterministic inlining order
4075f59f407SWenlei He     return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName());
4086bae5973SWenlei He   }
4096bae5973SWenlei He };
4106bae5973SWenlei He 
4116bae5973SWenlei He using CandidateQueue =
4126bae5973SWenlei He     PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
4136bae5973SWenlei He                   CandidateComparer>;
4146bae5973SWenlei He 
415db0d7d0bSRong Xu /// Sample profile pass.
416db0d7d0bSRong Xu ///
417db0d7d0bSRong Xu /// This pass reads profile data from the file specified by
418db0d7d0bSRong Xu /// -sample-profile-file and annotates every affected function with the
419db0d7d0bSRong Xu /// profile information found in that file.
4206103b6adSRong Xu class SampleProfileLoader final
4216103b6adSRong Xu     : public SampleProfileLoaderBaseImpl<BasicBlock> {
422db0d7d0bSRong Xu public:
SampleProfileLoader(StringRef Name,StringRef RemapName,ThinOrFullLTOPhase LTOPhase,std::function<AssumptionCache & (Function &)> GetAssumptionCache,std::function<TargetTransformInfo & (Function &)> GetTargetTransformInfo,std::function<const TargetLibraryInfo & (Function &)> GetTLI)423db0d7d0bSRong Xu   SampleProfileLoader(
424db0d7d0bSRong Xu       StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
425db0d7d0bSRong Xu       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
426db0d7d0bSRong Xu       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
427db0d7d0bSRong Xu       std::function<const TargetLibraryInfo &(Function &)> GetTLI)
4285fdaaf7fSRong Xu       : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName)),
429db0d7d0bSRong Xu         GetAC(std::move(GetAssumptionCache)),
430db0d7d0bSRong Xu         GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
431bc856eb3SMingming Liu         LTOPhase(LTOPhase),
432bc856eb3SMingming Liu         AnnotatedPassName(AnnotateSampleProfileInlinePhase
433bc856eb3SMingming Liu                               ? llvm::AnnotateInlinePassName(InlineContext{
434bc856eb3SMingming Liu                                     LTOPhase, InlinePass::SampleProfileInliner})
435bc856eb3SMingming Liu                               : CSINLINE_DEBUG) {}
436db0d7d0bSRong Xu 
437db0d7d0bSRong Xu   bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
438db0d7d0bSRong Xu   bool runOnModule(Module &M, ModuleAnalysisManager *AM,
439db0d7d0bSRong Xu                    ProfileSummaryInfo *_PSI, CallGraph *CG);
440db0d7d0bSRong Xu 
441db0d7d0bSRong Xu protected:
442db0d7d0bSRong Xu   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
443db0d7d0bSRong Xu   bool emitAnnotations(Function &F);
444db0d7d0bSRong Xu   ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
445db0d7d0bSRong Xu   ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
446db0d7d0bSRong Xu   const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
447db0d7d0bSRong Xu   const FunctionSamples *
448db0d7d0bSRong Xu   findFunctionSamples(const Instruction &I) const override;
449db0d7d0bSRong Xu   std::vector<const FunctionSamples *>
450db0d7d0bSRong Xu   findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
45151ce567bSmodimo   void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
452a5d30421SWenlei He                                    DenseSet<GlobalValue::GUID> &InlinedGUIDs,
453a5d30421SWenlei He                                    const StringMap<Function *> &SymbolMap,
454a5d30421SWenlei He                                    uint64_t Threshold);
455db0d7d0bSRong Xu   // Attempt to promote indirect call and also inline the promoted call
456db0d7d0bSRong Xu   bool tryPromoteAndInlineCandidate(
457db0d7d0bSRong Xu       Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
4582357d293SWei Mi       uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
45951ce567bSmodimo 
460db0d7d0bSRong Xu   bool inlineHotFunctions(Function &F,
461db0d7d0bSRong Xu                           DenseSet<GlobalValue::GUID> &InlinedGUIDs);
46251ce567bSmodimo   Optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
46351ce567bSmodimo   bool getExternalInlineAdvisorShouldInline(CallBase &CB);
464db0d7d0bSRong Xu   InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
465db0d7d0bSRong Xu   bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
466db0d7d0bSRong Xu   bool
467db0d7d0bSRong Xu   tryInlineCandidate(InlineCandidate &Candidate,
468db0d7d0bSRong Xu                      SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
469db0d7d0bSRong Xu   bool
470db0d7d0bSRong Xu   inlineHotFunctionsWithPriority(Function &F,
471db0d7d0bSRong Xu                                  DenseSet<GlobalValue::GUID> &InlinedGUIDs);
472db0d7d0bSRong Xu   // Inline cold/small functions in addition to hot ones
473db0d7d0bSRong Xu   bool shouldInlineColdCallee(CallBase &CallInst);
474db0d7d0bSRong Xu   void emitOptimizationRemarksForInlineCandidates(
475db0d7d0bSRong Xu       const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
476db0d7d0bSRong Xu       bool Hot);
4775740bb80SHongtao Yu   void promoteMergeNotInlinedContextSamples(
4785740bb80SHongtao Yu       DenseMap<CallBase *, const FunctionSamples *> NonInlinedCallSites,
4795740bb80SHongtao Yu       const Function &F);
480db0d7d0bSRong Xu   std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
4813e3fc431SHongtao Yu   std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG);
482db0d7d0bSRong Xu   void generateMDProfMetadata(Function &F);
483db0d7d0bSRong Xu 
484db0d7d0bSRong Xu   /// Map from function name to Function *. Used to find the function from
485db0d7d0bSRong Xu   /// the function name. If the function name contains suffix, additional
486db0d7d0bSRong Xu   /// entry is added to map from the stripped name to the function if there
487db0d7d0bSRong Xu   /// is one-to-one mapping.
488db0d7d0bSRong Xu   StringMap<Function *> SymbolMap;
489db0d7d0bSRong Xu 
490db0d7d0bSRong Xu   std::function<AssumptionCache &(Function &)> GetAC;
491db0d7d0bSRong Xu   std::function<TargetTransformInfo &(Function &)> GetTTI;
492db0d7d0bSRong Xu   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
493db0d7d0bSRong Xu 
494db0d7d0bSRong Xu   /// Profile tracker for different context.
495db0d7d0bSRong Xu   std::unique_ptr<SampleContextTracker> ContextTracker;
496db0d7d0bSRong Xu 
49786341247SWei Mi   /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
498d26dae0dSDehao Chen   ///
49986341247SWei Mi   /// We need to know the LTO phase because for example in ThinLTOPrelink
50086341247SWei Mi   /// phase, in annotation, we should not promote indirect calls. Instead,
50186341247SWei Mi   /// we will mark GUIDs that needs to be annotated to the function.
502bc856eb3SMingming Liu   const ThinOrFullLTOPhase LTOPhase;
503bc856eb3SMingming Liu   const std::string AnnotatedPassName;
504d26dae0dSDehao Chen 
505798e59b8SWei Mi   /// Profle Symbol list tells whether a function name appears in the binary
506798e59b8SWei Mi   /// used to generate the current profile.
507798e59b8SWei Mi   std::unique_ptr<ProfileSymbolList> PSL;
508798e59b8SWei Mi 
5095f8f34e4SAdrian Prantl   /// Total number of samples collected in this profile.
51084f06cc8SDiego Novillo   ///
51184f06cc8SDiego Novillo   /// This is the sum of all the samples collected in all the functions executed
51284f06cc8SDiego Novillo   /// at runtime.
513f27d161bSEugene Zelenko   uint64_t TotalCollectedSamples = 0;
51451cf2604SEli Friedman 
515d2eeb251SDavid Callahan   // Information recorded when we declined to inline a call site
516d2eeb251SDavid Callahan   // because we have determined it is too cold is accumulated for
517d2eeb251SDavid Callahan   // each callee function. Initially this is just the entry count.
518d2eeb251SDavid Callahan   struct NotInlinedProfileInfo {
519d2eeb251SDavid Callahan     uint64_t entryCount;
520d2eeb251SDavid Callahan   };
521d2eeb251SDavid Callahan   DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
5224b99b58aSWenlei He 
5234b99b58aSWenlei He   // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
5244b99b58aSWenlei He   // all the function symbols defined or declared in current module.
5254b99b58aSWenlei He   DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
5265f7e822dSWei Mi 
5275f7e822dSWei Mi   // All the Names used in FunctionSamples including outline function
5285f7e822dSWei Mi   // names, inline instance names and call target names.
5295f7e822dSWei Mi   StringSet<> NamesInProfile;
5305f7e822dSWei Mi 
531f0c4e70eSWei Mi   // For symbol in profile symbol list, whether to regard their profiles
532f0c4e70eSWei Mi   // to be accurate. It is mainly decided by existance of profile symbol
533f0c4e70eSWei Mi   // list and -profile-accurate-for-symsinlist flag, but it can be
534f0c4e70eSWei Mi   // overriden by -profile-sample-accurate or profile-sample-accurate
535f0c4e70eSWei Mi   // attribute.
536f0c4e70eSWei Mi   bool ProfAccForSymsInList;
537577e58bcSWenlei He 
538577e58bcSWenlei He   // External inline advisor used to replay inline decision from remarks.
539313c657fSmodimo   std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
540ac068e01SHongtao Yu 
541ac068e01SHongtao Yu   // A pseudo probe helper to correlate the imported sample counts.
542ac068e01SHongtao Yu   std::unique_ptr<PseudoProbeManager> ProbeManager;
543bc856eb3SMingming Liu 
544bc856eb3SMingming Liu private:
getAnnotatedRemarkPassName() const545bc856eb3SMingming Liu   const char *getAnnotatedRemarkPassName() const {
546bc856eb3SMingming Liu     return AnnotatedPassName.c_str();
547bc856eb3SMingming Liu   }
5484d71113cSDiego Novillo };
549f27d161bSEugene Zelenko } // end anonymous namespace
550f27d161bSEugene Zelenko 
getInstWeight(const Instruction & Inst)55194f369fcSDehao Chen ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
552ac068e01SHongtao Yu   if (FunctionSamples::ProfileIsProbeBased)
553ac068e01SHongtao Yu     return getProbeWeight(Inst);
554ac068e01SHongtao Yu 
5554fed928fSBenjamin Kramer   const DebugLoc &DLoc = Inst.getDebugLoc();
5564d71113cSDiego Novillo   if (!DLoc)
5578e7df83eSDehao Chen     return std::error_code();
5584d71113cSDiego Novillo 
55995779597SDavid Callahan   // Ignore all intrinsics, phinodes and branch instructions.
560db0d7d0bSRong Xu   // Branch and phinodes instruction usually contains debug info from sources
561db0d7d0bSRong Xu   // outside of the residing basic block, thus we ignore them during annotation.
56295779597SDavid Callahan   if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
563a8bae823SDehao Chen     return std::error_code();
564a8bae823SDehao Chen 
5654c3d759dSHongtao Yu   // For non-CS profile, if a direct call/invoke instruction is inlined in
5664c3d759dSHongtao Yu   // profile (findCalleeFunctionSamples returns non-empty result), but not
5674c3d759dSHongtao Yu   // inlined here, it means that the inlined callsite has no sample, thus the
5684c3d759dSHongtao Yu   // call instruction should have 0 count.
5694c3d759dSHongtao Yu   // For CS profile, the callsite count of previously inlined callees is
5704c3d759dSHongtao Yu   // populated with the entry count of the callees.
571e95ae395SHongtao Yu   if (!FunctionSamples::ProfileIsCS)
5726b989a17SWenlei He     if (const auto *CB = dyn_cast<CallBase>(&Inst))
5735034df86SCraig Topper       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
574c0a1e432SDehao Chen         return 0;
575c0a1e432SDehao Chen 
576db0d7d0bSRong Xu   return getInstWeightImpl(Inst);
577db0d7d0bSRong Xu }
578db0d7d0bSRong Xu 
579e475d4d6Swlei // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight
580e475d4d6Swlei // of non-probe instruction. So if all instructions of the BB give error_code,
581e475d4d6Swlei // tell the inference algorithm to infer the BB weight.
getProbeWeight(const Instruction & Inst)582ac068e01SHongtao Yu ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
583ac068e01SHongtao Yu   assert(FunctionSamples::ProfileIsProbeBased &&
584ac068e01SHongtao Yu          "Profile is not pseudo probe based");
585ac068e01SHongtao Yu   Optional<PseudoProbe> Probe = extractProbe(Inst);
586e475d4d6Swlei   // Ignore the non-probe instruction. If none of the instruction in the BB is
587e475d4d6Swlei   // probe, we choose to infer the BB's weight.
588ac068e01SHongtao Yu   if (!Probe)
589ac068e01SHongtao Yu     return std::error_code();
590ac068e01SHongtao Yu 
591ac068e01SHongtao Yu   const FunctionSamples *FS = findFunctionSamples(Inst);
592e475d4d6Swlei   // If none of the instruction has FunctionSample, we choose to return zero
593e475d4d6Swlei   // value sample to indicate the BB is cold. This could happen when the
594e475d4d6Swlei   // instruction is from inlinee and no profile data is found.
595e475d4d6Swlei   // FIXME: This should not be affected by the source drift issue as 1) if the
596e475d4d6Swlei   // newly added function is top-level inliner, it won't match the CFG checksum
597e475d4d6Swlei   // in the function profile or 2) if it's the inlinee, the inlinee should have
598e475d4d6Swlei   // a profile, otherwise it wouldn't be inlined. For non-probe based profile,
599e475d4d6Swlei   // we can improve it by adding a switch for profile-sample-block-accurate for
600e475d4d6Swlei   // block level counts in the future.
601ac068e01SHongtao Yu   if (!FS)
602e475d4d6Swlei     return 0;
603ac068e01SHongtao Yu 
6044c3d759dSHongtao Yu   // For non-CS profile, If a direct call/invoke instruction is inlined in
6054c3d759dSHongtao Yu   // profile (findCalleeFunctionSamples returns non-empty result), but not
6064c3d759dSHongtao Yu   // inlined here, it means that the inlined callsite has no sample, thus the
6074c3d759dSHongtao Yu   // call instruction should have 0 count.
6084c3d759dSHongtao Yu   // For CS profile, the callsite count of previously inlined callees is
6094c3d759dSHongtao Yu   // populated with the entry count of the callees.
610e95ae395SHongtao Yu   if (!FunctionSamples::ProfileIsCS)
611ac068e01SHongtao Yu     if (const auto *CB = dyn_cast<CallBase>(&Inst))
612ac068e01SHongtao Yu       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
613ac068e01SHongtao Yu         return 0;
614ac068e01SHongtao Yu 
615ac068e01SHongtao Yu   const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
616ac068e01SHongtao Yu   if (R) {
6173d89b3cbSHongtao Yu     uint64_t Samples = R.get() * Probe->Factor;
618ac068e01SHongtao Yu     bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
619ac068e01SHongtao Yu     if (FirstMark) {
620ac068e01SHongtao Yu       ORE->emit([&]() {
621ac068e01SHongtao Yu         OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
622ac068e01SHongtao Yu         Remark << "Applied " << ore::NV("NumSamples", Samples);
623ac068e01SHongtao Yu         Remark << " samples from profile (ProbeId=";
624ac068e01SHongtao Yu         Remark << ore::NV("ProbeId", Probe->Id);
6253d89b3cbSHongtao Yu         Remark << ", Factor=";
6263d89b3cbSHongtao Yu         Remark << ore::NV("Factor", Probe->Factor);
6273d89b3cbSHongtao Yu         Remark << ", OriginalSamples=";
6283d89b3cbSHongtao Yu         Remark << ore::NV("OriginalSamples", R.get());
629ac068e01SHongtao Yu         Remark << ")";
630ac068e01SHongtao Yu         return Remark;
631ac068e01SHongtao Yu       });
632ac068e01SHongtao Yu     }
633ac068e01SHongtao Yu     LLVM_DEBUG(dbgs() << "    " << Probe->Id << ":" << Inst
6343d89b3cbSHongtao Yu                       << " - weight: " << R.get() << " - factor: "
6353d89b3cbSHongtao Yu                       << format("%0.2f", Probe->Factor) << ")\n");
636ac068e01SHongtao Yu     return Samples;
637ac068e01SHongtao Yu   }
638ac068e01SHongtao Yu   return R;
639ac068e01SHongtao Yu }
640ac068e01SHongtao Yu 
6415f8f34e4SAdrian Prantl /// Get the FunctionSamples for a call instruction.
6426722688eSDehao Chen ///
64341cde0b9SDehao Chen /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
6446722688eSDehao Chen /// instance in which that call instruction is calling to. It contains
6456722688eSDehao Chen /// all samples that resides in the inlined instance. We first find the
6466722688eSDehao Chen /// inlined instance in which the call instruction is from, then we
6476722688eSDehao Chen /// traverse its children to find the callsite with the matching
64841cde0b9SDehao Chen /// location.
6496722688eSDehao Chen ///
65041cde0b9SDehao Chen /// \param Inst Call/Invoke instruction to query.
6516722688eSDehao Chen ///
6526722688eSDehao Chen /// \returns The FunctionSamples pointer to the inlined instance.
6536722688eSDehao Chen const FunctionSamples *
findCalleeFunctionSamples(const CallBase & Inst) const6545034df86SCraig Topper SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
6556722688eSDehao Chen   const DILocation *DIL = Inst.getDebugLoc();
6566722688eSDehao Chen   if (!DIL) {
6576722688eSDehao Chen     return nullptr;
6586722688eSDehao Chen   }
6592c7ca9b5SDehao Chen 
6602c7ca9b5SDehao Chen   StringRef CalleeName;
6614cd8e9b1SWei Mi   if (Function *Callee = Inst.getCalledFunction())
662ee35784aSWei Mi     CalleeName = Callee->getName();
6636b989a17SWenlei He 
664e95ae395SHongtao Yu   if (FunctionSamples::ProfileIsCS)
6656b989a17SWenlei He     return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
6662c7ca9b5SDehao Chen 
6676722688eSDehao Chen   const FunctionSamples *FS = findFunctionSamples(Inst);
6686722688eSDehao Chen   if (FS == nullptr)
6696722688eSDehao Chen     return nullptr;
6706722688eSDehao Chen 
671ac068e01SHongtao Yu   return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
672c67ccf5fSWei Mi                                    CalleeName, Reader->getRemapper());
6732c7ca9b5SDehao Chen }
6742c7ca9b5SDehao Chen 
6752c7ca9b5SDehao Chen /// Returns a vector of FunctionSamples that are the indirect call targets
6763f56a05aSDehao Chen /// of \p Inst. The vector is sorted by the total number of samples. Stores
6773f56a05aSDehao Chen /// the total call count of the indirect call in \p Sum.
6782c7ca9b5SDehao Chen std::vector<const FunctionSamples *>
findIndirectCallFunctionSamples(const Instruction & Inst,uint64_t & Sum) const6792c7ca9b5SDehao Chen SampleProfileLoader::findIndirectCallFunctionSamples(
6803f56a05aSDehao Chen     const Instruction &Inst, uint64_t &Sum) const {
6812c7ca9b5SDehao Chen   const DILocation *DIL = Inst.getDebugLoc();
6822c7ca9b5SDehao Chen   std::vector<const FunctionSamples *> R;
6832c7ca9b5SDehao Chen 
6842c7ca9b5SDehao Chen   if (!DIL) {
6852c7ca9b5SDehao Chen     return R;
6862c7ca9b5SDehao Chen   }
6872c7ca9b5SDehao Chen 
6886bae5973SWenlei He   auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
6896bae5973SWenlei He     assert(L && R && "Expect non-null FunctionSamples");
690*7b81a81dSMircea Trofin     if (L->getHeadSamplesEstimate() != R->getHeadSamplesEstimate())
691*7b81a81dSMircea Trofin       return L->getHeadSamplesEstimate() > R->getHeadSamplesEstimate();
6926bae5973SWenlei He     return FunctionSamples::getGUID(L->getName()) <
6936bae5973SWenlei He            FunctionSamples::getGUID(R->getName());
6946bae5973SWenlei He   };
6956bae5973SWenlei He 
696e95ae395SHongtao Yu   if (FunctionSamples::ProfileIsCS) {
6976bae5973SWenlei He     auto CalleeSamples =
6986bae5973SWenlei He         ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
6996bae5973SWenlei He     if (CalleeSamples.empty())
7006bae5973SWenlei He       return R;
7016bae5973SWenlei He 
7026bae5973SWenlei He     // For CSSPGO, we only use target context profile's entry count
7036bae5973SWenlei He     // as that already includes both inlined callee and non-inlined ones..
7046bae5973SWenlei He     Sum = 0;
7056bae5973SWenlei He     for (const auto *const FS : CalleeSamples) {
706*7b81a81dSMircea Trofin       Sum += FS->getHeadSamplesEstimate();
7076bae5973SWenlei He       R.push_back(FS);
7086bae5973SWenlei He     }
7096bae5973SWenlei He     llvm::sort(R, FSCompare);
7106bae5973SWenlei He     return R;
7116bae5973SWenlei He   }
7126bae5973SWenlei He 
7132c7ca9b5SDehao Chen   const FunctionSamples *FS = findFunctionSamples(Inst);
7142c7ca9b5SDehao Chen   if (FS == nullptr)
7152c7ca9b5SDehao Chen     return R;
7162c7ca9b5SDehao Chen 
717ac068e01SHongtao Yu   auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
718ac068e01SHongtao Yu   auto T = FS->findCallTargetMapAt(CallSite);
7193f56a05aSDehao Chen   Sum = 0;
7203f56a05aSDehao Chen   if (T)
7213f56a05aSDehao Chen     for (const auto &T_C : T.get())
7223f56a05aSDehao Chen       Sum += T_C.second;
723ac068e01SHongtao Yu   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
724f27d161bSEugene Zelenko     if (M->empty())
7252c7ca9b5SDehao Chen       return R;
7262c7ca9b5SDehao Chen     for (const auto &NameFS : *M) {
727*7b81a81dSMircea Trofin       Sum += NameFS.second.getHeadSamplesEstimate();
7282c7ca9b5SDehao Chen       R.push_back(&NameFS.second);
7292c7ca9b5SDehao Chen     }
7306bae5973SWenlei He     llvm::sort(R, FSCompare);
7312c7ca9b5SDehao Chen   }
7322c7ca9b5SDehao Chen   return R;
7336722688eSDehao Chen }
7346722688eSDehao Chen 
7356722688eSDehao Chen const FunctionSamples *
findFunctionSamples(const Instruction & Inst) const7366722688eSDehao Chen SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
737ac068e01SHongtao Yu   if (FunctionSamples::ProfileIsProbeBased) {
738ac068e01SHongtao Yu     Optional<PseudoProbe> Probe = extractProbe(Inst);
739ac068e01SHongtao Yu     if (!Probe)
740ac068e01SHongtao Yu       return nullptr;
741ac068e01SHongtao Yu   }
742ac068e01SHongtao Yu 
7436722688eSDehao Chen   const DILocation *DIL = Inst.getDebugLoc();
7442c7ca9b5SDehao Chen   if (!DIL)
7456722688eSDehao Chen     return Samples;
7462c7ca9b5SDehao Chen 
747dee00120SDavid Callahan   auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
7486b989a17SWenlei He   if (it.second) {
749e95ae395SHongtao Yu     if (FunctionSamples::ProfileIsCS)
7506b989a17SWenlei He       it.first->second = ContextTracker->getContextSamplesFor(DIL);
7516b989a17SWenlei He     else
7526b989a17SWenlei He       it.first->second =
7536b989a17SWenlei He           Samples->findFunctionSamples(DIL, Reader->getRemapper());
7546b989a17SWenlei He   }
755dee00120SDavid Callahan   return it.first->second;
7566722688eSDehao Chen }
7576722688eSDehao Chen 
7582357d293SWei Mi /// Check whether the indirect call promotion history of \p Inst allows
7592357d293SWei Mi /// the promotion for \p Candidate.
7602357d293SWei Mi /// If the profile count for the promotion candidate \p Candidate is
7612357d293SWei Mi /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
7622357d293SWei Mi /// for \p Inst. If we already have at least MaxNumPromotions
7632357d293SWei Mi /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
7642357d293SWei Mi /// cannot promote for \p Inst anymore.
doesHistoryAllowICP(const Instruction & Inst,StringRef Candidate)7652357d293SWei Mi static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
7665fb65c02SWei Mi   uint32_t NumVals = 0;
7675fb65c02SWei Mi   uint64_t TotalCount = 0;
7685fb65c02SWei Mi   std::unique_ptr<InstrProfValueData[]> ValueData =
7695fb65c02SWei Mi       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
7705fb65c02SWei Mi   bool Valid =
7715fb65c02SWei Mi       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
7725fb65c02SWei Mi                                ValueData.get(), NumVals, TotalCount, true);
7732357d293SWei Mi   // No valid value profile so no promoted targets have been recorded
7742357d293SWei Mi   // before. Ok to do ICP.
7752357d293SWei Mi   if (!Valid)
7762357d293SWei Mi     return true;
7772357d293SWei Mi 
7782357d293SWei Mi   unsigned NumPromoted = 0;
7795fb65c02SWei Mi   for (uint32_t I = 0; I < NumVals; I++) {
7802357d293SWei Mi     if (ValueData[I].Count != NOMORE_ICP_MAGICNUM)
7812357d293SWei Mi       continue;
7822357d293SWei Mi 
7832357d293SWei Mi     // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
7842357d293SWei Mi     // metadata, it means the candidate has been promoted for this
7852357d293SWei Mi     // indirect call.
7865fb65c02SWei Mi     if (ValueData[I].Value == Function::getGUID(Candidate))
7872357d293SWei Mi       return false;
7882357d293SWei Mi     NumPromoted++;
7892357d293SWei Mi     // If already have MaxNumPromotions promotion, don't do it anymore.
7902357d293SWei Mi     if (NumPromoted == MaxNumPromotions)
7915fb65c02SWei Mi       return false;
7925fb65c02SWei Mi   }
7932357d293SWei Mi   return true;
7942357d293SWei Mi }
7955fb65c02SWei Mi 
7962357d293SWei Mi /// Update indirect call target profile metadata for \p Inst.
7972357d293SWei Mi /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
7982357d293SWei Mi /// If it is 0, it means updateIDTMetaData is used to mark a
7992357d293SWei Mi /// certain target to be promoted already. If it is not zero,
8002357d293SWei Mi /// we expect to use it to update the total count in the value profile.
8015fb65c02SWei Mi static void
updateIDTMetaData(Instruction & Inst,const SmallVectorImpl<InstrProfValueData> & CallTargets,uint64_t Sum)8025fb65c02SWei Mi updateIDTMetaData(Instruction &Inst,
8035fb65c02SWei Mi                   const SmallVectorImpl<InstrProfValueData> &CallTargets,
8042357d293SWei Mi                   uint64_t Sum) {
805f415d74dSminglotus-6   // Bail out early if MaxNumPromotions is zero.
806f415d74dSminglotus-6   // This prevents allocating an array of zero length below.
807f415d74dSminglotus-6   //
808f415d74dSminglotus-6   // Note `updateIDTMetaData` is called in two places so check
809f415d74dSminglotus-6   // `MaxNumPromotions` inside it.
810f415d74dSminglotus-6   if (MaxNumPromotions == 0)
811f415d74dSminglotus-6     return;
8125fb65c02SWei Mi   uint32_t NumVals = 0;
8132357d293SWei Mi   // OldSum is the existing total count in the value profile data.
8142357d293SWei Mi   uint64_t OldSum = 0;
8155fb65c02SWei Mi   std::unique_ptr<InstrProfValueData[]> ValueData =
8165fb65c02SWei Mi       std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
8175fb65c02SWei Mi   bool Valid =
8185fb65c02SWei Mi       getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
8192357d293SWei Mi                                ValueData.get(), NumVals, OldSum, true);
8202357d293SWei Mi 
8212357d293SWei Mi   DenseMap<uint64_t, uint64_t> ValueCountMap;
82214756b70SWei Mi   if (Sum == 0) {
82314756b70SWei Mi     assert((CallTargets.size() == 1 &&
82414756b70SWei Mi             CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
82514756b70SWei Mi            "If sum is 0, assume only one element in CallTargets "
82614756b70SWei Mi            "with count being NOMORE_ICP_MAGICNUM");
8272357d293SWei Mi     // Initialize ValueCountMap with existing value profile data.
8285fb65c02SWei Mi     if (Valid) {
8295fb65c02SWei Mi       for (uint32_t I = 0; I < NumVals; I++)
8305fb65c02SWei Mi         ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
8315fb65c02SWei Mi     }
83214756b70SWei Mi     auto Pair =
83314756b70SWei Mi         ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
83414756b70SWei Mi     // If the target already exists in value profile, decrease the total
83514756b70SWei Mi     // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
83614756b70SWei Mi     if (!Pair.second) {
83714756b70SWei Mi       OldSum -= Pair.first->second;
83814756b70SWei Mi       Pair.first->second = NOMORE_ICP_MAGICNUM;
83914756b70SWei Mi     }
84014756b70SWei Mi     Sum = OldSum;
84114756b70SWei Mi   } else {
84214756b70SWei Mi     // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
84314756b70SWei Mi     // counts in the value profile.
84414756b70SWei Mi     if (Valid) {
84514756b70SWei Mi       for (uint32_t I = 0; I < NumVals; I++) {
84614756b70SWei Mi         if (ValueData[I].Count == NOMORE_ICP_MAGICNUM)
84714756b70SWei Mi           ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
84814756b70SWei Mi       }
84914756b70SWei Mi     }
8505fb65c02SWei Mi 
8515fb65c02SWei Mi     for (const auto &Data : CallTargets) {
8525fb65c02SWei Mi       auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
8535fb65c02SWei Mi       if (Pair.second)
8545fb65c02SWei Mi         continue;
85514756b70SWei Mi       // The target represented by Data.Value has already been promoted.
85614756b70SWei Mi       // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
85714756b70SWei Mi       // Sum by Data.Count.
8582357d293SWei Mi       assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
8592357d293SWei Mi       Sum -= Data.Count;
8605fb65c02SWei Mi     }
8615fb65c02SWei Mi   }
8625fb65c02SWei Mi 
8635fb65c02SWei Mi   SmallVector<InstrProfValueData, 8> NewCallTargets;
8645fb65c02SWei Mi   for (const auto &ValueCount : ValueCountMap) {
8655fb65c02SWei Mi     NewCallTargets.emplace_back(
8665fb65c02SWei Mi         InstrProfValueData{ValueCount.first, ValueCount.second});
8675fb65c02SWei Mi   }
8682357d293SWei Mi 
8695fb65c02SWei Mi   llvm::sort(NewCallTargets,
8705fb65c02SWei Mi              [](const InstrProfValueData &L, const InstrProfValueData &R) {
8715fb65c02SWei Mi                if (L.Count != R.Count)
8725fb65c02SWei Mi                  return L.Count > R.Count;
8735fb65c02SWei Mi                return L.Value > R.Value;
8745fb65c02SWei Mi              });
8752357d293SWei Mi 
8762357d293SWei Mi   uint32_t MaxMDCount =
8772357d293SWei Mi       std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
8785fb65c02SWei Mi   annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
87914756b70SWei Mi                     NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
8805fb65c02SWei Mi }
8815fb65c02SWei Mi 
8821645f465SWenlei He /// Attempt to promote indirect call and also inline the promoted call.
8831645f465SWenlei He ///
8841645f465SWenlei He /// \param F  Caller function.
8851645f465SWenlei He /// \param Candidate  ICP and inline candidate.
8865f2d7300SHongtao Yu /// \param SumOrigin  Original sum of target counts for indirect call before
8875f2d7300SHongtao Yu ///                   promoting given candidate.
8885f2d7300SHongtao Yu /// \param Sum        Prorated sum of remaining target counts for indirect call
8895f2d7300SHongtao Yu ///                   after promoting given candidate.
8901645f465SWenlei He /// \param InlinedCallSite  Output vector for new call sites exposed after
8911645f465SWenlei He /// inlining.
tryPromoteAndInlineCandidate(Function & F,InlineCandidate & Candidate,uint64_t SumOrigin,uint64_t & Sum,SmallVector<CallBase *,8> * InlinedCallSite)8921645f465SWenlei He bool SampleProfileLoader::tryPromoteAndInlineCandidate(
8933d89b3cbSHongtao Yu     Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
8941645f465SWenlei He     SmallVector<CallBase *, 8> *InlinedCallSite) {
895e2074de6Sminglotus-6   // Bail out early if sample-loader inliner is disabled.
896e2074de6Sminglotus-6   if (DisableSampleLoaderInlining)
897e2074de6Sminglotus-6     return false;
898e2074de6Sminglotus-6 
899f415d74dSminglotus-6   // Bail out early if MaxNumPromotions is zero.
900f415d74dSminglotus-6   // This prevents allocating an array of zero length in callees below.
901f415d74dSminglotus-6   if (MaxNumPromotions == 0)
902f415d74dSminglotus-6     return false;
9035fb65c02SWei Mi   auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName();
9045fb65c02SWei Mi   auto R = SymbolMap.find(CalleeFunctionName);
9055fb65c02SWei Mi   if (R == SymbolMap.end() || !R->getValue())
9065fb65c02SWei Mi     return false;
9075fb65c02SWei Mi 
9085fb65c02SWei Mi   auto &CI = *Candidate.CallInstr;
9092357d293SWei Mi   if (!doesHistoryAllowICP(CI, R->getValue()->getName()))
9105fb65c02SWei Mi     return false;
9115fb65c02SWei Mi 
9121645f465SWenlei He   const char *Reason = "Callee function not available";
9136bae5973SWenlei He   // R->getValue() != &F is to prevent promoting a recursive call.
9146bae5973SWenlei He   // If it is a recursive call, we do not inline it as it could bloat
9156bae5973SWenlei He   // the code exponentially. There is way to better handle this, e.g.
9166bae5973SWenlei He   // clone the caller first, and inline the cloned caller if it is
9176bae5973SWenlei He   // recursive. As llvm does not inline recursive calls, we will
9186bae5973SWenlei He   // simply ignore it instead of handling it explicitly.
9195fb65c02SWei Mi   if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() &&
9206bae5973SWenlei He       R->getValue()->hasFnAttribute("use-sample-profile") &&
9215fb65c02SWei Mi       R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) {
9222357d293SWei Mi     // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
9232357d293SWei Mi     // in the value profile metadata so the target won't be promoted again.
9242357d293SWei Mi     SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
9252357d293SWei Mi         Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}};
9262357d293SWei Mi     updateIDTMetaData(CI, SortedCallTargets, 0);
9275fb65c02SWei Mi 
9285fb65c02SWei Mi     auto *DI = &pgo::promoteIndirectCall(
9295fb65c02SWei Mi         CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE);
9301645f465SWenlei He     if (DI) {
9311645f465SWenlei He       Sum -= Candidate.CallsiteCount;
9325f2d7300SHongtao Yu       // Do not prorate the indirect callsite distribution since the original
9335f2d7300SHongtao Yu       // distribution will be used to scale down non-promoted profile target
9345f2d7300SHongtao Yu       // counts later. By doing this we lose track of the real callsite count
9355f2d7300SHongtao Yu       // for the leftover indirect callsite as a trade off for accurate call
9365f2d7300SHongtao Yu       // target counts.
9375f2d7300SHongtao Yu       // TODO: Ideally we would have two separate factors, one for call site
9385f2d7300SHongtao Yu       // counts and one is used to prorate call target counts.
9393d89b3cbSHongtao Yu       // Do not update the promoted direct callsite distribution at this
9405f2d7300SHongtao Yu       // point since the original distribution combined with the callee profile
9415f2d7300SHongtao Yu       // will be used to prorate callsites from the callee if inlined. Once not
9425f2d7300SHongtao Yu       // inlined, the direct callsite distribution should be prorated so that
9435f2d7300SHongtao Yu       // the it will reflect the real callsite counts.
9441645f465SWenlei He       Candidate.CallInstr = DI;
9453d89b3cbSHongtao Yu       if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
9463d89b3cbSHongtao Yu         bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
9473d89b3cbSHongtao Yu         if (!Inlined) {
9483d89b3cbSHongtao Yu           // Prorate the direct callsite distribution so that it reflects real
9493d89b3cbSHongtao Yu           // callsite counts.
9506d5132b4Swlei           setProbeDistributionFactor(
9516d5132b4Swlei               *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
9523d89b3cbSHongtao Yu         }
9533d89b3cbSHongtao Yu         return Inlined;
9543d89b3cbSHongtao Yu       }
9556bae5973SWenlei He     }
9561645f465SWenlei He   } else {
9571645f465SWenlei He     LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
9581645f465SWenlei He                       << Candidate.CalleeSamples->getFuncName() << " because "
9591645f465SWenlei He                       << Reason << "\n");
9604f5d8303SDehao Chen   }
9614f5d8303SDehao Chen   return false;
9624f5d8303SDehao Chen }
9634f5d8303SDehao Chen 
shouldInlineColdCallee(CallBase & CallInst)9645034df86SCraig Topper bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
9657b61ae68SWenlei He   if (!ProfileSizeInline)
9667b61ae68SWenlei He     return false;
9677b61ae68SWenlei He 
9685034df86SCraig Topper   Function *Callee = CallInst.getCalledFunction();
9697b61ae68SWenlei He   if (Callee == nullptr)
9707b61ae68SWenlei He     return false;
9717b61ae68SWenlei He 
9725034df86SCraig Topper   InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
97308e2386dSMircea Trofin                                   GetAC, GetTLI);
9747b61ae68SWenlei He 
9756b989a17SWenlei He   if (Cost.isNever())
9766b989a17SWenlei He     return false;
9776b989a17SWenlei He 
9786b989a17SWenlei He   if (Cost.isAlways())
9796b989a17SWenlei He     return true;
9806b989a17SWenlei He 
9817b61ae68SWenlei He   return Cost.getCost() <= SampleColdCallSiteThreshold;
9827b61ae68SWenlei He }
9837b61ae68SWenlei He 
emitOptimizationRemarksForInlineCandidates(const SmallVectorImpl<CallBase * > & Candidates,const Function & F,bool Hot)984d275a064SWenlei He void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
9855034df86SCraig Topper     const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
986d275a064SWenlei He     bool Hot) {
987d275a064SWenlei He   for (auto I : Candidates) {
9885034df86SCraig Topper     Function *CalledFunction = I->getCalledFunction();
989d275a064SWenlei He     if (CalledFunction) {
990bc856eb3SMingming Liu       ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
991bc856eb3SMingming Liu                                            "InlineAttempt", I->getDebugLoc(),
992bc856eb3SMingming Liu                                            I->getParent())
993d275a064SWenlei He                 << "previous inlining reattempted for "
994d275a064SWenlei He                 << (Hot ? "hotness: '" : "size: '")
995d275a064SWenlei He                 << ore::NV("Callee", CalledFunction) << "' into '"
996d275a064SWenlei He                 << ore::NV("Caller", &F) << "'");
997d275a064SWenlei He     }
998d275a064SWenlei He   }
999d275a064SWenlei He }
1000d275a064SWenlei He 
findExternalInlineCandidate(CallBase * CB,const FunctionSamples * Samples,DenseSet<GlobalValue::GUID> & InlinedGUIDs,const StringMap<Function * > & SymbolMap,uint64_t Threshold)1001a5d30421SWenlei He void SampleProfileLoader::findExternalInlineCandidate(
100251ce567bSmodimo     CallBase *CB, const FunctionSamples *Samples,
100351ce567bSmodimo     DenseSet<GlobalValue::GUID> &InlinedGUIDs,
1004a5d30421SWenlei He     const StringMap<Function *> &SymbolMap, uint64_t Threshold) {
100551ce567bSmodimo 
100651ce567bSmodimo   // If ExternalInlineAdvisor wants to inline an external function
100751ce567bSmodimo   // make sure it's imported
100851ce567bSmodimo   if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
100951ce567bSmodimo     // Samples may not exist for replayed function, if so
101051ce567bSmodimo     // just add the direct GUID and move on
101151ce567bSmodimo     if (!Samples) {
101251ce567bSmodimo       InlinedGUIDs.insert(
101351ce567bSmodimo           FunctionSamples::getGUID(CB->getCalledFunction()->getName()));
101451ce567bSmodimo       return;
101551ce567bSmodimo     }
101651ce567bSmodimo     // Otherwise, drop the threshold to import everything that we can
101751ce567bSmodimo     Threshold = 0;
101851ce567bSmodimo   }
101951ce567bSmodimo 
1020a5d30421SWenlei He   assert(Samples && "expect non-null caller profile");
1021a5d30421SWenlei He 
1022a5d30421SWenlei He   // For AutoFDO profile, retrieve candidate profiles by walking over
1023a5d30421SWenlei He   // the nested inlinee profiles.
1024e95ae395SHongtao Yu   if (!FunctionSamples::ProfileIsCS) {
1025a5d30421SWenlei He     Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold);
1026a5d30421SWenlei He     return;
1027a5d30421SWenlei He   }
1028a5d30421SWenlei He 
10297e86b13cSwlei   ContextTrieNode *Caller = ContextTracker->getContextNodeForProfile(Samples);
1030a5d30421SWenlei He   std::queue<ContextTrieNode *> CalleeList;
1031a5d30421SWenlei He   CalleeList.push(Caller);
1032a5d30421SWenlei He   while (!CalleeList.empty()) {
1033a5d30421SWenlei He     ContextTrieNode *Node = CalleeList.front();
1034a5d30421SWenlei He     CalleeList.pop();
1035a5d30421SWenlei He     FunctionSamples *CalleeSample = Node->getFunctionSamples();
1036a5d30421SWenlei He     // For CSSPGO profile, retrieve candidate profile by walking over the
1037a5d30421SWenlei He     // trie built for context profile. Note that also take call targets
1038a5d30421SWenlei He     // even if callee doesn't have a corresponding context profile.
1039054487c5SWenlei He     if (!CalleeSample)
1040054487c5SWenlei He       continue;
1041054487c5SWenlei He 
1042054487c5SWenlei He     // If pre-inliner decision is used, honor that for importing as well.
1043054487c5SWenlei He     bool PreInline =
1044054487c5SWenlei He         UsePreInlinerDecision &&
1045054487c5SWenlei He         CalleeSample->getContext().hasAttribute(ContextShouldBeInlined);
1046*7b81a81dSMircea Trofin     if (!PreInline && CalleeSample->getHeadSamplesEstimate() < Threshold)
1047a5d30421SWenlei He       continue;
1048a5d30421SWenlei He 
1049a5d30421SWenlei He     StringRef Name = CalleeSample->getFuncName();
1050a5d30421SWenlei He     Function *Func = SymbolMap.lookup(Name);
1051a5d30421SWenlei He     // Add to the import list only when it's defined out of module.
1052a5d30421SWenlei He     if (!Func || Func->isDeclaration())
10537ca80300SHongtao Yu       InlinedGUIDs.insert(FunctionSamples::getGUID(CalleeSample->getName()));
1054a5d30421SWenlei He 
1055a5d30421SWenlei He     // Import hot CallTargets, which may not be available in IR because full
1056a5d30421SWenlei He     // profile annotation cannot be done until backend compilation in ThinLTO.
1057a5d30421SWenlei He     for (const auto &BS : CalleeSample->getBodySamples())
1058a5d30421SWenlei He       for (const auto &TS : BS.second.getCallTargets())
1059a5d30421SWenlei He         if (TS.getValue() > Threshold) {
1060a5d30421SWenlei He           StringRef CalleeName = CalleeSample->getFuncName(TS.getKey());
1061a5d30421SWenlei He           const Function *Callee = SymbolMap.lookup(CalleeName);
1062a5d30421SWenlei He           if (!Callee || Callee->isDeclaration())
10637ca80300SHongtao Yu             InlinedGUIDs.insert(FunctionSamples::getGUID(TS.getKey()));
1064a5d30421SWenlei He         }
1065a5d30421SWenlei He 
1066a5d30421SWenlei He     // Import hot child context profile associted with callees. Note that this
1067a5d30421SWenlei He     // may have some overlap with the call target loop above, but doing this
1068a5d30421SWenlei He     // based child context profile again effectively allow us to use the max of
1069a5d30421SWenlei He     // entry count and call target count to determine importing.
1070a5d30421SWenlei He     for (auto &Child : Node->getAllChildContext()) {
1071a5d30421SWenlei He       ContextTrieNode *CalleeNode = &Child.second;
1072a5d30421SWenlei He       CalleeList.push(CalleeNode);
1073a5d30421SWenlei He     }
1074a5d30421SWenlei He   }
1075a5d30421SWenlei He }
1076a5d30421SWenlei He 
10775f8f34e4SAdrian Prantl /// Iteratively inline hot callsites of a function.
10786722688eSDehao Chen ///
1079e2074de6Sminglotus-6 /// Iteratively traverse all callsites of the function \p F, so as to
1080e2074de6Sminglotus-6 /// find out callsites with corresponding inline instances.
1081e2074de6Sminglotus-6 ///
1082e2074de6Sminglotus-6 /// For such callsites,
1083e2074de6Sminglotus-6 /// - If it is hot enough, inline the callsites and adds callsites of the callee
1084e2074de6Sminglotus-6 ///   into the caller. If the call is an indirect call, first promote
1085274df5eaSDehao Chen ///   it to direct call. Each indirect call is limited with a single target.
10866722688eSDehao Chen ///
1087e2074de6Sminglotus-6 /// - If a callsite is not inlined, merge the its profile to the outline
1088e2074de6Sminglotus-6 ///   version (if --sample-profile-merge-inlinee is true), or scale the
1089e2074de6Sminglotus-6 ///   counters of standalone function based on the profile of inlined
1090e2074de6Sminglotus-6 ///   instances (if --sample-profile-merge-inlinee is false).
1091e2074de6Sminglotus-6 ///
1092e2074de6Sminglotus-6 ///   Later passes may consume the updated profiles.
1093e2074de6Sminglotus-6 ///
10946722688eSDehao Chen /// \param F function to perform iterative inlining.
1095c6c051f2SDehao Chen /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1096c6c051f2SDehao Chen ///     inlined in the profiled binary.
10976722688eSDehao Chen ///
10986722688eSDehao Chen /// \returns True if there is any inline happened.
inlineHotFunctions(Function & F,DenseSet<GlobalValue::GUID> & InlinedGUIDs)1099a60cdd38SDehao Chen bool SampleProfileLoader::inlineHotFunctions(
1100c6c051f2SDehao Chen     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1101f0c4e70eSWei Mi   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1102f0c4e70eSWei Mi   // Profile symbol list is ignored when profile-sample-accurate is on.
1103f0c4e70eSWei Mi   assert((!ProfAccForSymsInList ||
1104f0c4e70eSWei Mi           (!ProfileSampleAccurate &&
1105f0c4e70eSWei Mi            !F.hasFnAttribute("profile-sample-accurate"))) &&
1106f0c4e70eSWei Mi          "ProfAccForSymsInList should be false when profile-sample-accurate "
1107f0c4e70eSWei Mi          "is enabled");
1108f0c4e70eSWei Mi 
11091645f465SWenlei He   DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
11106722688eSDehao Chen   bool Changed = false;
11111645f465SWenlei He   bool LocalChanged = true;
11121645f465SWenlei He   while (LocalChanged) {
11131645f465SWenlei He     LocalChanged = false;
11145034df86SCraig Topper     SmallVector<CallBase *, 10> CIS;
11156722688eSDehao Chen     for (auto &BB : F) {
111620866ed5SDehao Chen       bool Hot = false;
11175034df86SCraig Topper       SmallVector<CallBase *, 10> AllCandidates;
11185034df86SCraig Topper       SmallVector<CallBase *, 10> ColdCandidates;
11196722688eSDehao Chen       for (auto &I : BB.getInstList()) {
112041cde0b9SDehao Chen         const FunctionSamples *FS = nullptr;
11215034df86SCraig Topper         if (auto *CB = dyn_cast<CallBase>(&I)) {
112251ce567bSmodimo           if (!isa<IntrinsicInst>(I)) {
112351ce567bSmodimo             if ((FS = findCalleeFunctionSamples(*CB))) {
1124836991d3SWei Mi               assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1125836991d3SWei Mi                      "GUIDToFuncNameMap has to be populated");
11265034df86SCraig Topper               AllCandidates.push_back(CB);
1127*7b81a81dSMircea Trofin               if (FS->getHeadSamplesEstimate() > 0 ||
1128*7b81a81dSMircea Trofin                   FunctionSamples::ProfileIsCS)
11291645f465SWenlei He                 LocalNotInlinedCallSites.try_emplace(CB, FS);
1130b8f13db5SRong Xu               if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
113120866ed5SDehao Chen                 Hot = true;
11325034df86SCraig Topper               else if (shouldInlineColdCallee(*CB))
11335034df86SCraig Topper                 ColdCandidates.push_back(CB);
113451ce567bSmodimo             } else if (getExternalInlineAdvisorShouldInline(*CB)) {
113551ce567bSmodimo               AllCandidates.push_back(CB);
113651ce567bSmodimo             }
11375034df86SCraig Topper           }
11386722688eSDehao Chen         }
11396722688eSDehao Chen       }
1140577e58bcSWenlei He       if (Hot || ExternalInlineAdvisor) {
11417b61ae68SWenlei He         CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1142d275a064SWenlei He         emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
11435034df86SCraig Topper       } else {
11447b61ae68SWenlei He         CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1145d275a064SWenlei He         emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
114620866ed5SDehao Chen       }
114741cde0b9SDehao Chen     }
11485034df86SCraig Topper     for (CallBase *I : CIS) {
11495034df86SCraig Topper       Function *CalledFunction = I->getCalledFunction();
1150fee57711SKazu Hirata       InlineCandidate Candidate = {I, LocalNotInlinedCallSites.lookup(I),
1151fee57711SKazu Hirata                                    0 /* dummy count */,
1152fee57711SKazu Hirata                                    1.0 /* dummy distribution factor */};
115350f2aa19SDehao Chen       // Do not inline recursive calls.
115450f2aa19SDehao Chen       if (CalledFunction == &F)
115550f2aa19SDehao Chen         continue;
11565034df86SCraig Topper       if (I->isIndirectCall()) {
11573f56a05aSDehao Chen         uint64_t Sum;
11583f56a05aSDehao Chen         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
11593d89b3cbSHongtao Yu           uint64_t SumOrigin = Sum;
116086341247SWei Mi           if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
116151ce567bSmodimo             findExternalInlineCandidate(I, FS, InlinedGUIDs, SymbolMap,
116294d44c97SWei Mi                                         PSI->getOrCompHotCountThreshold());
1163d26dae0dSDehao Chen             continue;
1164d26dae0dSDehao Chen           }
1165b8f13db5SRong Xu           if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1166c67ccf5fSWei Mi             continue;
1167c67ccf5fSWei Mi 
1168*7b81a81dSMircea Trofin           Candidate = {I, FS, FS->getHeadSamplesEstimate(), 1.0};
11692357d293SWei Mi           if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
11701645f465SWenlei He             LocalNotInlinedCallSites.erase(I);
11714f5d8303SDehao Chen             LocalChanged = true;
1172d2eeb251SDavid Callahan           }
1173274df5eaSDehao Chen         }
11744f5d8303SDehao Chen       } else if (CalledFunction && CalledFunction->getSubprogram() &&
11754f5d8303SDehao Chen                  !CalledFunction->isDeclaration()) {
11761645f465SWenlei He         if (tryInlineCandidate(Candidate)) {
11771645f465SWenlei He           LocalNotInlinedCallSites.erase(I);
11784f5d8303SDehao Chen           LocalChanged = true;
1179d2eeb251SDavid Callahan         }
118086341247SWei Mi       } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
118151ce567bSmodimo         findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
118251ce567bSmodimo                                     InlinedGUIDs, SymbolMap,
1183ee35784aSWei Mi                                     PSI->getOrCompHotCountThreshold());
11847963ea19SDiego Novillo       }
11856722688eSDehao Chen     }
11861645f465SWenlei He     Changed |= LocalChanged;
11876722688eSDehao Chen   }
1188d2eeb251SDavid Callahan 
11896bae5973SWenlei He   // For CS profile, profile for not inlined context will be merged when
11905740bb80SHongtao Yu   // base profile is being retrieved.
1191e36786d1SHongtao Yu   if (!FunctionSamples::ProfileIsCS)
11925740bb80SHongtao Yu     promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
11936722688eSDehao Chen   return Changed;
11946722688eSDehao Chen }
11956722688eSDehao Chen 
tryInlineCandidate(InlineCandidate & Candidate,SmallVector<CallBase *,8> * InlinedCallSites)11966bae5973SWenlei He bool SampleProfileLoader::tryInlineCandidate(
11971645f465SWenlei He     InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1198e2074de6Sminglotus-6   // Do not attempt to inline a candidate if
1199e2074de6Sminglotus-6   // --disable-sample-loader-inlining is true.
1200e2074de6Sminglotus-6   if (DisableSampleLoaderInlining)
1201e2074de6Sminglotus-6     return false;
12026bae5973SWenlei He 
12036bae5973SWenlei He   CallBase &CB = *Candidate.CallInstr;
12046bae5973SWenlei He   Function *CalledFunction = CB.getCalledFunction();
12056bae5973SWenlei He   assert(CalledFunction && "Expect a callee with definition");
12066bae5973SWenlei He   DebugLoc DLoc = CB.getDebugLoc();
12076bae5973SWenlei He   BasicBlock *BB = CB.getParent();
12086bae5973SWenlei He 
12096bae5973SWenlei He   InlineCost Cost = shouldInlineCandidate(Candidate);
12106bae5973SWenlei He   if (Cost.isNever()) {
1211bc856eb3SMingming Liu     ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1212bc856eb3SMingming Liu                                          "InlineFail", DLoc, BB)
12136bae5973SWenlei He               << "incompatible inlining");
12146bae5973SWenlei He     return false;
12156bae5973SWenlei He   }
12166bae5973SWenlei He 
12176bae5973SWenlei He   if (!Cost)
12186bae5973SWenlei He     return false;
12196bae5973SWenlei He 
12206bae5973SWenlei He   InlineFunctionInfo IFI(nullptr, GetAC);
1221051f2c14SWenlei He   IFI.UpdateProfile = false;
12223710078cSKazu Hirata   if (!InlineFunction(CB, IFI).isSuccess())
12233710078cSKazu Hirata     return false;
12243710078cSKazu Hirata 
122549d66d9fSKazu Hirata   // Merge the attributes based on the inlining.
122649d66d9fSKazu Hirata   AttributeFuncs::mergeAttributesForInlining(*BB->getParent(),
122749d66d9fSKazu Hirata                                              *CalledFunction);
122849d66d9fSKazu Hirata 
12296bae5973SWenlei He   // The call to InlineFunction erases I, so we can't pass it here.
1230bc856eb3SMingming Liu   emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(),
1231bc856eb3SMingming Liu                              Cost, true, getAnnotatedRemarkPassName());
12326bae5973SWenlei He 
12336bae5973SWenlei He   // Now populate the list of newly exposed call sites.
12341645f465SWenlei He   if (InlinedCallSites) {
12351645f465SWenlei He     InlinedCallSites->clear();
12366bae5973SWenlei He     for (auto &I : IFI.InlinedCallSites)
12371645f465SWenlei He       InlinedCallSites->push_back(I);
12381645f465SWenlei He   }
12396bae5973SWenlei He 
1240e95ae395SHongtao Yu   if (FunctionSamples::ProfileIsCS)
12416bae5973SWenlei He     ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
12426bae5973SWenlei He   ++NumCSInlined;
12433d89b3cbSHongtao Yu 
12443d89b3cbSHongtao Yu   // Prorate inlined probes for a duplicated inlining callsite which probably
12453d89b3cbSHongtao Yu   // has a distribution less than 100%. Samples for an inlinee should be
12463d89b3cbSHongtao Yu   // distributed among the copies of the original callsite based on each
12473d89b3cbSHongtao Yu   // callsite's distribution factor for counts accuracy. Note that an inlined
12483d89b3cbSHongtao Yu   // probe may come with its own distribution factor if it has been duplicated
12493d89b3cbSHongtao Yu   // in the inlinee body. The two factor are multiplied to reflect the
12503d89b3cbSHongtao Yu   // aggregation of duplication.
12513d89b3cbSHongtao Yu   if (Candidate.CallsiteDistribution < 1) {
12523d89b3cbSHongtao Yu     for (auto &I : IFI.InlinedCallSites) {
12533d89b3cbSHongtao Yu       if (Optional<PseudoProbe> Probe = extractProbe(*I))
12543d89b3cbSHongtao Yu         setProbeDistributionFactor(*I, Probe->Factor *
12553d89b3cbSHongtao Yu                                    Candidate.CallsiteDistribution);
12563d89b3cbSHongtao Yu     }
12573d89b3cbSHongtao Yu     NumDuplicatedInlinesite++;
12583d89b3cbSHongtao Yu   }
12593d89b3cbSHongtao Yu 
12606bae5973SWenlei He   return true;
12616bae5973SWenlei He }
12626bae5973SWenlei He 
getInlineCandidate(InlineCandidate * NewCandidate,CallBase * CB)12636bae5973SWenlei He bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
12646bae5973SWenlei He                                              CallBase *CB) {
12656bae5973SWenlei He   assert(CB && "Expect non-null call instruction");
12666bae5973SWenlei He 
12676bae5973SWenlei He   if (isa<IntrinsicInst>(CB))
12686bae5973SWenlei He     return false;
12696bae5973SWenlei He 
12706bae5973SWenlei He   // Find the callee's profile. For indirect call, find hottest target profile.
12716bae5973SWenlei He   const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
127251ce567bSmodimo   // If ExternalInlineAdvisor wants to inline this site, do so even
127351ce567bSmodimo   // if Samples are not present.
127451ce567bSmodimo   if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
12756bae5973SWenlei He     return false;
12766bae5973SWenlei He 
12773d89b3cbSHongtao Yu   float Factor = 1.0;
12783d89b3cbSHongtao Yu   if (Optional<PseudoProbe> Probe = extractProbe(*CB))
12793d89b3cbSHongtao Yu     Factor = Probe->Factor;
12803d89b3cbSHongtao Yu 
128107846e33SHongtao Yu   uint64_t CallsiteCount =
1282*7b81a81dSMircea Trofin       CalleeSamples ? CalleeSamples->getHeadSamplesEstimate() * Factor : 0;
12833d89b3cbSHongtao Yu   *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
12846bae5973SWenlei He   return true;
12856bae5973SWenlei He }
12866bae5973SWenlei He 
128751ce567bSmodimo Optional<InlineCost>
getExternalInlineAdvisorCost(CallBase & CB)128851ce567bSmodimo SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
12896bae5973SWenlei He   std::unique_ptr<InlineAdvice> Advice = nullptr;
12906bae5973SWenlei He   if (ExternalInlineAdvisor) {
129151ce567bSmodimo     Advice = ExternalInlineAdvisor->getAdvice(CB);
1292313c657fSmodimo     if (Advice) {
12936bae5973SWenlei He       if (!Advice->isInliningRecommended()) {
12946bae5973SWenlei He         Advice->recordUnattemptedInlining();
12956bae5973SWenlei He         return InlineCost::getNever("not previously inlined");
12966bae5973SWenlei He       }
12976bae5973SWenlei He       Advice->recordInlining();
12986bae5973SWenlei He       return InlineCost::getAlways("previously inlined");
12996bae5973SWenlei He     }
1300313c657fSmodimo   }
13016bae5973SWenlei He 
130251ce567bSmodimo   return {};
130351ce567bSmodimo }
130451ce567bSmodimo 
getExternalInlineAdvisorShouldInline(CallBase & CB)130551ce567bSmodimo bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
130651ce567bSmodimo   Optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
1307611ffcf4SKazu Hirata   return Cost ? !!Cost.value() : false;
130851ce567bSmodimo }
130951ce567bSmodimo 
131051ce567bSmodimo InlineCost
shouldInlineCandidate(InlineCandidate & Candidate)131151ce567bSmodimo SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
131251ce567bSmodimo   if (Optional<InlineCost> ReplayCost =
131351ce567bSmodimo           getExternalInlineAdvisorCost(*Candidate.CallInstr))
1314611ffcf4SKazu Hirata     return ReplayCost.value();
13156bae5973SWenlei He   // Adjust threshold based on call site hotness, only do this for callsite
13166bae5973SWenlei He   // prioritized inliner because otherwise cost-benefit check is done earlier.
13176bae5973SWenlei He   int SampleThreshold = SampleColdCallSiteThreshold;
13186bae5973SWenlei He   if (CallsitePrioritizedInline) {
13196bae5973SWenlei He     if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
13206bae5973SWenlei He       SampleThreshold = SampleHotCallSiteThreshold;
13216bae5973SWenlei He     else if (!ProfileSizeInline)
13226bae5973SWenlei He       return InlineCost::getNever("cold callsite");
13236bae5973SWenlei He   }
13246bae5973SWenlei He 
13256bae5973SWenlei He   Function *Callee = Candidate.CallInstr->getCalledFunction();
13266bae5973SWenlei He   assert(Callee && "Expect a definition for inline candidate of direct call");
13276bae5973SWenlei He 
13286bae5973SWenlei He   InlineParams Params = getInlineParams();
1329f7fff46aSWenlei He   // We will ignore the threshold from inline cost, so always get full cost.
13306bae5973SWenlei He   Params.ComputeFullInlineCost = true;
1331f7fff46aSWenlei He   Params.AllowRecursiveCall = AllowRecursiveInline;
13326bae5973SWenlei He   // Checks if there is anything in the reachable portion of the callee at
13336bae5973SWenlei He   // this callsite that makes this inlining potentially illegal. Need to
13346bae5973SWenlei He   // set ComputeFullInlineCost, otherwise getInlineCost may return early
13356bae5973SWenlei He   // when cost exceeds threshold without checking all IRs in the callee.
13366bae5973SWenlei He   // The acutal cost does not matter because we only checks isNever() to
13376bae5973SWenlei He   // see if it is legal to inline the callsite.
13386bae5973SWenlei He   InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
13396bae5973SWenlei He                                   GetTTI(*Callee), GetAC, GetTLI);
13406bae5973SWenlei He 
134148ca6da9SAdrian Kuegel   // Honor always inline and never inline from call analyzer
134248ca6da9SAdrian Kuegel   if (Cost.isNever() || Cost.isAlways())
134348ca6da9SAdrian Kuegel     return Cost;
134448ca6da9SAdrian Kuegel 
1345a45d72e0SWenlei He   // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1346a45d72e0SWenlei He   // decisions based on hotness as well as accurate function byte sizes for
1347a45d72e0SWenlei He   // given context using function/inlinee sizes from previous build. It
1348a45d72e0SWenlei He   // stores the decision in profile, and also adjust/merge context profile
1349a45d72e0SWenlei He   // aiming at better context-sensitive post-inline profile quality, assuming
1350a45d72e0SWenlei He   // all inline decision estimates are going to be honored by compiler. Here
1351a45d72e0SWenlei He   // we replay that inline decision under `sample-profile-use-preinliner`.
1352c000b8bdSWenlei He   // Note that we don't need to handle negative decision from preinliner as
1353c000b8bdSWenlei He   // context profile for not inlined calls are merged by preinliner already.
1354054487c5SWenlei He   if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1355054487c5SWenlei He     // Once two node are merged due to promotion, we're losing some context
1356054487c5SWenlei He     // so the original context-sensitive preinliner decision should be ignored
1357054487c5SWenlei He     // for SyntheticContext.
1358054487c5SWenlei He     SampleContext &Context = Candidate.CalleeSamples->getContext();
1359054487c5SWenlei He     if (!Context.hasState(SyntheticContext) &&
1360054487c5SWenlei He         Context.hasAttribute(ContextShouldBeInlined))
1361a45d72e0SWenlei He       return InlineCost::getAlways("preinliner");
1362054487c5SWenlei He   }
1363a45d72e0SWenlei He 
13641645f465SWenlei He   // For old FDO inliner, we inline the call site as long as cost is not
13651645f465SWenlei He   // "Never". The cost-benefit check is done earlier.
13661645f465SWenlei He   if (!CallsitePrioritizedInline) {
13671645f465SWenlei He     return InlineCost::get(Cost.getCost(), INT_MAX);
13681645f465SWenlei He   }
13691645f465SWenlei He 
13706bae5973SWenlei He   // Otherwise only use the cost from call analyzer, but overwite threshold with
13716bae5973SWenlei He   // Sample PGO threshold.
13726bae5973SWenlei He   return InlineCost::get(Cost.getCost(), SampleThreshold);
13736bae5973SWenlei He }
13746bae5973SWenlei He 
inlineHotFunctionsWithPriority(Function & F,DenseSet<GlobalValue::GUID> & InlinedGUIDs)13756bae5973SWenlei He bool SampleProfileLoader::inlineHotFunctionsWithPriority(
13766bae5973SWenlei He     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
13776bae5973SWenlei He   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
13786bae5973SWenlei He   // Profile symbol list is ignored when profile-sample-accurate is on.
13796bae5973SWenlei He   assert((!ProfAccForSymsInList ||
13806bae5973SWenlei He           (!ProfileSampleAccurate &&
13816bae5973SWenlei He            !F.hasFnAttribute("profile-sample-accurate"))) &&
13826bae5973SWenlei He          "ProfAccForSymsInList should be false when profile-sample-accurate "
13836bae5973SWenlei He          "is enabled");
13846bae5973SWenlei He 
13856bae5973SWenlei He   // Populating worklist with initial call sites from root inliner, along
13866bae5973SWenlei He   // with call site weights.
13876bae5973SWenlei He   CandidateQueue CQueue;
13886bae5973SWenlei He   InlineCandidate NewCandidate;
13896bae5973SWenlei He   for (auto &BB : F) {
13906bae5973SWenlei He     for (auto &I : BB.getInstList()) {
13916bae5973SWenlei He       auto *CB = dyn_cast<CallBase>(&I);
13926bae5973SWenlei He       if (!CB)
13936bae5973SWenlei He         continue;
13946bae5973SWenlei He       if (getInlineCandidate(&NewCandidate, CB))
13956bae5973SWenlei He         CQueue.push(NewCandidate);
13966bae5973SWenlei He     }
13976bae5973SWenlei He   }
13986bae5973SWenlei He 
13996bae5973SWenlei He   // Cap the size growth from profile guided inlining. This is needed even
14006bae5973SWenlei He   // though cost of each inline candidate already accounts for callee size,
14016bae5973SWenlei He   // because with top-down inlining, we can grow inliner size significantly
14026bae5973SWenlei He   // with large number of smaller inlinees each pass the cost check.
14036bae5973SWenlei He   assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
14046bae5973SWenlei He          "Max inline size limit should not be smaller than min inline size "
14056bae5973SWenlei He          "limit.");
14066bae5973SWenlei He   unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
14076bae5973SWenlei He   SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
14086bae5973SWenlei He   SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
14096bae5973SWenlei He   if (ExternalInlineAdvisor)
14106bae5973SWenlei He     SizeLimit = std::numeric_limits<unsigned>::max();
14116bae5973SWenlei He 
14125740bb80SHongtao Yu   DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
14135740bb80SHongtao Yu 
14146bae5973SWenlei He   // Perform iterative BFS call site prioritized inlining
14156bae5973SWenlei He   bool Changed = false;
14166bae5973SWenlei He   while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
14176bae5973SWenlei He     InlineCandidate Candidate = CQueue.top();
14186bae5973SWenlei He     CQueue.pop();
14196bae5973SWenlei He     CallBase *I = Candidate.CallInstr;
14206bae5973SWenlei He     Function *CalledFunction = I->getCalledFunction();
14216bae5973SWenlei He 
14226bae5973SWenlei He     if (CalledFunction == &F)
14236bae5973SWenlei He       continue;
14246bae5973SWenlei He     if (I->isIndirectCall()) {
1425e30540a6SSimon Pilgrim       uint64_t Sum = 0;
14266bae5973SWenlei He       auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
14276bae5973SWenlei He       uint64_t SumOrigin = Sum;
14283d89b3cbSHongtao Yu       Sum *= Candidate.CallsiteDistribution;
1429f0d41b58Swlei       unsigned ICPCount = 0;
14306bae5973SWenlei He       for (const auto *FS : CalleeSamples) {
14316bae5973SWenlei He         // TODO: Consider disable pre-lTO ICP for MonoLTO as well
14326bae5973SWenlei He         if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
143351ce567bSmodimo           findExternalInlineCandidate(I, FS, InlinedGUIDs, SymbolMap,
14346bae5973SWenlei He                                       PSI->getOrCompHotCountThreshold());
14356bae5973SWenlei He           continue;
14366bae5973SWenlei He         }
14373d89b3cbSHongtao Yu         uint64_t EntryCountDistributed =
1438*7b81a81dSMircea Trofin             FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
14396bae5973SWenlei He         // In addition to regular inline cost check, we also need to make sure
14406bae5973SWenlei He         // ICP isn't introducing excessive speculative checks even if individual
14416bae5973SWenlei He         // target looks beneficial to promote and inline. That means we should
14426bae5973SWenlei He         // only do ICP when there's a small number dominant targets.
1443f0d41b58Swlei         if (ICPCount >= ProfileICPRelativeHotnessSkip &&
1444f0d41b58Swlei             EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness)
14456bae5973SWenlei He           break;
14466bae5973SWenlei He         // TODO: Fix CallAnalyzer to handle all indirect calls.
14476bae5973SWenlei He         // For indirect call, we don't run CallAnalyzer to get InlineCost
14486bae5973SWenlei He         // before actual inlining. This is because we could see two different
14496bae5973SWenlei He         // types from the same definition, which makes CallAnalyzer choke as
14506bae5973SWenlei He         // it's expecting matching parameter type on both caller and callee
14516bae5973SWenlei He         // side. See example from PR18962 for the triggering cases (the bug was
14526bae5973SWenlei He         // fixed, but we generate different types).
14536bae5973SWenlei He         if (!PSI->isHotCount(EntryCountDistributed))
14546bae5973SWenlei He           break;
14551645f465SWenlei He         SmallVector<CallBase *, 8> InlinedCallSites;
14566bae5973SWenlei He         // Attach function profile for promoted indirect callee, and update
14576bae5973SWenlei He         // call site count for the promoted inline candidate too.
14583d89b3cbSHongtao Yu         Candidate = {I, FS, EntryCountDistributed,
14593d89b3cbSHongtao Yu                      Candidate.CallsiteDistribution};
14603d89b3cbSHongtao Yu         if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
14612357d293SWei Mi                                          &InlinedCallSites)) {
14626bae5973SWenlei He           for (auto *CB : InlinedCallSites) {
14636bae5973SWenlei He             if (getInlineCandidate(&NewCandidate, CB))
14646bae5973SWenlei He               CQueue.emplace(NewCandidate);
14656bae5973SWenlei He           }
1466f0d41b58Swlei           ICPCount++;
14676bae5973SWenlei He           Changed = true;
14685740bb80SHongtao Yu         } else if (!ContextTracker) {
14695740bb80SHongtao Yu           LocalNotInlinedCallSites.try_emplace(I, FS);
14706bae5973SWenlei He         }
14716bae5973SWenlei He       }
14726bae5973SWenlei He     } else if (CalledFunction && CalledFunction->getSubprogram() &&
14736bae5973SWenlei He                !CalledFunction->isDeclaration()) {
14746bae5973SWenlei He       SmallVector<CallBase *, 8> InlinedCallSites;
14751645f465SWenlei He       if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
14766bae5973SWenlei He         for (auto *CB : InlinedCallSites) {
14776bae5973SWenlei He           if (getInlineCandidate(&NewCandidate, CB))
14786bae5973SWenlei He             CQueue.emplace(NewCandidate);
14796bae5973SWenlei He         }
14806bae5973SWenlei He         Changed = true;
14815740bb80SHongtao Yu       } else if (!ContextTracker) {
14825740bb80SHongtao Yu         LocalNotInlinedCallSites.try_emplace(I, Candidate.CalleeSamples);
14836bae5973SWenlei He       }
14846bae5973SWenlei He     } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
148551ce567bSmodimo       findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
148651ce567bSmodimo                                   InlinedGUIDs, SymbolMap,
148751ce567bSmodimo                                   PSI->getOrCompHotCountThreshold());
14886bae5973SWenlei He     }
14896bae5973SWenlei He   }
14906bae5973SWenlei He 
14916bae5973SWenlei He   if (!CQueue.empty()) {
14926bae5973SWenlei He     if (SizeLimit == (unsigned)ProfileInlineLimitMax)
14936bae5973SWenlei He       ++NumCSInlinedHitMaxLimit;
14946bae5973SWenlei He     else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
14956bae5973SWenlei He       ++NumCSInlinedHitMinLimit;
14966bae5973SWenlei He     else
14976bae5973SWenlei He       ++NumCSInlinedHitGrowthLimit;
14986bae5973SWenlei He   }
14996bae5973SWenlei He 
15005740bb80SHongtao Yu   // For CS profile, profile for not inlined context will be merged when
15015740bb80SHongtao Yu   // base profile is being retrieved.
1502e36786d1SHongtao Yu   if (!FunctionSamples::ProfileIsCS)
15035740bb80SHongtao Yu     promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
15046bae5973SWenlei He   return Changed;
15056bae5973SWenlei He }
15066bae5973SWenlei He 
promoteMergeNotInlinedContextSamples(DenseMap<CallBase *,const FunctionSamples * > NonInlinedCallSites,const Function & F)15075740bb80SHongtao Yu void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
15085740bb80SHongtao Yu     DenseMap<CallBase *, const FunctionSamples *> NonInlinedCallSites,
15095740bb80SHongtao Yu     const Function &F) {
15105740bb80SHongtao Yu   // Accumulate not inlined callsite information into notInlinedSamples
15115740bb80SHongtao Yu   for (const auto &Pair : NonInlinedCallSites) {
15125740bb80SHongtao Yu     CallBase *I = Pair.getFirst();
15135740bb80SHongtao Yu     Function *Callee = I->getCalledFunction();
15145740bb80SHongtao Yu     if (!Callee || Callee->isDeclaration())
15155740bb80SHongtao Yu       continue;
15165740bb80SHongtao Yu 
1517bc856eb3SMingming Liu     ORE->emit(
1518bc856eb3SMingming Liu         OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
15195740bb80SHongtao Yu                                    I->getDebugLoc(), I->getParent())
1520bc856eb3SMingming Liu         << "previous inlining not repeated: '" << ore::NV("Callee", Callee)
1521bc856eb3SMingming Liu         << "' into '" << ore::NV("Caller", &F) << "'");
15225740bb80SHongtao Yu 
15235740bb80SHongtao Yu     ++NumCSNotInlined;
15245740bb80SHongtao Yu     const FunctionSamples *FS = Pair.getSecond();
1525*7b81a81dSMircea Trofin     if (FS->getTotalSamples() == 0 && FS->getHeadSamplesEstimate() == 0) {
15265740bb80SHongtao Yu       continue;
15275740bb80SHongtao Yu     }
15285740bb80SHongtao Yu 
152962ef77caSHongtao Yu     // Do not merge a context that is already duplicated into the base profile.
153062ef77caSHongtao Yu     if (FS->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase))
153162ef77caSHongtao Yu       continue;
153262ef77caSHongtao Yu 
15335740bb80SHongtao Yu     if (ProfileMergeInlinee) {
15345740bb80SHongtao Yu       // A function call can be replicated by optimizations like callsite
15355740bb80SHongtao Yu       // splitting or jump threading and the replicates end up sharing the
15365740bb80SHongtao Yu       // sample nested callee profile instead of slicing the original
15375740bb80SHongtao Yu       // inlinee's profile. We want to do merge exactly once by filtering out
15385740bb80SHongtao Yu       // callee profiles with a non-zero head sample count.
15395740bb80SHongtao Yu       if (FS->getHeadSamples() == 0) {
15405740bb80SHongtao Yu         // Use entry samples as head samples during the merge, as inlinees
15415740bb80SHongtao Yu         // don't have head samples.
15425740bb80SHongtao Yu         const_cast<FunctionSamples *>(FS)->addHeadSamples(
1543*7b81a81dSMircea Trofin             FS->getHeadSamplesEstimate());
15445740bb80SHongtao Yu 
15455740bb80SHongtao Yu         // Note that we have to do the merge right after processing function.
15465740bb80SHongtao Yu         // This allows OutlineFS's profile to be used for annotation during
15475740bb80SHongtao Yu         // top-down processing of functions' annotation.
15485740bb80SHongtao Yu         FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
15495740bb80SHongtao Yu         OutlineFS->merge(*FS, 1);
15505740bb80SHongtao Yu         // Set outlined profile to be synthetic to not bias the inliner.
15515740bb80SHongtao Yu         OutlineFS->SetContextSynthetic();
15525740bb80SHongtao Yu       }
15535740bb80SHongtao Yu     } else {
15545740bb80SHongtao Yu       auto pair =
15555740bb80SHongtao Yu           notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1556*7b81a81dSMircea Trofin       pair.first->second.entryCount += FS->getHeadSamplesEstimate();
15575740bb80SHongtao Yu     }
15585740bb80SHongtao Yu   }
15595740bb80SHongtao Yu }
15605740bb80SHongtao Yu 
15615d2a1a50SDehao Chen /// Returns the sorted CallTargetMap \p M by count in descending order.
15627397905aSRong Xu static SmallVector<InstrProfValueData, 2>
GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap & M)15637397905aSRong Xu GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
15645d2a1a50SDehao Chen   SmallVector<InstrProfValueData, 2> R;
15655adace35SWenlei He   for (const auto &I : SampleRecord::SortCallTargets(M)) {
15667397905aSRong Xu     R.emplace_back(
15677397905aSRong Xu         InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
15685adace35SWenlei He   }
15695d2a1a50SDehao Chen   return R;
157077079003SDehao Chen }
157177079003SDehao Chen 
1572db0d7d0bSRong Xu // Generate MD_prof metadata for every branch instruction using the
1573db0d7d0bSRong Xu // edge weights computed during propagation.
generateMDProfMetadata(Function & F)1574db0d7d0bSRong Xu void SampleProfileLoader::generateMDProfMetadata(Function &F) {
15754d71113cSDiego Novillo   // Generate MD_prof metadata for every branch instruction using the
15764d71113cSDiego Novillo   // edge weights computed during propagation.
1577d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
15787963ea19SDiego Novillo   LLVMContext &Ctx = F.getContext();
15797963ea19SDiego Novillo   MDBuilder MDB(Ctx);
15804d71113cSDiego Novillo   for (auto &BI : F) {
15814d71113cSDiego Novillo     BasicBlock *BB = &BI;
15829232f982SDehao Chen 
15839232f982SDehao Chen     if (BlockWeights[BB]) {
15849232f982SDehao Chen       for (auto &I : BB->getInstList()) {
158577079003SDehao Chen         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
158677079003SDehao Chen           continue;
15877b6ff8bfSCraig Topper         if (!cast<CallBase>(I).getCalledFunction()) {
158877079003SDehao Chen           const DebugLoc &DLoc = I.getDebugLoc();
158977079003SDehao Chen           if (!DLoc)
159077079003SDehao Chen             continue;
159177079003SDehao Chen           const DILocation *DIL = DLoc;
159277079003SDehao Chen           const FunctionSamples *FS = findFunctionSamples(I);
159377079003SDehao Chen           if (!FS)
159477079003SDehao Chen             continue;
1595ac068e01SHongtao Yu           auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1596ac068e01SHongtao Yu           auto T = FS->findCallTargetMapAt(CallSite);
1597f27d161bSEugene Zelenko           if (!T || T.get().empty())
159877079003SDehao Chen             continue;
15993d89b3cbSHongtao Yu           if (FunctionSamples::ProfileIsProbeBased) {
16004ca6e37bSHongtao Yu             // Prorate the callsite counts based on the pre-ICP distribution
16014ca6e37bSHongtao Yu             // factor to reflect what is already done to the callsite before
16024ca6e37bSHongtao Yu             // ICP, such as calliste cloning.
16033d89b3cbSHongtao Yu             if (Optional<PseudoProbe> Probe = extractProbe(I)) {
16043d89b3cbSHongtao Yu               if (Probe->Factor < 1)
16053d89b3cbSHongtao Yu                 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
16063d89b3cbSHongtao Yu             }
16073d89b3cbSHongtao Yu           }
16085d2a1a50SDehao Chen           SmallVector<InstrProfValueData, 2> SortedCallTargets =
16095adace35SWenlei He               GetSortedValueDataFromCallTargets(T.get());
1610e87b1b1dSHongtao Yu           uint64_t Sum = 0;
1611e87b1b1dSHongtao Yu           for (const auto &C : T.get())
1612e87b1b1dSHongtao Yu             Sum += C.second;
1613e87b1b1dSHongtao Yu           // With CSSPGO all indirect call targets are counted torwards the
1614e87b1b1dSHongtao Yu           // original indirect call site in the profile, including both
1615e87b1b1dSHongtao Yu           // inlined and non-inlined targets.
1616e36786d1SHongtao Yu           if (!FunctionSamples::ProfileIsCS) {
1617e87b1b1dSHongtao Yu             if (const FunctionSamplesMap *M =
1618e87b1b1dSHongtao Yu                     FS->findFunctionSamplesMapAt(CallSite)) {
1619e87b1b1dSHongtao Yu               for (const auto &NameFS : *M)
1620*7b81a81dSMircea Trofin                 Sum += NameFS.second.getHeadSamplesEstimate();
1621e87b1b1dSHongtao Yu             }
1622e87b1b1dSHongtao Yu           }
16234ca6e37bSHongtao Yu           if (Sum)
16245fb65c02SWei Mi             updateIDTMetaData(I, SortedCallTargets, Sum);
16254ca6e37bSHongtao Yu           else if (OverwriteExistingWeights)
16264ca6e37bSHongtao Yu             I.setMetadata(LLVMContext::MD_prof, nullptr);
16272c5c12c0SFangrui Song         } else if (!isa<IntrinsicInst>(&I)) {
16284901f371SWei Mi           I.setMetadata(LLVMContext::MD_prof,
16295c31b8b9SArthur Eubanks                         MDB.createBranchWeights(
16305c31b8b9SArthur Eubanks                             {static_cast<uint32_t>(BlockWeights[BB])}));
16319232f982SDehao Chen         }
16329232f982SDehao Chen       }
16335f187f0aSWenlei He     } else if (OverwriteExistingWeights || ProfileSampleBlockAccurate) {
16344ca6e37bSHongtao Yu       // Set profile metadata (possibly annotated by LTO prelink) to zero or
16354ca6e37bSHongtao Yu       // clear it for cold code.
16364ca6e37bSHongtao Yu       for (auto &I : BB->getInstList()) {
16374ca6e37bSHongtao Yu         if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
16384ca6e37bSHongtao Yu           if (cast<CallBase>(I).isIndirectCall())
16394ca6e37bSHongtao Yu             I.setMetadata(LLVMContext::MD_prof, nullptr);
16404ca6e37bSHongtao Yu           else
16414ca6e37bSHongtao Yu             I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(0));
16429232f982SDehao Chen         }
16434ca6e37bSHongtao Yu       }
16444ca6e37bSHongtao Yu     }
16454ca6e37bSHongtao Yu 
1646edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
16474d71113cSDiego Novillo     if (TI->getNumSuccessors() == 1)
16484d71113cSDiego Novillo       continue;
164922998738Sspupyrev     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) &&
165022998738Sspupyrev         !isa<IndirectBrInst>(TI))
16514d71113cSDiego Novillo       continue;
16524d71113cSDiego Novillo 
1653517e3fc3SAndrea Di Biagio     DebugLoc BranchLoc = TI->getDebugLoc();
1654d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1655517e3fc3SAndrea Di Biagio                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
1656517e3fc3SAndrea Di Biagio                                       : Twine("<UNKNOWN LOCATION>"))
1657517e3fc3SAndrea Di Biagio                       << ".\n");
16585c31b8b9SArthur Eubanks     SmallVector<uint32_t, 4> Weights;
16595c31b8b9SArthur Eubanks     uint32_t MaxWeight = 0;
166051cf2604SEli Friedman     Instruction *MaxDestInst;
16617cc2493dSspupyrev     // Since profi treats multiple edges (multiway branches) as a single edge,
16627cc2493dSspupyrev     // we need to distribute the computed weight among the branches. We do
16637cc2493dSspupyrev     // this by evenly splitting the edge weight among destinations.
16647cc2493dSspupyrev     DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
16657cc2493dSspupyrev     std::vector<uint64_t> EdgeIndex;
16667cc2493dSspupyrev     if (SampleProfileUseProfi) {
16677cc2493dSspupyrev       EdgeIndex.resize(TI->getNumSuccessors());
16687cc2493dSspupyrev       for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
16697cc2493dSspupyrev         const BasicBlock *Succ = TI->getSuccessor(I);
16707cc2493dSspupyrev         EdgeIndex[I] = EdgeMultiplicity[Succ];
16717cc2493dSspupyrev         EdgeMultiplicity[Succ]++;
16727cc2493dSspupyrev       }
16737cc2493dSspupyrev     }
16744d71113cSDiego Novillo     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
16754d71113cSDiego Novillo       BasicBlock *Succ = TI->getSuccessor(I);
16764d71113cSDiego Novillo       Edge E = std::make_pair(BB, Succ);
167738be3330SDiego Novillo       uint64_t Weight = EdgeWeights[E];
1678d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
16795c31b8b9SArthur Eubanks       // Use uint32_t saturated arithmetic to adjust the incoming weights,
16805c31b8b9SArthur Eubanks       // if needed. Sample counts in profiles are 64-bit unsigned values,
16815c31b8b9SArthur Eubanks       // but internally branch weights are expressed as 32-bit values.
16825c31b8b9SArthur Eubanks       if (Weight > std::numeric_limits<uint32_t>::max()) {
16835c31b8b9SArthur Eubanks         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
16845c31b8b9SArthur Eubanks         Weight = std::numeric_limits<uint32_t>::max();
16855c31b8b9SArthur Eubanks       }
16867cc2493dSspupyrev       if (!SampleProfileUseProfi) {
1687c0a1e432SDehao Chen         // Weight is added by one to avoid propagation errors introduced by
1688c0a1e432SDehao Chen         // 0 weights.
16895c31b8b9SArthur Eubanks         Weights.push_back(static_cast<uint32_t>(Weight + 1));
16907cc2493dSspupyrev       } else {
16917cc2493dSspupyrev         // Profi creates proper weights that do not require "+1" adjustments but
16927cc2493dSspupyrev         // we evenly split the weight among branches with the same destination.
16937cc2493dSspupyrev         uint64_t W = Weight / EdgeMultiplicity[Succ];
16947cc2493dSspupyrev         // Rounding up, if needed, so that first branches are hotter.
16957cc2493dSspupyrev         if (EdgeIndex[I] < Weight % EdgeMultiplicity[Succ])
16967cc2493dSspupyrev           W++;
16977cc2493dSspupyrev         Weights.push_back(static_cast<uint32_t>(W));
16987cc2493dSspupyrev       }
16997963ea19SDiego Novillo       if (Weight != 0) {
17007963ea19SDiego Novillo         if (Weight > MaxWeight) {
17017963ea19SDiego Novillo           MaxWeight = Weight;
170251cf2604SEli Friedman           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
17037963ea19SDiego Novillo         }
17047963ea19SDiego Novillo       }
17054d71113cSDiego Novillo     }
17064d71113cSDiego Novillo 
17074683a2efSPaul Kirth     // FIXME: Re-enable for sample profiling after investigating why the sum
17084683a2efSPaul Kirth     // of branch weights can be 0
17094683a2efSPaul Kirth     //
17104683a2efSPaul Kirth     // misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
1711bac6cd5bSPaul Kirth 
171253a0c082SDehao Chen     uint64_t TempWeight;
17134d71113cSDiego Novillo     // Only set weights if there is at least one non-zero weight.
17144d71113cSDiego Novillo     // In any other case, let the analyzer set weights.
17154ca6e37bSHongtao Yu     // Do not set weights if the weights are present unless under
17164ca6e37bSHongtao Yu     // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
17174ca6e37bSHongtao Yu     // twice. If the first annotation already set the weights, the second pass
17184ca6e37bSHongtao Yu     // does not need to set it. With OverwriteExistingWeights, Blocks with zero
17194ca6e37bSHongtao Yu     // weight should have their existing metadata (possibly annotated by LTO
17204ca6e37bSHongtao Yu     // prelink) cleared.
17214ca6e37bSHongtao Yu     if (MaxWeight > 0 &&
17224ca6e37bSHongtao Yu         (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) {
1723d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
17244ca6e37bSHongtao Yu       TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
17259590658fSVivek Pandya       ORE->emit([&]() {
17269590658fSVivek Pandya         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
172751cf2604SEli Friedman                << "most popular destination for conditional branches at "
17289590658fSVivek Pandya                << ore::NV("CondBranchesLoc", BranchLoc);
17299590658fSVivek Pandya       });
173082667d04SDehao Chen     } else {
17314ca6e37bSHongtao Yu       if (OverwriteExistingWeights) {
17324ca6e37bSHongtao Yu         TI->setMetadata(LLVMContext::MD_prof, nullptr);
17334ca6e37bSHongtao Yu         LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
17344ca6e37bSHongtao Yu       } else {
1735d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
173682667d04SDehao Chen       }
17374d71113cSDiego Novillo     }
17384d71113cSDiego Novillo   }
17394ca6e37bSHongtao Yu }
17404d71113cSDiego Novillo 
17414d71113cSDiego Novillo /// Once all the branch weights are computed, we emit the MD_prof
17424d71113cSDiego Novillo /// metadata on BB using the computed values for each of its branches.
17434d71113cSDiego Novillo ///
17444d71113cSDiego Novillo /// \param F The function to query.
17454d71113cSDiego Novillo ///
17464d71113cSDiego Novillo /// \returns true if \p F was modified. Returns false, otherwise.
emitAnnotations(Function & F)17474d71113cSDiego Novillo bool SampleProfileLoader::emitAnnotations(Function &F) {
17484d71113cSDiego Novillo   bool Changed = false;
17494d71113cSDiego Novillo 
1750ac068e01SHongtao Yu   if (FunctionSamples::ProfileIsProbeBased) {
1751ac068e01SHongtao Yu     if (!ProbeManager->profileIsValid(F, *Samples)) {
1752ac068e01SHongtao Yu       LLVM_DEBUG(
1753ac068e01SHongtao Yu           dbgs() << "Profile is invalid due to CFG mismatch for Function "
1754ac068e01SHongtao Yu                  << F.getName());
1755ac068e01SHongtao Yu       ++NumMismatchedProfile;
1756ac068e01SHongtao Yu       return false;
1757ac068e01SHongtao Yu     }
1758ac068e01SHongtao Yu     ++NumMatchedProfile;
1759ac068e01SHongtao Yu   } else {
176041dc5a6eSDehao Chen     if (getFunctionLoc(F) == 0)
17614d71113cSDiego Novillo       return false;
17624d71113cSDiego Novillo 
1763d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1764d34e60caSNicola Zaghen                       << F.getName() << ": " << getFunctionLoc(F) << "\n");
1765ac068e01SHongtao Yu   }
17664d71113cSDiego Novillo 
1767c6c051f2SDehao Chen   DenseSet<GlobalValue::GUID> InlinedGUIDs;
17685740bb80SHongtao Yu   if (CallsitePrioritizedInline)
17696bae5973SWenlei He     Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
17706bae5973SWenlei He   else
1771c6c051f2SDehao Chen     Changed |= inlineHotFunctions(F, InlinedGUIDs);
17726722688eSDehao Chen 
1773db0d7d0bSRong Xu   Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
17744d71113cSDiego Novillo 
1775db0d7d0bSRong Xu   if (Changed)
1776db0d7d0bSRong Xu     generateMDProfMetadata(F);
1777a60cdd38SDehao Chen 
1778db0d7d0bSRong Xu   emitCoverageRemarks(F);
17794d71113cSDiego Novillo   return Changed;
17804d71113cSDiego Novillo }
17814d71113cSDiego Novillo 
17823e3fc431SHongtao Yu std::unique_ptr<ProfiledCallGraph>
buildProfiledCallGraph(CallGraph & CG)17833e3fc431SHongtao Yu SampleProfileLoader::buildProfiledCallGraph(CallGraph &CG) {
17843e3fc431SHongtao Yu   std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1785e95ae395SHongtao Yu   if (FunctionSamples::ProfileIsCS)
17863e3fc431SHongtao Yu     ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
17873e3fc431SHongtao Yu   else
17883e3fc431SHongtao Yu     ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1789de40f6d6SHongtao Yu 
17903e3fc431SHongtao Yu   // Add all functions into the profiled call graph even if they are not in
17913e3fc431SHongtao Yu   // the profile. This makes sure functions missing from the profile still
17923e3fc431SHongtao Yu   // gets a chance to be processed.
17933e3fc431SHongtao Yu   for (auto &Node : CG) {
17943e3fc431SHongtao Yu     const auto *F = Node.first;
17953e3fc431SHongtao Yu     if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile"))
17963e3fc431SHongtao Yu       continue;
17973e3fc431SHongtao Yu     ProfiledCG->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F));
1798de40f6d6SHongtao Yu   }
1799de40f6d6SHongtao Yu 
18003e3fc431SHongtao Yu   return ProfiledCG;
1801de40f6d6SHongtao Yu }
1802de40f6d6SHongtao Yu 
1803532196d8SWenlei He std::vector<Function *>
buildFunctionOrder(Module & M,CallGraph * CG)1804532196d8SWenlei He SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1805532196d8SWenlei He   std::vector<Function *> FunctionOrderList;
1806532196d8SWenlei He   FunctionOrderList.reserve(M.size());
1807532196d8SWenlei He 
18083e3fc431SHongtao Yu   if (!ProfileTopDownLoad && UseProfiledCallGraph)
18093e3fc431SHongtao Yu     errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
18103e3fc431SHongtao Yu               "together with -sample-profile-top-down-load.\n";
18113e3fc431SHongtao Yu 
1812532196d8SWenlei He   if (!ProfileTopDownLoad || CG == nullptr) {
1813e32469a1SWei Mi     if (ProfileMergeInlinee) {
1814e32469a1SWei Mi       // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1815e32469a1SWei Mi       // because the profile for a function may be used for the profile
1816e32469a1SWei Mi       // annotation of its outline copy before the profile merging of its
1817e32469a1SWei Mi       // non-inlined inline instances, and that is not the way how
1818e32469a1SWei Mi       // ProfileMergeInlinee is supposed to work.
1819e32469a1SWei Mi       ProfileMergeInlinee = false;
1820e32469a1SWei Mi     }
1821e32469a1SWei Mi 
1822532196d8SWenlei He     for (Function &F : M)
18237a6c8942SWei Mi       if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1824532196d8SWenlei He         FunctionOrderList.push_back(&F);
1825532196d8SWenlei He     return FunctionOrderList;
1826532196d8SWenlei He   }
1827532196d8SWenlei He 
1828532196d8SWenlei He   assert(&CG->getModule() == &M);
1829de40f6d6SHongtao Yu 
1830e95ae395SHongtao Yu   if (UseProfiledCallGraph || (FunctionSamples::ProfileIsCS &&
1831e95ae395SHongtao Yu                                !UseProfiledCallGraph.getNumOccurrences())) {
18323e3fc431SHongtao Yu     // Use profiled call edges to augment the top-down order. There are cases
18333e3fc431SHongtao Yu     // that the top-down order computed based on the static call graph doesn't
18343e3fc431SHongtao Yu     // reflect real execution order. For example
18353e3fc431SHongtao Yu     //
18363e3fc431SHongtao Yu     // 1. Incomplete static call graph due to unknown indirect call targets.
18373e3fc431SHongtao Yu     //    Adjusting the order by considering indirect call edges from the
18383e3fc431SHongtao Yu     //    profile can enable the inlining of indirect call targets by allowing
18393e3fc431SHongtao Yu     //    the caller processed before them.
18403e3fc431SHongtao Yu     // 2. Mutual call edges in an SCC. The static processing order computed for
18413e3fc431SHongtao Yu     //    an SCC may not reflect the call contexts in the context-sensitive
18423e3fc431SHongtao Yu     //    profile, thus may cause potential inlining to be overlooked. The
18433e3fc431SHongtao Yu     //    function order in one SCC is being adjusted to a top-down order based
18443e3fc431SHongtao Yu     //    on the profile to favor more inlining. This is only a problem with CS
18453e3fc431SHongtao Yu     //    profile.
18463e3fc431SHongtao Yu     // 3. Transitive indirect call edges due to inlining. When a callee function
18473e3fc431SHongtao Yu     //    (say B) is inlined into into a caller function (say A) in LTO prelink,
18483e3fc431SHongtao Yu     //    every call edge originated from the callee B will be transferred to
18493e3fc431SHongtao Yu     //    the caller A. If any transferred edge (say A->C) is indirect, the
18503e3fc431SHongtao Yu     //    original profiled indirect edge B->C, even if considered, would not
18513e3fc431SHongtao Yu     //    enforce a top-down order from the caller A to the potential indirect
18523e3fc431SHongtao Yu     //    call target C in LTO postlink since the inlined callee B is gone from
18533e3fc431SHongtao Yu     //    the static call graph.
18543e3fc431SHongtao Yu     // 4. #3 can happen even for direct call targets, due to functions defined
18553e3fc431SHongtao Yu     //    in header files. A header function (say A), when included into source
18563e3fc431SHongtao Yu     //    files, is defined multiple times but only one definition survives due
18573e3fc431SHongtao Yu     //    to ODR. Therefore, the LTO prelink inlining done on those dropped
18583e3fc431SHongtao Yu     //    definitions can be useless based on a local file scope. More
18593e3fc431SHongtao Yu     //    importantly, the inlinee (say B), once fully inlined to a
18603e3fc431SHongtao Yu     //    to-be-dropped A, will have no profile to consume when its outlined
18613e3fc431SHongtao Yu     //    version is compiled. This can lead to a profile-less prelink
18623e3fc431SHongtao Yu     //    compilation for the outlined version of B which may be called from
18633e3fc431SHongtao Yu     //    external modules. while this isn't easy to fix, we rely on the
18643e3fc431SHongtao Yu     //    postlink AutoFDO pipeline to optimize B. Since the survived copy of
18653e3fc431SHongtao Yu     //    the A can be inlined in its local scope in prelink, it may not exist
18663e3fc431SHongtao Yu     //    in the merged IR in postlink, and we'll need the profiled call edges
18673e3fc431SHongtao Yu     //    to enforce a top-down order for the rest of the functions.
18683e3fc431SHongtao Yu     //
18693e3fc431SHongtao Yu     // Considering those cases, a profiled call graph completely independent of
18703e3fc431SHongtao Yu     // the static call graph is constructed based on profile data, where
18713e3fc431SHongtao Yu     // function objects are not even needed to handle case #3 and case 4.
18723e3fc431SHongtao Yu     //
18733e3fc431SHongtao Yu     // Note that static callgraph edges are completely ignored since they
18743e3fc431SHongtao Yu     // can be conflicting with profiled edges for cyclic SCCs and may result in
18753e3fc431SHongtao Yu     // an SCC order incompatible with profile-defined one. Using strictly
18763e3fc431SHongtao Yu     // profile order ensures a maximum inlining experience. On the other hand,
18773e3fc431SHongtao Yu     // static call edges are not so important when they don't correspond to a
18783e3fc431SHongtao Yu     // context in the profile.
1879de40f6d6SHongtao Yu 
18803e3fc431SHongtao Yu     std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(*CG);
18813e3fc431SHongtao Yu     scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1882532196d8SWenlei He     while (!CGI.isAtEnd()) {
1883bf317f66SHongtao Yu       auto Range = *CGI;
1884bf317f66SHongtao Yu       if (SortProfiledSCC) {
1885bf317f66SHongtao Yu         // Sort nodes in one SCC based on callsite hotness.
1886bf317f66SHongtao Yu         scc_member_iterator<ProfiledCallGraph *> SI(*CGI);
1887bf317f66SHongtao Yu         Range = *SI;
1888bf317f66SHongtao Yu       }
1889bf317f66SHongtao Yu       for (auto *Node : Range) {
18903e3fc431SHongtao Yu         Function *F = SymbolMap.lookup(Node->Name);
18913e3fc431SHongtao Yu         if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
18923e3fc431SHongtao Yu           FunctionOrderList.push_back(F);
1893532196d8SWenlei He       }
1894532196d8SWenlei He       ++CGI;
1895532196d8SWenlei He     }
18963e3fc431SHongtao Yu   } else {
1897de40f6d6SHongtao Yu     scc_iterator<CallGraph *> CGI = scc_begin(CG);
1898de40f6d6SHongtao Yu     while (!CGI.isAtEnd()) {
1899de40f6d6SHongtao Yu       for (CallGraphNode *Node : *CGI) {
1900de40f6d6SHongtao Yu         auto *F = Node->getFunction();
1901de40f6d6SHongtao Yu         if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1902de40f6d6SHongtao Yu           FunctionOrderList.push_back(F);
1903de40f6d6SHongtao Yu       }
1904de40f6d6SHongtao Yu       ++CGI;
1905de40f6d6SHongtao Yu     }
19063e3fc431SHongtao Yu   }
1907de40f6d6SHongtao Yu 
1908de40f6d6SHongtao Yu   LLVM_DEBUG({
1909de40f6d6SHongtao Yu     dbgs() << "Function processing order:\n";
1910de40f6d6SHongtao Yu     for (auto F : reverse(FunctionOrderList)) {
1911de40f6d6SHongtao Yu       dbgs() << F->getName() << "\n";
1912de40f6d6SHongtao Yu     }
1913de40f6d6SHongtao Yu   });
1914532196d8SWenlei He 
1915532196d8SWenlei He   std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1916532196d8SWenlei He   return FunctionOrderList;
1917532196d8SWenlei He }
1918532196d8SWenlei He 
doInitialization(Module & M,FunctionAnalysisManager * FAM)1919577e58bcSWenlei He bool SampleProfileLoader::doInitialization(Module &M,
1920577e58bcSWenlei He                                            FunctionAnalysisManager *FAM) {
19214d71113cSDiego Novillo   auto &Ctx = M.getContext();
19228c8ec1f6SWei Mi 
19238d581857SRong Xu   auto ReaderOrErr = SampleProfileReader::create(
19248d581857SRong Xu       Filename, Ctx, FSDiscriminatorPass::Base, RemappingFilename);
19254d71113cSDiego Novillo   if (std::error_code EC = ReaderOrErr.getError()) {
19264d71113cSDiego Novillo     std::string Msg = "Could not open profile: " + EC.message();
19272297a914SDavid Blaikie     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
19284d71113cSDiego Novillo     return false;
19294d71113cSDiego Novillo   }
19304d71113cSDiego Novillo   Reader = std::move(ReaderOrErr.get());
193121b1ad03SWei Mi   Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1932ee35784aSWei Mi   // set module before reading the profile so reader may be able to only
1933ee35784aSWei Mi   // read the function profiles which are used by the current module.
1934ee35784aSWei Mi   Reader->setModule(&M);
1935c9cd9a00SWei Mi   if (std::error_code EC = Reader->read()) {
1936c9cd9a00SWei Mi     std::string Msg = "profile reading failed: " + EC.message();
1937c9cd9a00SWei Mi     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1938c9cd9a00SWei Mi     return false;
1939c9cd9a00SWei Mi   }
1940c9cd9a00SWei Mi 
1941798e59b8SWei Mi   PSL = Reader->getProfileSymbolList();
19426c676628SRichard Smith 
1943f0c4e70eSWei Mi   // While profile-sample-accurate is on, ignore symbol list.
1944f0c4e70eSWei Mi   ProfAccForSymsInList =
1945f0c4e70eSWei Mi       ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1946f0c4e70eSWei Mi   if (ProfAccForSymsInList) {
19475f7e822dSWei Mi     NamesInProfile.clear();
19485f7e822dSWei Mi     if (auto NameTable = Reader->getNameTable())
19495f7e822dSWei Mi       NamesInProfile.insert(NameTable->begin(), NameTable->end());
1950b8f13db5SRong Xu     CoverageTracker.setProfAccForSymsInList(true);
19515f7e822dSWei Mi   }
19525f7e822dSWei Mi 
1953577e58bcSWenlei He   if (FAM && !ProfileInlineReplayFile.empty()) {
1954313c657fSmodimo     ExternalInlineAdvisor = getReplayInlineAdvisor(
19555caad9b5Smodimo         M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr,
19565caad9b5Smodimo         ReplayInlinerSettings{ProfileInlineReplayFile,
19575caad9b5Smodimo                               ProfileInlineReplayScope,
19585caad9b5Smodimo                               ProfileInlineReplayFallback,
19595caad9b5Smodimo                               {ProfileInlineReplayFormat}},
1960e0d06959SMingming Liu         /*EmitRemarks=*/false, InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
1961577e58bcSWenlei He   }
1962577e58bcSWenlei He 
19637a316c0aSHongtao Yu   // Apply tweaks if context-sensitive or probe-based profile is available.
1964e36786d1SHongtao Yu   if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
19657a316c0aSHongtao Yu       Reader->profileIsProbeBased()) {
19667a316c0aSHongtao Yu     if (!UseIterativeBFIInference.getNumOccurrences())
19677a316c0aSHongtao Yu       UseIterativeBFIInference = true;
19687a316c0aSHongtao Yu     if (!SampleProfileUseProfi.getNumOccurrences())
19697a316c0aSHongtao Yu       SampleProfileUseProfi = true;
19707a316c0aSHongtao Yu     if (!EnableExtTspBlockPlacement.getNumOccurrences())
19717a316c0aSHongtao Yu       EnableExtTspBlockPlacement = true;
19726bae5973SWenlei He     // Enable priority-base inliner and size inline by default for CSSPGO.
19736bae5973SWenlei He     if (!ProfileSizeInline.getNumOccurrences())
19746bae5973SWenlei He       ProfileSizeInline = true;
19756bae5973SWenlei He     if (!CallsitePrioritizedInline.getNumOccurrences())
19766bae5973SWenlei He       CallsitePrioritizedInline = true;
1977f7fff46aSWenlei He     // For CSSPGO, we also allow recursive inline to best use context profile.
1978f7fff46aSWenlei He     if (!AllowRecursiveInline.getNumOccurrences())
1979f7fff46aSWenlei He       AllowRecursiveInline = true;
1980f7fff46aSWenlei He 
1981bdb8c50aSHongtao Yu     if (Reader->profileIsPreInlined()) {
1982bdb8c50aSHongtao Yu       if (!UsePreInlinerDecision.getNumOccurrences())
1983bdb8c50aSHongtao Yu         UsePreInlinerDecision = true;
19843113e5bbSHongtao Yu     }
19853113e5bbSHongtao Yu 
19863113e5bbSHongtao Yu     if (!Reader->profileIsCS()) {
1987bdb8c50aSHongtao Yu       // Non-CS profile should be fine without a function size budget for the
19883113e5bbSHongtao Yu       // inliner since the contexts in the profile are either all from inlining
19893113e5bbSHongtao Yu       // in the prevoius build or pre-computed by the preinliner with a size
19903113e5bbSHongtao Yu       // cap, thus they are bounded.
1991bdb8c50aSHongtao Yu       if (!ProfileInlineLimitMin.getNumOccurrences())
1992bdb8c50aSHongtao Yu         ProfileInlineLimitMin = std::numeric_limits<unsigned>::max();
1993bdb8c50aSHongtao Yu       if (!ProfileInlineLimitMax.getNumOccurrences())
1994bdb8c50aSHongtao Yu         ProfileInlineLimitMax = std::numeric_limits<unsigned>::max();
1995bdb8c50aSHongtao Yu     }
1996bdb8c50aSHongtao Yu   }
1997bdb8c50aSHongtao Yu 
1998e95ae395SHongtao Yu   if (Reader->profileIsCS()) {
19996b989a17SWenlei He     // Tracker for profiles under different context
20007ca80300SHongtao Yu     ContextTracker = std::make_unique<SampleContextTracker>(
20017ca80300SHongtao Yu         Reader->getProfiles(), &GUIDToFuncNameMap);
20026b989a17SWenlei He   }
20036b989a17SWenlei He 
2004ac068e01SHongtao Yu   // Load pseudo probe descriptors for probe-based function samples.
2005ac068e01SHongtao Yu   if (Reader->profileIsProbeBased()) {
2006ac068e01SHongtao Yu     ProbeManager = std::make_unique<PseudoProbeManager>(M);
2007ac068e01SHongtao Yu     if (!ProbeManager->moduleIsProbed(M)) {
2008ac068e01SHongtao Yu       const char *Msg =
2009ac068e01SHongtao Yu           "Pseudo-probe-based profile requires SampleProfileProbePass";
2010d7b7b649SHongtao Yu       Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg,
2011d7b7b649SHongtao Yu                                                DS_Warning));
2012ac068e01SHongtao Yu       return false;
2013ac068e01SHongtao Yu     }
2014ac068e01SHongtao Yu   }
2015ac068e01SHongtao Yu 
20164d71113cSDiego Novillo   return true;
20174d71113cSDiego Novillo }
20184d71113cSDiego Novillo 
runOnModule(Module & M,ModuleAnalysisManager * AM,ProfileSummaryInfo * _PSI,CallGraph * CG)20190c2f6be6SWei Mi bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
2020532196d8SWenlei He                                       ProfileSummaryInfo *_PSI, CallGraph *CG) {
2021c1c9eb0aSYi Kong   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
2022a8a3bd21SDiego Novillo 
20230c2f6be6SWei Mi   PSI = _PSI;
2024fa3b5871SMircea Trofin   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
2025a6ff69f6SRong Xu     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
2026a6ff69f6SRong Xu                         ProfileSummary::PSK_Sample);
2027fa3b5871SMircea Trofin     PSI->refresh();
2028fa3b5871SMircea Trofin   }
202984f06cc8SDiego Novillo   // Compute the total number of samples collected in this profile.
203084f06cc8SDiego Novillo   for (const auto &I : Reader->getProfiles())
203184f06cc8SDiego Novillo     TotalCollectedSamples += I.second.getTotalSamples();
203284f06cc8SDiego Novillo 
2033c67ccf5fSWei Mi   auto Remapper = Reader->getRemapper();
20341ea8bd81SDehao Chen   // Populate the symbol map.
20351ea8bd81SDehao Chen   for (const auto &N_F : M.getValueSymbolTable()) {
203624cb28bbSBenjamin Kramer     StringRef OrigName = N_F.getKey();
20371ea8bd81SDehao Chen     Function *F = dyn_cast<Function>(N_F.getValue());
2038ee35784aSWei Mi     if (F == nullptr || OrigName.empty())
20391ea8bd81SDehao Chen       continue;
20401ea8bd81SDehao Chen     SymbolMap[OrigName] = F;
2041ee35784aSWei Mi     StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
2042ee35784aSWei Mi     if (OrigName != NewName && !NewName.empty()) {
20431ea8bd81SDehao Chen       auto r = SymbolMap.insert(std::make_pair(NewName, F));
20441ea8bd81SDehao Chen       // Failiing to insert means there is already an entry in SymbolMap,
20451ea8bd81SDehao Chen       // thus there are multiple functions that are mapped to the same
20461ea8bd81SDehao Chen       // stripped name. In this case of name conflicting, set the value
20471ea8bd81SDehao Chen       // to nullptr to avoid confusion.
20481ea8bd81SDehao Chen       if (!r.second)
20491ea8bd81SDehao Chen         r.first->second = nullptr;
2050c67ccf5fSWei Mi       OrigName = NewName;
2051c67ccf5fSWei Mi     }
2052c67ccf5fSWei Mi     // Insert the remapped names into SymbolMap.
2053c67ccf5fSWei Mi     if (Remapper) {
2054c67ccf5fSWei Mi       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2055ee35784aSWei Mi         if (*MapName != OrigName && !MapName->empty())
2056c67ccf5fSWei Mi           SymbolMap.insert(std::make_pair(*MapName, F));
2057c67ccf5fSWei Mi       }
20581ea8bd81SDehao Chen     }
20591ea8bd81SDehao Chen   }
2060ee35784aSWei Mi   assert(SymbolMap.count(StringRef()) == 0 &&
2061ee35784aSWei Mi          "No empty StringRef should be added in SymbolMap");
20621ea8bd81SDehao Chen 
20634d71113cSDiego Novillo   bool retval = false;
2064532196d8SWenlei He   for (auto F : buildFunctionOrder(M, CG)) {
2065532196d8SWenlei He     assert(!F->isDeclaration());
2066a8a3bd21SDiego Novillo     clearFunctionData();
2067532196d8SWenlei He     retval |= runOnFunction(*F, AM);
2068a8a3bd21SDiego Novillo   }
2069d2eeb251SDavid Callahan 
2070d2eeb251SDavid Callahan   // Account for cold calls not inlined....
2071e95ae395SHongtao Yu   if (!FunctionSamples::ProfileIsCS)
2072d2eeb251SDavid Callahan     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
2073d2eeb251SDavid Callahan          notInlinedCallInfo)
2074d2eeb251SDavid Callahan       updateProfileCallee(pair.first, pair.second.entryCount);
2075d2eeb251SDavid Callahan 
20764d71113cSDiego Novillo   return retval;
20774d71113cSDiego Novillo }
20784d71113cSDiego Novillo 
runOnFunction(Function & F,ModuleAnalysisManager * AM)207951cf2604SEli Friedman bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
2080de40f6d6SHongtao Yu   LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
2081dee00120SDavid Callahan   DILocation2SampleMap.clear();
208266c6c5abSWei Mi   // By default the entry count is initialized to -1, which will be treated
208366c6c5abSWei Mi   // conservatively by getEntryCount as the same as unknown (None). This is
208466c6c5abSWei Mi   // to avoid newly added code to be treated as cold. If we have samples
208566c6c5abSWei Mi   // this will be overwritten in emitAnnotations.
20865f7e822dSWei Mi   uint64_t initialEntryCount = -1;
20875f7e822dSWei Mi 
2088f0c4e70eSWei Mi   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
2089f0c4e70eSWei Mi   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
2090f0c4e70eSWei Mi     // initialize all the function entry counts to 0. It means all the
2091f0c4e70eSWei Mi     // functions without profile will be regarded as cold.
2092f0c4e70eSWei Mi     initialEntryCount = 0;
2093f0c4e70eSWei Mi     // profile-sample-accurate is a user assertion which has a higher precedence
2094f0c4e70eSWei Mi     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2095f0c4e70eSWei Mi     ProfAccForSymsInList = false;
2096f0c4e70eSWei Mi   }
2097b8f13db5SRong Xu   CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
2098f0c4e70eSWei Mi 
2099798e59b8SWei Mi   // PSL -- profile symbol list include all the symbols in sampled binary.
2100f0c4e70eSWei Mi   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2101f0c4e70eSWei Mi   // old functions without samples being cold, without having to worry
2102f0c4e70eSWei Mi   // about new and hot functions being mistakenly treated as cold.
2103f0c4e70eSWei Mi   if (ProfAccForSymsInList) {
2104f0c4e70eSWei Mi     // Initialize the entry count to 0 for functions in the list.
210522fd8853SWei Mi     if (PSL->contains(F.getName()))
21065f7e822dSWei Mi       initialEntryCount = 0;
21075f7e822dSWei Mi 
2108f0c4e70eSWei Mi     // Function in the symbol list but without sample will be regarded as
2109f0c4e70eSWei Mi     // cold. To minimize the potential negative performance impact it could
2110f0c4e70eSWei Mi     // have, we want to be a little conservative here saying if a function
2111f0c4e70eSWei Mi     // shows up in the profile, no matter as outline function, inline instance
2112f0c4e70eSWei Mi     // or call targets, treat the function as not being cold. This will handle
2113f0c4e70eSWei Mi     // the cases such as most callsites of a function are inlined in sampled
2114f0c4e70eSWei Mi     // binary but not inlined in current build (because of source code drift,
2115f0c4e70eSWei Mi     // imprecise debug information, or the callsites are all cold individually
2116f0c4e70eSWei Mi     // but not cold accumulatively...), so the outline function showing up as
2117f0c4e70eSWei Mi     // cold in sampled binary will actually not be cold after current build.
21185f7e822dSWei Mi     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
21195f7e822dSWei Mi     if (NamesInProfile.count(CanonName))
21205f7e822dSWei Mi       initialEntryCount = -1;
21215f7e822dSWei Mi   }
21225f7e822dSWei Mi 
212321b1ad03SWei Mi   // Initialize entry count when the function has no existing entry
212421b1ad03SWei Mi   // count value.
2125e0e687a6SKazu Hirata   if (!F.getEntryCount())
212666c6c5abSWei Mi     F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
212751cf2604SEli Friedman   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
212851cf2604SEli Friedman   if (AM) {
212951cf2604SEli Friedman     auto &FAM =
213051cf2604SEli Friedman         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
213151cf2604SEli Friedman             .getManager();
213251cf2604SEli Friedman     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
213351cf2604SEli Friedman   } else {
21340eaee545SJonas Devlieghere     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
213551cf2604SEli Friedman     ORE = OwnedORE.get();
213651cf2604SEli Friedman   }
21376b989a17SWenlei He 
2138e95ae395SHongtao Yu   if (FunctionSamples::ProfileIsCS)
21396b989a17SWenlei He     Samples = ContextTracker->getBaseSamplesFor(F);
21406b989a17SWenlei He   else
21414d71113cSDiego Novillo     Samples = Reader->getSamplesFor(F);
21426b989a17SWenlei He 
21434a435e08SDehao Chen   if (Samples && !Samples->empty())
21444d71113cSDiego Novillo     return emitAnnotations(F);
21454d71113cSDiego Novillo   return false;
21464d71113cSDiego Novillo }
2147d38392ecSXinliang David Li 
run(Module & M,ModuleAnalysisManager & AM)2148d38392ecSXinliang David Li PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
2149fd03ac6aSSean Silva                                                ModuleAnalysisManager &AM) {
2150f3ed14d3SDehao Chen   FunctionAnalysisManager &FAM =
2151f3ed14d3SDehao Chen       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2152d38392ecSXinliang David Li 
2153f3ed14d3SDehao Chen   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2154f3ed14d3SDehao Chen     return FAM.getResult<AssumptionAnalysis>(F);
2155f3ed14d3SDehao Chen   };
21563a81f84dSDehao Chen   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
21573a81f84dSDehao Chen     return FAM.getResult<TargetIRAnalysis>(F);
21583a81f84dSDehao Chen   };
2159f9ca75f1STeresa Johnson   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2160f9ca75f1STeresa Johnson     return FAM.getResult<TargetLibraryAnalysis>(F);
2161f9ca75f1STeresa Johnson   };
2162f3ed14d3SDehao Chen 
2163d26dae0dSDehao Chen   SampleProfileLoader SampleLoader(
2164d26dae0dSDehao Chen       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
21656c676628SRichard Smith       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
21666c676628SRichard Smith                                        : ProfileRemappingFileName,
216786341247SWei Mi       LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
2168d38392ecSXinliang David Li 
2169577e58bcSWenlei He   if (!SampleLoader.doInitialization(M, &FAM))
2170193da743SFangrui Song     return PreservedAnalyses::all();
2171d38392ecSXinliang David Li 
21720c2f6be6SWei Mi   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2173532196d8SWenlei He   CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
2174532196d8SWenlei He   if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
2175d38392ecSXinliang David Li     return PreservedAnalyses::all();
2176d38392ecSXinliang David Li 
2177d38392ecSXinliang David Li   return PreservedAnalyses::none();
2178d38392ecSXinliang David Li }
2179