1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the SampleProfileLoader transformation. This pass
10 // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
11 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
12 // profile information in the given profile.
14 // This pass generates branch weight annotations on the IR:
16 // - prof: Represents branch weights. This annotation is added to branches
17 // to indicate the weights of each edge coming out of the branch.
18 // The weight of each edge is the weight of the target block for
19 // that edge. The weight of a block B is computed as the maximum
20 // number of samples found in B.
22 //===----------------------------------------------------------------------===//
24 #include "llvm/Transforms/IPO/SampleProfile.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/MapVector.h"
29 #include "llvm/ADT/PriorityQueue.h"
30 #include "llvm/ADT/SCCIterator.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/ADT/Twine.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
38 #include "llvm/Analysis/CallGraph.h"
39 #include "llvm/Analysis/InlineAdvisor.h"
40 #include "llvm/Analysis/InlineCost.h"
41 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
42 #include "llvm/Analysis/ProfileSummaryInfo.h"
43 #include "llvm/Analysis/ReplayInlineAdvisor.h"
44 #include "llvm/Analysis/TargetLibraryInfo.h"
45 #include "llvm/Analysis/TargetTransformInfo.h"
46 #include "llvm/IR/BasicBlock.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/DiagnosticInfo.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/IR/InstrTypes.h"
52 #include "llvm/IR/Instruction.h"
53 #include "llvm/IR/Instructions.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/LLVMContext.h"
56 #include "llvm/IR/MDBuilder.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/PassManager.h"
59 #include "llvm/IR/PseudoProbe.h"
60 #include "llvm/IR/ValueSymbolTable.h"
61 #include "llvm/InitializePasses.h"
62 #include "llvm/Pass.h"
63 #include "llvm/ProfileData/InstrProf.h"
64 #include "llvm/ProfileData/SampleProf.h"
65 #include "llvm/ProfileData/SampleProfReader.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/ErrorOr.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Transforms/IPO.h"
72 #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
73 #include "llvm/Transforms/IPO/SampleContextTracker.h"
74 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
75 #include "llvm/Transforms/Instrumentation.h"
76 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
77 #include "llvm/Transforms/Utils/Cloning.h"
78 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
79 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
89 #include <system_error>
94 using namespace sampleprof
;
95 using namespace llvm::sampleprofutil
;
96 using ProfileCount
= Function::ProfileCount
;
97 #define DEBUG_TYPE "sample-profile"
98 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
100 STATISTIC(NumCSInlined
,
101 "Number of functions inlined with context sensitive profile");
102 STATISTIC(NumCSNotInlined
,
103 "Number of functions not inlined with context sensitive profile");
104 STATISTIC(NumMismatchedProfile
,
105 "Number of functions with CFG mismatched profile");
106 STATISTIC(NumMatchedProfile
, "Number of functions with CFG matched profile");
107 STATISTIC(NumDuplicatedInlinesite
,
108 "Number of inlined callsites with a partial distribution factor");
110 STATISTIC(NumCSInlinedHitMinLimit
,
111 "Number of functions with FDO inline stopped due to min size limit");
112 STATISTIC(NumCSInlinedHitMaxLimit
,
113 "Number of functions with FDO inline stopped due to max size limit");
115 NumCSInlinedHitGrowthLimit
,
116 "Number of functions with FDO inline stopped due to growth size limit");
118 // Command line option to specify the file to read samples from. This is
119 // mainly used for debugging.
120 static cl::opt
<std::string
> SampleProfileFile(
121 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
122 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden
);
124 // The named file contains a set of transformations that may have been applied
125 // to the symbol names between the program from which the sample data was
126 // collected and the current program's symbols.
127 static cl::opt
<std::string
> SampleProfileRemappingFile(
128 "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
129 cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden
);
131 static cl::opt
<bool> ProfileSampleAccurate(
132 "profile-sample-accurate", cl::Hidden
, cl::init(false),
133 cl::desc("If the sample profile is accurate, we will mark all un-sampled "
134 "callsite and function as having 0 samples. Otherwise, treat "
135 "un-sampled callsites and functions conservatively as unknown. "));
137 static cl::opt
<bool> ProfileSampleBlockAccurate(
138 "profile-sample-block-accurate", cl::Hidden
, cl::init(false),
139 cl::desc("If the sample profile is accurate, we will mark all un-sampled "
140 "branches and calls as having 0 samples. Otherwise, treat "
141 "them conservatively as unknown. "));
143 static cl::opt
<bool> ProfileAccurateForSymsInList(
144 "profile-accurate-for-symsinlist", cl::Hidden
, cl::init(true),
145 cl::desc("For symbols in profile symbol list, regard their profiles to "
146 "be accurate. It may be overriden by profile-sample-accurate. "));
148 static cl::opt
<bool> ProfileMergeInlinee(
149 "sample-profile-merge-inlinee", cl::Hidden
, cl::init(true),
150 cl::desc("Merge past inlinee's profile to outline version if sample "
151 "profile loader decided not to inline a call site. It will "
152 "only be enabled when top-down order of profile loading is "
155 static cl::opt
<bool> ProfileTopDownLoad(
156 "sample-profile-top-down-load", cl::Hidden
, cl::init(true),
157 cl::desc("Do profile annotation and inlining for functions in top-down "
158 "order of call graph during sample profile loading. It only "
159 "works for new pass manager. "));
162 UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden
,
163 cl::desc("Process functions in a top-down order "
164 "defined by the profiled call graph when "
165 "-sample-profile-top-down-load is on."));
167 SortProfiledSCC("sort-profiled-scc-member", cl::init(true), cl::Hidden
,
168 cl::desc("Sort profiled recursion by edge weights."));
170 static cl::opt
<bool> ProfileSizeInline(
171 "sample-profile-inline-size", cl::Hidden
, cl::init(false),
172 cl::desc("Inline cold call sites in profile loader if it's beneficial "
175 // Since profiles are consumed by many passes, turning on this option has
176 // side effects. For instance, pre-link SCC inliner would see merged profiles
177 // and inline the hot functions (that are skipped in this pass).
178 static cl::opt
<bool> DisableSampleLoaderInlining(
179 "disable-sample-loader-inlining", cl::Hidden
, cl::init(false),
180 cl::desc("If true, artifically skip inline transformation in sample-loader "
181 "pass, and merge (or scale) profiles (as configured by "
182 "--sample-profile-merge-inlinee)."));
184 cl::opt
<int> ProfileInlineGrowthLimit(
185 "sample-profile-inline-growth-limit", cl::Hidden
, cl::init(12),
186 cl::desc("The size growth ratio limit for proirity-based sample profile "
187 "loader inlining."));
189 cl::opt
<int> ProfileInlineLimitMin(
190 "sample-profile-inline-limit-min", cl::Hidden
, cl::init(100),
191 cl::desc("The lower bound of size growth limit for "
192 "proirity-based sample profile loader inlining."));
194 cl::opt
<int> ProfileInlineLimitMax(
195 "sample-profile-inline-limit-max", cl::Hidden
, cl::init(10000),
196 cl::desc("The upper bound of size growth limit for "
197 "proirity-based sample profile loader inlining."));
199 cl::opt
<int> SampleHotCallSiteThreshold(
200 "sample-profile-hot-inline-threshold", cl::Hidden
, cl::init(3000),
201 cl::desc("Hot callsite threshold for proirity-based sample profile loader "
204 cl::opt
<int> SampleColdCallSiteThreshold(
205 "sample-profile-cold-inline-threshold", cl::Hidden
, cl::init(45),
206 cl::desc("Threshold for inlining cold callsites"));
208 static cl::opt
<unsigned> ProfileICPRelativeHotness(
209 "sample-profile-icp-relative-hotness", cl::Hidden
, cl::init(25),
211 "Relative hotness percentage threshold for indirect "
212 "call promotion in proirity-based sample profile loader inlining."));
214 static cl::opt
<unsigned> ProfileICPRelativeHotnessSkip(
215 "sample-profile-icp-relative-hotness-skip", cl::Hidden
, cl::init(1),
217 "Skip relative hotness check for ICP up to given number of targets."));
219 static cl::opt
<bool> CallsitePrioritizedInline(
220 "sample-profile-prioritized-inline", cl::Hidden
,
222 cl::desc("Use call site prioritized inlining for sample profile loader."
223 "Currently only CSSPGO is supported."));
225 static cl::opt
<bool> UsePreInlinerDecision(
226 "sample-profile-use-preinliner", cl::Hidden
,
228 cl::desc("Use the preinliner decisions stored in profile context."));
230 static cl::opt
<bool> AllowRecursiveInline(
231 "sample-profile-recursive-inline", cl::Hidden
,
233 cl::desc("Allow sample loader inliner to inline recursive calls."));
235 static cl::opt
<std::string
> ProfileInlineReplayFile(
236 "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
238 "Optimization remarks file containing inline remarks to be replayed "
239 "by inlining from sample profile loader."),
242 static cl::opt
<ReplayInlinerSettings::Scope
> ProfileInlineReplayScope(
243 "sample-profile-inline-replay-scope",
244 cl::init(ReplayInlinerSettings::Scope::Function
),
245 cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function
, "Function",
246 "Replay on functions that have remarks associated "
247 "with them (default)"),
248 clEnumValN(ReplayInlinerSettings::Scope::Module
, "Module",
249 "Replay on the entire module")),
250 cl::desc("Whether inline replay should be applied to the entire "
251 "Module or just the Functions (default) that are present as "
252 "callers in remarks during sample profile inlining."),
255 static cl::opt
<ReplayInlinerSettings::Fallback
> ProfileInlineReplayFallback(
256 "sample-profile-inline-replay-fallback",
257 cl::init(ReplayInlinerSettings::Fallback::Original
),
260 ReplayInlinerSettings::Fallback::Original
, "Original",
261 "All decisions not in replay send to original advisor (default)"),
262 clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline
,
263 "AlwaysInline", "All decisions not in replay are inlined"),
264 clEnumValN(ReplayInlinerSettings::Fallback::NeverInline
, "NeverInline",
265 "All decisions not in replay are not inlined")),
266 cl::desc("How sample profile inline replay treats sites that don't come "
267 "from the replay. Original: defers to original advisor, "
268 "AlwaysInline: inline all sites not in replay, NeverInline: "
269 "inline no sites not in replay"),
272 static cl::opt
<CallSiteFormat::Format
> ProfileInlineReplayFormat(
273 "sample-profile-inline-replay-format",
274 cl::init(CallSiteFormat::Format::LineColumnDiscriminator
),
276 clEnumValN(CallSiteFormat::Format::Line
, "Line", "<Line Number>"),
277 clEnumValN(CallSiteFormat::Format::LineColumn
, "LineColumn",
278 "<Line Number>:<Column Number>"),
279 clEnumValN(CallSiteFormat::Format::LineDiscriminator
,
280 "LineDiscriminator", "<Line Number>.<Discriminator>"),
281 clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator
,
282 "LineColumnDiscriminator",
283 "<Line Number>:<Column Number>.<Discriminator> (default)")),
284 cl::desc("How sample profile inline replay file is formatted"), cl::Hidden
);
286 static cl::opt
<unsigned>
287 MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden
,
288 cl::desc("Max number of promotions for a single indirect "
289 "call callsite in sample profile loader"));
291 static cl::opt
<bool> OverwriteExistingWeights(
292 "overwrite-existing-weights", cl::Hidden
, cl::init(false),
293 cl::desc("Ignore existing branch weights on IR and always overwrite."));
295 static cl::opt
<bool> AnnotateSampleProfileInlinePhase(
296 "annotate-sample-profile-inline-phase", cl::Hidden
, cl::init(false),
297 cl::desc("Annotate LTO phase (prelink / postlink), or main (no LTO) for "
298 "sample-profile inline pass name."));
300 extern cl::opt
<bool> EnableExtTspBlockPlacement
;
304 using BlockWeightMap
= DenseMap
<const BasicBlock
*, uint64_t>;
305 using EquivalenceClassMap
= DenseMap
<const BasicBlock
*, const BasicBlock
*>;
306 using Edge
= std::pair
<const BasicBlock
*, const BasicBlock
*>;
307 using EdgeWeightMap
= DenseMap
<Edge
, uint64_t>;
309 DenseMap
<const BasicBlock
*, SmallVector
<const BasicBlock
*, 8>>;
311 class GUIDToFuncNameMapper
{
313 GUIDToFuncNameMapper(Module
&M
, SampleProfileReader
&Reader
,
314 DenseMap
<uint64_t, StringRef
> &GUIDToFuncNameMap
)
315 : CurrentReader(Reader
), CurrentModule(M
),
316 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap
) {
317 if (!CurrentReader
.useMD5())
320 for (const auto &F
: CurrentModule
) {
321 StringRef OrigName
= F
.getName();
322 CurrentGUIDToFuncNameMap
.insert(
323 {Function::getGUID(OrigName
), OrigName
});
325 // Local to global var promotion used by optimization like thinlto
326 // will rename the var and add suffix like ".llvm.xxx" to the
327 // original local name. In sample profile, the suffixes of function
328 // names are all stripped. Since it is possible that the mapper is
329 // built in post-thin-link phase and var promotion has been done,
330 // we need to add the substring of function name without the suffix
331 // into the GUIDToFuncNameMap.
332 StringRef CanonName
= FunctionSamples::getCanonicalFnName(F
);
333 if (CanonName
!= OrigName
)
334 CurrentGUIDToFuncNameMap
.insert(
335 {Function::getGUID(CanonName
), CanonName
});
338 // Update GUIDToFuncNameMap for each function including inlinees.
339 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap
);
342 ~GUIDToFuncNameMapper() {
343 if (!CurrentReader
.useMD5())
346 CurrentGUIDToFuncNameMap
.clear();
348 // Reset GUIDToFuncNameMap for of each function as they're no
349 // longer valid at this point.
350 SetGUIDToFuncNameMapForAll(nullptr);
354 void SetGUIDToFuncNameMapForAll(DenseMap
<uint64_t, StringRef
> *Map
) {
355 std::queue
<FunctionSamples
*> FSToUpdate
;
356 for (auto &IFS
: CurrentReader
.getProfiles()) {
357 FSToUpdate
.push(&IFS
.second
);
360 while (!FSToUpdate
.empty()) {
361 FunctionSamples
*FS
= FSToUpdate
.front();
363 FS
->GUIDToFuncNameMap
= Map
;
364 for (const auto &ICS
: FS
->getCallsiteSamples()) {
365 const FunctionSamplesMap
&FSMap
= ICS
.second
;
366 for (const auto &IFS
: FSMap
) {
367 FunctionSamples
&FS
= const_cast<FunctionSamples
&>(IFS
.second
);
368 FSToUpdate
.push(&FS
);
374 SampleProfileReader
&CurrentReader
;
375 Module
&CurrentModule
;
376 DenseMap
<uint64_t, StringRef
> &CurrentGUIDToFuncNameMap
;
379 // Inline candidate used by iterative callsite prioritized inliner
380 struct InlineCandidate
{
382 const FunctionSamples
*CalleeSamples
;
383 // Prorated callsite count, which will be used to guide inlining. For example,
384 // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
385 // copies will get their own distribution factors and their prorated counts
386 // will be used to decide if they should be inlined independently.
387 uint64_t CallsiteCount
;
388 // Call site distribution factor to prorate the profile samples for a
389 // duplicated callsite. Default value is 1.0.
390 float CallsiteDistribution
;
393 // Inline candidate comparer using call site weight
394 struct CandidateComparer
{
395 bool operator()(const InlineCandidate
&LHS
, const InlineCandidate
&RHS
) {
396 if (LHS
.CallsiteCount
!= RHS
.CallsiteCount
)
397 return LHS
.CallsiteCount
< RHS
.CallsiteCount
;
399 const FunctionSamples
*LCS
= LHS
.CalleeSamples
;
400 const FunctionSamples
*RCS
= RHS
.CalleeSamples
;
401 assert(LCS
&& RCS
&& "Expect non-null FunctionSamples");
403 // Tie breaker using number of samples try to favor smaller functions first
404 if (LCS
->getBodySamples().size() != RCS
->getBodySamples().size())
405 return LCS
->getBodySamples().size() > RCS
->getBodySamples().size();
407 // Tie breaker using GUID so we have stable/deterministic inlining order
408 return LCS
->getGUID(LCS
->getName()) < RCS
->getGUID(RCS
->getName());
412 using CandidateQueue
=
413 PriorityQueue
<InlineCandidate
, std::vector
<InlineCandidate
>,
416 /// Sample profile pass.
418 /// This pass reads profile data from the file specified by
419 /// -sample-profile-file and annotates every affected function with the
420 /// profile information found in that file.
421 class SampleProfileLoader final
422 : public SampleProfileLoaderBaseImpl
<BasicBlock
> {
425 StringRef Name
, StringRef RemapName
, ThinOrFullLTOPhase LTOPhase
,
426 std::function
<AssumptionCache
&(Function
&)> GetAssumptionCache
,
427 std::function
<TargetTransformInfo
&(Function
&)> GetTargetTransformInfo
,
428 std::function
<const TargetLibraryInfo
&(Function
&)> GetTLI
)
429 : SampleProfileLoaderBaseImpl(std::string(Name
), std::string(RemapName
)),
430 GetAC(std::move(GetAssumptionCache
)),
431 GetTTI(std::move(GetTargetTransformInfo
)), GetTLI(std::move(GetTLI
)),
433 AnnotatedPassName(AnnotateSampleProfileInlinePhase
434 ? llvm::AnnotateInlinePassName(InlineContext
{
435 LTOPhase
, InlinePass::SampleProfileInliner
})
438 bool doInitialization(Module
&M
, FunctionAnalysisManager
*FAM
= nullptr);
439 bool runOnModule(Module
&M
, ModuleAnalysisManager
*AM
,
440 ProfileSummaryInfo
*_PSI
, CallGraph
*CG
);
443 bool runOnFunction(Function
&F
, ModuleAnalysisManager
*AM
);
444 bool emitAnnotations(Function
&F
);
445 ErrorOr
<uint64_t> getInstWeight(const Instruction
&I
) override
;
446 ErrorOr
<uint64_t> getProbeWeight(const Instruction
&I
);
447 const FunctionSamples
*findCalleeFunctionSamples(const CallBase
&I
) const;
448 const FunctionSamples
*
449 findFunctionSamples(const Instruction
&I
) const override
;
450 std::vector
<const FunctionSamples
*>
451 findIndirectCallFunctionSamples(const Instruction
&I
, uint64_t &Sum
) const;
452 void findExternalInlineCandidate(CallBase
*CB
, const FunctionSamples
*Samples
,
453 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
,
454 const StringMap
<Function
*> &SymbolMap
,
456 // Attempt to promote indirect call and also inline the promoted call
457 bool tryPromoteAndInlineCandidate(
458 Function
&F
, InlineCandidate
&Candidate
, uint64_t SumOrigin
,
459 uint64_t &Sum
, SmallVector
<CallBase
*, 8> *InlinedCallSites
= nullptr);
461 bool inlineHotFunctions(Function
&F
,
462 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
);
463 Optional
<InlineCost
> getExternalInlineAdvisorCost(CallBase
&CB
);
464 bool getExternalInlineAdvisorShouldInline(CallBase
&CB
);
465 InlineCost
shouldInlineCandidate(InlineCandidate
&Candidate
);
466 bool getInlineCandidate(InlineCandidate
*NewCandidate
, CallBase
*CB
);
468 tryInlineCandidate(InlineCandidate
&Candidate
,
469 SmallVector
<CallBase
*, 8> *InlinedCallSites
= nullptr);
471 inlineHotFunctionsWithPriority(Function
&F
,
472 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
);
473 // Inline cold/small functions in addition to hot ones
474 bool shouldInlineColdCallee(CallBase
&CallInst
);
475 void emitOptimizationRemarksForInlineCandidates(
476 const SmallVectorImpl
<CallBase
*> &Candidates
, const Function
&F
,
478 void promoteMergeNotInlinedContextSamples(
479 MapVector
<CallBase
*, const FunctionSamples
*> NonInlinedCallSites
,
481 std::vector
<Function
*> buildFunctionOrder(Module
&M
, CallGraph
*CG
);
482 std::unique_ptr
<ProfiledCallGraph
> buildProfiledCallGraph(CallGraph
&CG
);
483 void generateMDProfMetadata(Function
&F
);
485 /// Map from function name to Function *. Used to find the function from
486 /// the function name. If the function name contains suffix, additional
487 /// entry is added to map from the stripped name to the function if there
488 /// is one-to-one mapping.
489 StringMap
<Function
*> SymbolMap
;
491 std::function
<AssumptionCache
&(Function
&)> GetAC
;
492 std::function
<TargetTransformInfo
&(Function
&)> GetTTI
;
493 std::function
<const TargetLibraryInfo
&(Function
&)> GetTLI
;
495 /// Profile tracker for different context.
496 std::unique_ptr
<SampleContextTracker
> ContextTracker
;
498 /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
500 /// We need to know the LTO phase because for example in ThinLTOPrelink
501 /// phase, in annotation, we should not promote indirect calls. Instead,
502 /// we will mark GUIDs that needs to be annotated to the function.
503 const ThinOrFullLTOPhase LTOPhase
;
504 const std::string AnnotatedPassName
;
506 /// Profle Symbol list tells whether a function name appears in the binary
507 /// used to generate the current profile.
508 std::unique_ptr
<ProfileSymbolList
> PSL
;
510 /// Total number of samples collected in this profile.
512 /// This is the sum of all the samples collected in all the functions executed
514 uint64_t TotalCollectedSamples
= 0;
516 // Information recorded when we declined to inline a call site
517 // because we have determined it is too cold is accumulated for
518 // each callee function. Initially this is just the entry count.
519 struct NotInlinedProfileInfo
{
522 DenseMap
<Function
*, NotInlinedProfileInfo
> notInlinedCallInfo
;
524 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
525 // all the function symbols defined or declared in current module.
526 DenseMap
<uint64_t, StringRef
> GUIDToFuncNameMap
;
528 // All the Names used in FunctionSamples including outline function
529 // names, inline instance names and call target names.
530 StringSet
<> NamesInProfile
;
532 // For symbol in profile symbol list, whether to regard their profiles
533 // to be accurate. It is mainly decided by existance of profile symbol
534 // list and -profile-accurate-for-symsinlist flag, but it can be
535 // overriden by -profile-sample-accurate or profile-sample-accurate
537 bool ProfAccForSymsInList
;
539 // External inline advisor used to replay inline decision from remarks.
540 std::unique_ptr
<InlineAdvisor
> ExternalInlineAdvisor
;
542 // A pseudo probe helper to correlate the imported sample counts.
543 std::unique_ptr
<PseudoProbeManager
> ProbeManager
;
546 const char *getAnnotatedRemarkPassName() const {
547 return AnnotatedPassName
.c_str();
550 } // end anonymous namespace
552 ErrorOr
<uint64_t> SampleProfileLoader::getInstWeight(const Instruction
&Inst
) {
553 if (FunctionSamples::ProfileIsProbeBased
)
554 return getProbeWeight(Inst
);
556 const DebugLoc
&DLoc
= Inst
.getDebugLoc();
558 return std::error_code();
560 // Ignore all intrinsics, phinodes and branch instructions.
561 // Branch and phinodes instruction usually contains debug info from sources
562 // outside of the residing basic block, thus we ignore them during annotation.
563 if (isa
<BranchInst
>(Inst
) || isa
<IntrinsicInst
>(Inst
) || isa
<PHINode
>(Inst
))
564 return std::error_code();
566 // For non-CS profile, if a direct call/invoke instruction is inlined in
567 // profile (findCalleeFunctionSamples returns non-empty result), but not
568 // inlined here, it means that the inlined callsite has no sample, thus the
569 // call instruction should have 0 count.
570 // For CS profile, the callsite count of previously inlined callees is
571 // populated with the entry count of the callees.
572 if (!FunctionSamples::ProfileIsCS
)
573 if (const auto *CB
= dyn_cast
<CallBase
>(&Inst
))
574 if (!CB
->isIndirectCall() && findCalleeFunctionSamples(*CB
))
577 return getInstWeightImpl(Inst
);
580 // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight
581 // of non-probe instruction. So if all instructions of the BB give error_code,
582 // tell the inference algorithm to infer the BB weight.
583 ErrorOr
<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction
&Inst
) {
584 assert(FunctionSamples::ProfileIsProbeBased
&&
585 "Profile is not pseudo probe based");
586 Optional
<PseudoProbe
> Probe
= extractProbe(Inst
);
587 // Ignore the non-probe instruction. If none of the instruction in the BB is
588 // probe, we choose to infer the BB's weight.
590 return std::error_code();
592 const FunctionSamples
*FS
= findFunctionSamples(Inst
);
593 // If none of the instruction has FunctionSample, we choose to return zero
594 // value sample to indicate the BB is cold. This could happen when the
595 // instruction is from inlinee and no profile data is found.
596 // FIXME: This should not be affected by the source drift issue as 1) if the
597 // newly added function is top-level inliner, it won't match the CFG checksum
598 // in the function profile or 2) if it's the inlinee, the inlinee should have
599 // a profile, otherwise it wouldn't be inlined. For non-probe based profile,
600 // we can improve it by adding a switch for profile-sample-block-accurate for
601 // block level counts in the future.
605 // For non-CS profile, If a direct call/invoke instruction is inlined in
606 // profile (findCalleeFunctionSamples returns non-empty result), but not
607 // inlined here, it means that the inlined callsite has no sample, thus the
608 // call instruction should have 0 count.
609 // For CS profile, the callsite count of previously inlined callees is
610 // populated with the entry count of the callees.
611 if (!FunctionSamples::ProfileIsCS
)
612 if (const auto *CB
= dyn_cast
<CallBase
>(&Inst
))
613 if (!CB
->isIndirectCall() && findCalleeFunctionSamples(*CB
))
616 const ErrorOr
<uint64_t> &R
= FS
->findSamplesAt(Probe
->Id
, 0);
618 uint64_t Samples
= R
.get() * Probe
->Factor
;
619 bool FirstMark
= CoverageTracker
.markSamplesUsed(FS
, Probe
->Id
, 0, Samples
);
622 OptimizationRemarkAnalysis
Remark(DEBUG_TYPE
, "AppliedSamples", &Inst
);
623 Remark
<< "Applied " << ore::NV("NumSamples", Samples
);
624 Remark
<< " samples from profile (ProbeId=";
625 Remark
<< ore::NV("ProbeId", Probe
->Id
);
626 Remark
<< ", Factor=";
627 Remark
<< ore::NV("Factor", Probe
->Factor
);
628 Remark
<< ", OriginalSamples=";
629 Remark
<< ore::NV("OriginalSamples", R
.get());
634 LLVM_DEBUG(dbgs() << " " << Probe
->Id
<< ":" << Inst
635 << " - weight: " << R
.get() << " - factor: "
636 << format("%0.2f", Probe
->Factor
) << ")\n");
642 /// Get the FunctionSamples for a call instruction.
644 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
645 /// instance in which that call instruction is calling to. It contains
646 /// all samples that resides in the inlined instance. We first find the
647 /// inlined instance in which the call instruction is from, then we
648 /// traverse its children to find the callsite with the matching
651 /// \param Inst Call/Invoke instruction to query.
653 /// \returns The FunctionSamples pointer to the inlined instance.
654 const FunctionSamples
*
655 SampleProfileLoader::findCalleeFunctionSamples(const CallBase
&Inst
) const {
656 const DILocation
*DIL
= Inst
.getDebugLoc();
661 StringRef CalleeName
;
662 if (Function
*Callee
= Inst
.getCalledFunction())
663 CalleeName
= Callee
->getName();
665 if (FunctionSamples::ProfileIsCS
)
666 return ContextTracker
->getCalleeContextSamplesFor(Inst
, CalleeName
);
668 const FunctionSamples
*FS
= findFunctionSamples(Inst
);
672 return FS
->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL
),
673 CalleeName
, Reader
->getRemapper());
676 /// Returns a vector of FunctionSamples that are the indirect call targets
677 /// of \p Inst. The vector is sorted by the total number of samples. Stores
678 /// the total call count of the indirect call in \p Sum.
679 std::vector
<const FunctionSamples
*>
680 SampleProfileLoader::findIndirectCallFunctionSamples(
681 const Instruction
&Inst
, uint64_t &Sum
) const {
682 const DILocation
*DIL
= Inst
.getDebugLoc();
683 std::vector
<const FunctionSamples
*> R
;
689 auto FSCompare
= [](const FunctionSamples
*L
, const FunctionSamples
*R
) {
690 assert(L
&& R
&& "Expect non-null FunctionSamples");
691 if (L
->getHeadSamplesEstimate() != R
->getHeadSamplesEstimate())
692 return L
->getHeadSamplesEstimate() > R
->getHeadSamplesEstimate();
693 return FunctionSamples::getGUID(L
->getName()) <
694 FunctionSamples::getGUID(R
->getName());
697 if (FunctionSamples::ProfileIsCS
) {
699 ContextTracker
->getIndirectCalleeContextSamplesFor(DIL
);
700 if (CalleeSamples
.empty())
703 // For CSSPGO, we only use target context profile's entry count
704 // as that already includes both inlined callee and non-inlined ones..
706 for (const auto *const FS
: CalleeSamples
) {
707 Sum
+= FS
->getHeadSamplesEstimate();
710 llvm::sort(R
, FSCompare
);
714 const FunctionSamples
*FS
= findFunctionSamples(Inst
);
718 auto CallSite
= FunctionSamples::getCallSiteIdentifier(DIL
);
719 auto T
= FS
->findCallTargetMapAt(CallSite
);
722 for (const auto &T_C
: T
.get())
724 if (const FunctionSamplesMap
*M
= FS
->findFunctionSamplesMapAt(CallSite
)) {
727 for (const auto &NameFS
: *M
) {
728 Sum
+= NameFS
.second
.getHeadSamplesEstimate();
729 R
.push_back(&NameFS
.second
);
731 llvm::sort(R
, FSCompare
);
736 const FunctionSamples
*
737 SampleProfileLoader::findFunctionSamples(const Instruction
&Inst
) const {
738 if (FunctionSamples::ProfileIsProbeBased
) {
739 Optional
<PseudoProbe
> Probe
= extractProbe(Inst
);
744 const DILocation
*DIL
= Inst
.getDebugLoc();
748 auto it
= DILocation2SampleMap
.try_emplace(DIL
,nullptr);
750 if (FunctionSamples::ProfileIsCS
)
751 it
.first
->second
= ContextTracker
->getContextSamplesFor(DIL
);
754 Samples
->findFunctionSamples(DIL
, Reader
->getRemapper());
756 return it
.first
->second
;
759 /// Check whether the indirect call promotion history of \p Inst allows
760 /// the promotion for \p Candidate.
761 /// If the profile count for the promotion candidate \p Candidate is
762 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
763 /// for \p Inst. If we already have at least MaxNumPromotions
764 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
765 /// cannot promote for \p Inst anymore.
766 static bool doesHistoryAllowICP(const Instruction
&Inst
, StringRef Candidate
) {
767 uint32_t NumVals
= 0;
768 uint64_t TotalCount
= 0;
769 std::unique_ptr
<InstrProfValueData
[]> ValueData
=
770 std::make_unique
<InstrProfValueData
[]>(MaxNumPromotions
);
772 getValueProfDataFromInst(Inst
, IPVK_IndirectCallTarget
, MaxNumPromotions
,
773 ValueData
.get(), NumVals
, TotalCount
, true);
774 // No valid value profile so no promoted targets have been recorded
775 // before. Ok to do ICP.
779 unsigned NumPromoted
= 0;
780 for (uint32_t I
= 0; I
< NumVals
; I
++) {
781 if (ValueData
[I
].Count
!= NOMORE_ICP_MAGICNUM
)
784 // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
785 // metadata, it means the candidate has been promoted for this
787 if (ValueData
[I
].Value
== Function::getGUID(Candidate
))
790 // If already have MaxNumPromotions promotion, don't do it anymore.
791 if (NumPromoted
== MaxNumPromotions
)
797 /// Update indirect call target profile metadata for \p Inst.
798 /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
799 /// If it is 0, it means updateIDTMetaData is used to mark a
800 /// certain target to be promoted already. If it is not zero,
801 /// we expect to use it to update the total count in the value profile.
803 updateIDTMetaData(Instruction
&Inst
,
804 const SmallVectorImpl
<InstrProfValueData
> &CallTargets
,
806 // Bail out early if MaxNumPromotions is zero.
807 // This prevents allocating an array of zero length below.
809 // Note `updateIDTMetaData` is called in two places so check
810 // `MaxNumPromotions` inside it.
811 if (MaxNumPromotions
== 0)
813 uint32_t NumVals
= 0;
814 // OldSum is the existing total count in the value profile data.
816 std::unique_ptr
<InstrProfValueData
[]> ValueData
=
817 std::make_unique
<InstrProfValueData
[]>(MaxNumPromotions
);
819 getValueProfDataFromInst(Inst
, IPVK_IndirectCallTarget
, MaxNumPromotions
,
820 ValueData
.get(), NumVals
, OldSum
, true);
822 DenseMap
<uint64_t, uint64_t> ValueCountMap
;
824 assert((CallTargets
.size() == 1 &&
825 CallTargets
[0].Count
== NOMORE_ICP_MAGICNUM
) &&
826 "If sum is 0, assume only one element in CallTargets "
827 "with count being NOMORE_ICP_MAGICNUM");
828 // Initialize ValueCountMap with existing value profile data.
830 for (uint32_t I
= 0; I
< NumVals
; I
++)
831 ValueCountMap
[ValueData
[I
].Value
] = ValueData
[I
].Count
;
834 ValueCountMap
.try_emplace(CallTargets
[0].Value
, CallTargets
[0].Count
);
835 // If the target already exists in value profile, decrease the total
836 // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
838 OldSum
-= Pair
.first
->second
;
839 Pair
.first
->second
= NOMORE_ICP_MAGICNUM
;
843 // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
844 // counts in the value profile.
846 for (uint32_t I
= 0; I
< NumVals
; I
++) {
847 if (ValueData
[I
].Count
== NOMORE_ICP_MAGICNUM
)
848 ValueCountMap
[ValueData
[I
].Value
] = ValueData
[I
].Count
;
852 for (const auto &Data
: CallTargets
) {
853 auto Pair
= ValueCountMap
.try_emplace(Data
.Value
, Data
.Count
);
856 // The target represented by Data.Value has already been promoted.
857 // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
858 // Sum by Data.Count.
859 assert(Sum
>= Data
.Count
&& "Sum should never be less than Data.Count");
864 SmallVector
<InstrProfValueData
, 8> NewCallTargets
;
865 for (const auto &ValueCount
: ValueCountMap
) {
866 NewCallTargets
.emplace_back(
867 InstrProfValueData
{ValueCount
.first
, ValueCount
.second
});
870 llvm::sort(NewCallTargets
,
871 [](const InstrProfValueData
&L
, const InstrProfValueData
&R
) {
872 if (L
.Count
!= R
.Count
)
873 return L
.Count
> R
.Count
;
874 return L
.Value
> R
.Value
;
877 uint32_t MaxMDCount
=
878 std::min(NewCallTargets
.size(), static_cast<size_t>(MaxNumPromotions
));
879 annotateValueSite(*Inst
.getParent()->getParent()->getParent(), Inst
,
880 NewCallTargets
, Sum
, IPVK_IndirectCallTarget
, MaxMDCount
);
883 /// Attempt to promote indirect call and also inline the promoted call.
885 /// \param F Caller function.
886 /// \param Candidate ICP and inline candidate.
887 /// \param SumOrigin Original sum of target counts for indirect call before
888 /// promoting given candidate.
889 /// \param Sum Prorated sum of remaining target counts for indirect call
890 /// after promoting given candidate.
891 /// \param InlinedCallSite Output vector for new call sites exposed after
893 bool SampleProfileLoader::tryPromoteAndInlineCandidate(
894 Function
&F
, InlineCandidate
&Candidate
, uint64_t SumOrigin
, uint64_t &Sum
,
895 SmallVector
<CallBase
*, 8> *InlinedCallSite
) {
896 // Bail out early if sample-loader inliner is disabled.
897 if (DisableSampleLoaderInlining
)
900 // Bail out early if MaxNumPromotions is zero.
901 // This prevents allocating an array of zero length in callees below.
902 if (MaxNumPromotions
== 0)
904 auto CalleeFunctionName
= Candidate
.CalleeSamples
->getFuncName();
905 auto R
= SymbolMap
.find(CalleeFunctionName
);
906 if (R
== SymbolMap
.end() || !R
->getValue())
909 auto &CI
= *Candidate
.CallInstr
;
910 if (!doesHistoryAllowICP(CI
, R
->getValue()->getName()))
913 const char *Reason
= "Callee function not available";
914 // R->getValue() != &F is to prevent promoting a recursive call.
915 // If it is a recursive call, we do not inline it as it could bloat
916 // the code exponentially. There is way to better handle this, e.g.
917 // clone the caller first, and inline the cloned caller if it is
918 // recursive. As llvm does not inline recursive calls, we will
919 // simply ignore it instead of handling it explicitly.
920 if (!R
->getValue()->isDeclaration() && R
->getValue()->getSubprogram() &&
921 R
->getValue()->hasFnAttribute("use-sample-profile") &&
922 R
->getValue() != &F
&& isLegalToPromote(CI
, R
->getValue(), &Reason
)) {
923 // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
924 // in the value profile metadata so the target won't be promoted again.
925 SmallVector
<InstrProfValueData
, 1> SortedCallTargets
= {InstrProfValueData
{
926 Function::getGUID(R
->getValue()->getName()), NOMORE_ICP_MAGICNUM
}};
927 updateIDTMetaData(CI
, SortedCallTargets
, 0);
929 auto *DI
= &pgo::promoteIndirectCall(
930 CI
, R
->getValue(), Candidate
.CallsiteCount
, Sum
, false, ORE
);
932 Sum
-= Candidate
.CallsiteCount
;
933 // Do not prorate the indirect callsite distribution since the original
934 // distribution will be used to scale down non-promoted profile target
935 // counts later. By doing this we lose track of the real callsite count
936 // for the leftover indirect callsite as a trade off for accurate call
938 // TODO: Ideally we would have two separate factors, one for call site
939 // counts and one is used to prorate call target counts.
940 // Do not update the promoted direct callsite distribution at this
941 // point since the original distribution combined with the callee profile
942 // will be used to prorate callsites from the callee if inlined. Once not
943 // inlined, the direct callsite distribution should be prorated so that
944 // the it will reflect the real callsite counts.
945 Candidate
.CallInstr
= DI
;
946 if (isa
<CallInst
>(DI
) || isa
<InvokeInst
>(DI
)) {
947 bool Inlined
= tryInlineCandidate(Candidate
, InlinedCallSite
);
949 // Prorate the direct callsite distribution so that it reflects real
951 setProbeDistributionFactor(
952 *DI
, static_cast<float>(Candidate
.CallsiteCount
) / SumOrigin
);
958 LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
959 << Candidate
.CalleeSamples
->getFuncName() << " because "
965 bool SampleProfileLoader::shouldInlineColdCallee(CallBase
&CallInst
) {
966 if (!ProfileSizeInline
)
969 Function
*Callee
= CallInst
.getCalledFunction();
970 if (Callee
== nullptr)
973 InlineCost Cost
= getInlineCost(CallInst
, getInlineParams(), GetTTI(*Callee
),
982 return Cost
.getCost() <= SampleColdCallSiteThreshold
;
985 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
986 const SmallVectorImpl
<CallBase
*> &Candidates
, const Function
&F
,
988 for (auto I
: Candidates
) {
989 Function
*CalledFunction
= I
->getCalledFunction();
990 if (CalledFunction
) {
991 ORE
->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
992 "InlineAttempt", I
->getDebugLoc(),
994 << "previous inlining reattempted for "
995 << (Hot
? "hotness: '" : "size: '")
996 << ore::NV("Callee", CalledFunction
) << "' into '"
997 << ore::NV("Caller", &F
) << "'");
1002 void SampleProfileLoader::findExternalInlineCandidate(
1003 CallBase
*CB
, const FunctionSamples
*Samples
,
1004 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
,
1005 const StringMap
<Function
*> &SymbolMap
, uint64_t Threshold
) {
1007 // If ExternalInlineAdvisor wants to inline an external function
1008 // make sure it's imported
1009 if (CB
&& getExternalInlineAdvisorShouldInline(*CB
)) {
1010 // Samples may not exist for replayed function, if so
1011 // just add the direct GUID and move on
1013 InlinedGUIDs
.insert(
1014 FunctionSamples::getGUID(CB
->getCalledFunction()->getName()));
1017 // Otherwise, drop the threshold to import everything that we can
1021 assert(Samples
&& "expect non-null caller profile");
1023 // For AutoFDO profile, retrieve candidate profiles by walking over
1024 // the nested inlinee profiles.
1025 if (!FunctionSamples::ProfileIsCS
) {
1026 Samples
->findInlinedFunctions(InlinedGUIDs
, SymbolMap
, Threshold
);
1030 ContextTrieNode
*Caller
= ContextTracker
->getContextNodeForProfile(Samples
);
1031 std::queue
<ContextTrieNode
*> CalleeList
;
1032 CalleeList
.push(Caller
);
1033 while (!CalleeList
.empty()) {
1034 ContextTrieNode
*Node
= CalleeList
.front();
1036 FunctionSamples
*CalleeSample
= Node
->getFunctionSamples();
1037 // For CSSPGO profile, retrieve candidate profile by walking over the
1038 // trie built for context profile. Note that also take call targets
1039 // even if callee doesn't have a corresponding context profile.
1043 // If pre-inliner decision is used, honor that for importing as well.
1045 UsePreInlinerDecision
&&
1046 CalleeSample
->getContext().hasAttribute(ContextShouldBeInlined
);
1047 if (!PreInline
&& CalleeSample
->getHeadSamplesEstimate() < Threshold
)
1050 StringRef Name
= CalleeSample
->getFuncName();
1051 Function
*Func
= SymbolMap
.lookup(Name
);
1052 // Add to the import list only when it's defined out of module.
1053 if (!Func
|| Func
->isDeclaration())
1054 InlinedGUIDs
.insert(FunctionSamples::getGUID(CalleeSample
->getName()));
1056 // Import hot CallTargets, which may not be available in IR because full
1057 // profile annotation cannot be done until backend compilation in ThinLTO.
1058 for (const auto &BS
: CalleeSample
->getBodySamples())
1059 for (const auto &TS
: BS
.second
.getCallTargets())
1060 if (TS
.getValue() > Threshold
) {
1061 StringRef CalleeName
= CalleeSample
->getFuncName(TS
.getKey());
1062 const Function
*Callee
= SymbolMap
.lookup(CalleeName
);
1063 if (!Callee
|| Callee
->isDeclaration())
1064 InlinedGUIDs
.insert(FunctionSamples::getGUID(TS
.getKey()));
1067 // Import hot child context profile associted with callees. Note that this
1068 // may have some overlap with the call target loop above, but doing this
1069 // based child context profile again effectively allow us to use the max of
1070 // entry count and call target count to determine importing.
1071 for (auto &Child
: Node
->getAllChildContext()) {
1072 ContextTrieNode
*CalleeNode
= &Child
.second
;
1073 CalleeList
.push(CalleeNode
);
1078 /// Iteratively inline hot callsites of a function.
1080 /// Iteratively traverse all callsites of the function \p F, so as to
1081 /// find out callsites with corresponding inline instances.
1083 /// For such callsites,
1084 /// - If it is hot enough, inline the callsites and adds callsites of the callee
1085 /// into the caller. If the call is an indirect call, first promote
1086 /// it to direct call. Each indirect call is limited with a single target.
1088 /// - If a callsite is not inlined, merge the its profile to the outline
1089 /// version (if --sample-profile-merge-inlinee is true), or scale the
1090 /// counters of standalone function based on the profile of inlined
1091 /// instances (if --sample-profile-merge-inlinee is false).
1093 /// Later passes may consume the updated profiles.
1095 /// \param F function to perform iterative inlining.
1096 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1097 /// inlined in the profiled binary.
1099 /// \returns True if there is any inline happened.
1100 bool SampleProfileLoader::inlineHotFunctions(
1101 Function
&F
, DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
) {
1102 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1103 // Profile symbol list is ignored when profile-sample-accurate is on.
1104 assert((!ProfAccForSymsInList
||
1105 (!ProfileSampleAccurate
&&
1106 !F
.hasFnAttribute("profile-sample-accurate"))) &&
1107 "ProfAccForSymsInList should be false when profile-sample-accurate "
1110 MapVector
<CallBase
*, const FunctionSamples
*> LocalNotInlinedCallSites
;
1111 bool Changed
= false;
1112 bool LocalChanged
= true;
1113 while (LocalChanged
) {
1114 LocalChanged
= false;
1115 SmallVector
<CallBase
*, 10> CIS
;
1116 for (auto &BB
: F
) {
1118 SmallVector
<CallBase
*, 10> AllCandidates
;
1119 SmallVector
<CallBase
*, 10> ColdCandidates
;
1120 for (auto &I
: BB
.getInstList()) {
1121 const FunctionSamples
*FS
= nullptr;
1122 if (auto *CB
= dyn_cast
<CallBase
>(&I
)) {
1123 if (!isa
<IntrinsicInst
>(I
)) {
1124 if ((FS
= findCalleeFunctionSamples(*CB
))) {
1125 assert((!FunctionSamples::UseMD5
|| FS
->GUIDToFuncNameMap
) &&
1126 "GUIDToFuncNameMap has to be populated");
1127 AllCandidates
.push_back(CB
);
1128 if (FS
->getHeadSamplesEstimate() > 0 ||
1129 FunctionSamples::ProfileIsCS
)
1130 LocalNotInlinedCallSites
.insert({CB
, FS
});
1131 if (callsiteIsHot(FS
, PSI
, ProfAccForSymsInList
))
1133 else if (shouldInlineColdCallee(*CB
))
1134 ColdCandidates
.push_back(CB
);
1135 } else if (getExternalInlineAdvisorShouldInline(*CB
)) {
1136 AllCandidates
.push_back(CB
);
1141 if (Hot
|| ExternalInlineAdvisor
) {
1142 CIS
.insert(CIS
.begin(), AllCandidates
.begin(), AllCandidates
.end());
1143 emitOptimizationRemarksForInlineCandidates(AllCandidates
, F
, true);
1145 CIS
.insert(CIS
.begin(), ColdCandidates
.begin(), ColdCandidates
.end());
1146 emitOptimizationRemarksForInlineCandidates(ColdCandidates
, F
, false);
1149 for (CallBase
*I
: CIS
) {
1150 Function
*CalledFunction
= I
->getCalledFunction();
1151 InlineCandidate Candidate
= {I
, LocalNotInlinedCallSites
.lookup(I
),
1152 0 /* dummy count */,
1153 1.0 /* dummy distribution factor */};
1154 // Do not inline recursive calls.
1155 if (CalledFunction
== &F
)
1157 if (I
->isIndirectCall()) {
1159 for (const auto *FS
: findIndirectCallFunctionSamples(*I
, Sum
)) {
1160 uint64_t SumOrigin
= Sum
;
1161 if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1162 findExternalInlineCandidate(I
, FS
, InlinedGUIDs
, SymbolMap
,
1163 PSI
->getOrCompHotCountThreshold());
1166 if (!callsiteIsHot(FS
, PSI
, ProfAccForSymsInList
))
1169 Candidate
= {I
, FS
, FS
->getHeadSamplesEstimate(), 1.0};
1170 if (tryPromoteAndInlineCandidate(F
, Candidate
, SumOrigin
, Sum
)) {
1171 LocalNotInlinedCallSites
.erase(I
);
1172 LocalChanged
= true;
1175 } else if (CalledFunction
&& CalledFunction
->getSubprogram() &&
1176 !CalledFunction
->isDeclaration()) {
1177 if (tryInlineCandidate(Candidate
)) {
1178 LocalNotInlinedCallSites
.erase(I
);
1179 LocalChanged
= true;
1181 } else if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1182 findExternalInlineCandidate(I
, findCalleeFunctionSamples(*I
),
1183 InlinedGUIDs
, SymbolMap
,
1184 PSI
->getOrCompHotCountThreshold());
1187 Changed
|= LocalChanged
;
1190 // For CS profile, profile for not inlined context will be merged when
1191 // base profile is being retrieved.
1192 if (!FunctionSamples::ProfileIsCS
)
1193 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites
, F
);
1197 bool SampleProfileLoader::tryInlineCandidate(
1198 InlineCandidate
&Candidate
, SmallVector
<CallBase
*, 8> *InlinedCallSites
) {
1199 // Do not attempt to inline a candidate if
1200 // --disable-sample-loader-inlining is true.
1201 if (DisableSampleLoaderInlining
)
1204 CallBase
&CB
= *Candidate
.CallInstr
;
1205 Function
*CalledFunction
= CB
.getCalledFunction();
1206 assert(CalledFunction
&& "Expect a callee with definition");
1207 DebugLoc DLoc
= CB
.getDebugLoc();
1208 BasicBlock
*BB
= CB
.getParent();
1210 InlineCost Cost
= shouldInlineCandidate(Candidate
);
1211 if (Cost
.isNever()) {
1212 ORE
->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1213 "InlineFail", DLoc
, BB
)
1214 << "incompatible inlining");
1221 InlineFunctionInfo
IFI(nullptr, GetAC
);
1222 IFI
.UpdateProfile
= false;
1223 if (!InlineFunction(CB
, IFI
).isSuccess())
1226 // Merge the attributes based on the inlining.
1227 AttributeFuncs::mergeAttributesForInlining(*BB
->getParent(),
1230 // The call to InlineFunction erases I, so we can't pass it here.
1231 emitInlinedIntoBasedOnCost(*ORE
, DLoc
, BB
, *CalledFunction
, *BB
->getParent(),
1232 Cost
, true, getAnnotatedRemarkPassName());
1234 // Now populate the list of newly exposed call sites.
1235 if (InlinedCallSites
) {
1236 InlinedCallSites
->clear();
1237 for (auto &I
: IFI
.InlinedCallSites
)
1238 InlinedCallSites
->push_back(I
);
1241 if (FunctionSamples::ProfileIsCS
)
1242 ContextTracker
->markContextSamplesInlined(Candidate
.CalleeSamples
);
1245 // Prorate inlined probes for a duplicated inlining callsite which probably
1246 // has a distribution less than 100%. Samples for an inlinee should be
1247 // distributed among the copies of the original callsite based on each
1248 // callsite's distribution factor for counts accuracy. Note that an inlined
1249 // probe may come with its own distribution factor if it has been duplicated
1250 // in the inlinee body. The two factor are multiplied to reflect the
1251 // aggregation of duplication.
1252 if (Candidate
.CallsiteDistribution
< 1) {
1253 for (auto &I
: IFI
.InlinedCallSites
) {
1254 if (Optional
<PseudoProbe
> Probe
= extractProbe(*I
))
1255 setProbeDistributionFactor(*I
, Probe
->Factor
*
1256 Candidate
.CallsiteDistribution
);
1258 NumDuplicatedInlinesite
++;
1264 bool SampleProfileLoader::getInlineCandidate(InlineCandidate
*NewCandidate
,
1266 assert(CB
&& "Expect non-null call instruction");
1268 if (isa
<IntrinsicInst
>(CB
))
1271 // Find the callee's profile. For indirect call, find hottest target profile.
1272 const FunctionSamples
*CalleeSamples
= findCalleeFunctionSamples(*CB
);
1273 // If ExternalInlineAdvisor wants to inline this site, do so even
1274 // if Samples are not present.
1275 if (!CalleeSamples
&& !getExternalInlineAdvisorShouldInline(*CB
))
1279 if (Optional
<PseudoProbe
> Probe
= extractProbe(*CB
))
1280 Factor
= Probe
->Factor
;
1282 uint64_t CallsiteCount
=
1283 CalleeSamples
? CalleeSamples
->getHeadSamplesEstimate() * Factor
: 0;
1284 *NewCandidate
= {CB
, CalleeSamples
, CallsiteCount
, Factor
};
1288 Optional
<InlineCost
>
1289 SampleProfileLoader::getExternalInlineAdvisorCost(CallBase
&CB
) {
1290 std::unique_ptr
<InlineAdvice
> Advice
= nullptr;
1291 if (ExternalInlineAdvisor
) {
1292 Advice
= ExternalInlineAdvisor
->getAdvice(CB
);
1294 if (!Advice
->isInliningRecommended()) {
1295 Advice
->recordUnattemptedInlining();
1296 return InlineCost::getNever("not previously inlined");
1298 Advice
->recordInlining();
1299 return InlineCost::getAlways("previously inlined");
1306 bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase
&CB
) {
1307 Optional
<InlineCost
> Cost
= getExternalInlineAdvisorCost(CB
);
1308 return Cost
? !!Cost
.value() : false;
1312 SampleProfileLoader::shouldInlineCandidate(InlineCandidate
&Candidate
) {
1313 if (Optional
<InlineCost
> ReplayCost
=
1314 getExternalInlineAdvisorCost(*Candidate
.CallInstr
))
1315 return ReplayCost
.value();
1316 // Adjust threshold based on call site hotness, only do this for callsite
1317 // prioritized inliner because otherwise cost-benefit check is done earlier.
1318 int SampleThreshold
= SampleColdCallSiteThreshold
;
1319 if (CallsitePrioritizedInline
) {
1320 if (Candidate
.CallsiteCount
> PSI
->getHotCountThreshold())
1321 SampleThreshold
= SampleHotCallSiteThreshold
;
1322 else if (!ProfileSizeInline
)
1323 return InlineCost::getNever("cold callsite");
1326 Function
*Callee
= Candidate
.CallInstr
->getCalledFunction();
1327 assert(Callee
&& "Expect a definition for inline candidate of direct call");
1329 InlineParams Params
= getInlineParams();
1330 // We will ignore the threshold from inline cost, so always get full cost.
1331 Params
.ComputeFullInlineCost
= true;
1332 Params
.AllowRecursiveCall
= AllowRecursiveInline
;
1333 // Checks if there is anything in the reachable portion of the callee at
1334 // this callsite that makes this inlining potentially illegal. Need to
1335 // set ComputeFullInlineCost, otherwise getInlineCost may return early
1336 // when cost exceeds threshold without checking all IRs in the callee.
1337 // The acutal cost does not matter because we only checks isNever() to
1338 // see if it is legal to inline the callsite.
1339 InlineCost Cost
= getInlineCost(*Candidate
.CallInstr
, Callee
, Params
,
1340 GetTTI(*Callee
), GetAC
, GetTLI
);
1342 // Honor always inline and never inline from call analyzer
1343 if (Cost
.isNever() || Cost
.isAlways())
1346 // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1347 // decisions based on hotness as well as accurate function byte sizes for
1348 // given context using function/inlinee sizes from previous build. It
1349 // stores the decision in profile, and also adjust/merge context profile
1350 // aiming at better context-sensitive post-inline profile quality, assuming
1351 // all inline decision estimates are going to be honored by compiler. Here
1352 // we replay that inline decision under `sample-profile-use-preinliner`.
1353 // Note that we don't need to handle negative decision from preinliner as
1354 // context profile for not inlined calls are merged by preinliner already.
1355 if (UsePreInlinerDecision
&& Candidate
.CalleeSamples
) {
1356 // Once two node are merged due to promotion, we're losing some context
1357 // so the original context-sensitive preinliner decision should be ignored
1358 // for SyntheticContext.
1359 SampleContext
&Context
= Candidate
.CalleeSamples
->getContext();
1360 if (!Context
.hasState(SyntheticContext
) &&
1361 Context
.hasAttribute(ContextShouldBeInlined
))
1362 return InlineCost::getAlways("preinliner");
1365 // For old FDO inliner, we inline the call site as long as cost is not
1366 // "Never". The cost-benefit check is done earlier.
1367 if (!CallsitePrioritizedInline
) {
1368 return InlineCost::get(Cost
.getCost(), INT_MAX
);
1371 // Otherwise only use the cost from call analyzer, but overwite threshold with
1372 // Sample PGO threshold.
1373 return InlineCost::get(Cost
.getCost(), SampleThreshold
);
1376 bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1377 Function
&F
, DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
) {
1378 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1379 // Profile symbol list is ignored when profile-sample-accurate is on.
1380 assert((!ProfAccForSymsInList
||
1381 (!ProfileSampleAccurate
&&
1382 !F
.hasFnAttribute("profile-sample-accurate"))) &&
1383 "ProfAccForSymsInList should be false when profile-sample-accurate "
1386 // Populating worklist with initial call sites from root inliner, along
1387 // with call site weights.
1388 CandidateQueue CQueue
;
1389 InlineCandidate NewCandidate
;
1390 for (auto &BB
: F
) {
1391 for (auto &I
: BB
.getInstList()) {
1392 auto *CB
= dyn_cast
<CallBase
>(&I
);
1395 if (getInlineCandidate(&NewCandidate
, CB
))
1396 CQueue
.push(NewCandidate
);
1400 // Cap the size growth from profile guided inlining. This is needed even
1401 // though cost of each inline candidate already accounts for callee size,
1402 // because with top-down inlining, we can grow inliner size significantly
1403 // with large number of smaller inlinees each pass the cost check.
1404 assert(ProfileInlineLimitMax
>= ProfileInlineLimitMin
&&
1405 "Max inline size limit should not be smaller than min inline size "
1407 unsigned SizeLimit
= F
.getInstructionCount() * ProfileInlineGrowthLimit
;
1408 SizeLimit
= std::min(SizeLimit
, (unsigned)ProfileInlineLimitMax
);
1409 SizeLimit
= std::max(SizeLimit
, (unsigned)ProfileInlineLimitMin
);
1410 if (ExternalInlineAdvisor
)
1411 SizeLimit
= std::numeric_limits
<unsigned>::max();
1413 MapVector
<CallBase
*, const FunctionSamples
*> LocalNotInlinedCallSites
;
1415 // Perform iterative BFS call site prioritized inlining
1416 bool Changed
= false;
1417 while (!CQueue
.empty() && F
.getInstructionCount() < SizeLimit
) {
1418 InlineCandidate Candidate
= CQueue
.top();
1420 CallBase
*I
= Candidate
.CallInstr
;
1421 Function
*CalledFunction
= I
->getCalledFunction();
1423 if (CalledFunction
== &F
)
1425 if (I
->isIndirectCall()) {
1427 auto CalleeSamples
= findIndirectCallFunctionSamples(*I
, Sum
);
1428 uint64_t SumOrigin
= Sum
;
1429 Sum
*= Candidate
.CallsiteDistribution
;
1430 unsigned ICPCount
= 0;
1431 for (const auto *FS
: CalleeSamples
) {
1432 // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1433 if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1434 findExternalInlineCandidate(I
, FS
, InlinedGUIDs
, SymbolMap
,
1435 PSI
->getOrCompHotCountThreshold());
1438 uint64_t EntryCountDistributed
=
1439 FS
->getHeadSamplesEstimate() * Candidate
.CallsiteDistribution
;
1440 // In addition to regular inline cost check, we also need to make sure
1441 // ICP isn't introducing excessive speculative checks even if individual
1442 // target looks beneficial to promote and inline. That means we should
1443 // only do ICP when there's a small number dominant targets.
1444 if (ICPCount
>= ProfileICPRelativeHotnessSkip
&&
1445 EntryCountDistributed
* 100 < SumOrigin
* ProfileICPRelativeHotness
)
1447 // TODO: Fix CallAnalyzer to handle all indirect calls.
1448 // For indirect call, we don't run CallAnalyzer to get InlineCost
1449 // before actual inlining. This is because we could see two different
1450 // types from the same definition, which makes CallAnalyzer choke as
1451 // it's expecting matching parameter type on both caller and callee
1452 // side. See example from PR18962 for the triggering cases (the bug was
1453 // fixed, but we generate different types).
1454 if (!PSI
->isHotCount(EntryCountDistributed
))
1456 SmallVector
<CallBase
*, 8> InlinedCallSites
;
1457 // Attach function profile for promoted indirect callee, and update
1458 // call site count for the promoted inline candidate too.
1459 Candidate
= {I
, FS
, EntryCountDistributed
,
1460 Candidate
.CallsiteDistribution
};
1461 if (tryPromoteAndInlineCandidate(F
, Candidate
, SumOrigin
, Sum
,
1462 &InlinedCallSites
)) {
1463 for (auto *CB
: InlinedCallSites
) {
1464 if (getInlineCandidate(&NewCandidate
, CB
))
1465 CQueue
.emplace(NewCandidate
);
1469 } else if (!ContextTracker
) {
1470 LocalNotInlinedCallSites
.insert({I
, FS
});
1473 } else if (CalledFunction
&& CalledFunction
->getSubprogram() &&
1474 !CalledFunction
->isDeclaration()) {
1475 SmallVector
<CallBase
*, 8> InlinedCallSites
;
1476 if (tryInlineCandidate(Candidate
, &InlinedCallSites
)) {
1477 for (auto *CB
: InlinedCallSites
) {
1478 if (getInlineCandidate(&NewCandidate
, CB
))
1479 CQueue
.emplace(NewCandidate
);
1482 } else if (!ContextTracker
) {
1483 LocalNotInlinedCallSites
.insert({I
, Candidate
.CalleeSamples
});
1485 } else if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1486 findExternalInlineCandidate(I
, findCalleeFunctionSamples(*I
),
1487 InlinedGUIDs
, SymbolMap
,
1488 PSI
->getOrCompHotCountThreshold());
1492 if (!CQueue
.empty()) {
1493 if (SizeLimit
== (unsigned)ProfileInlineLimitMax
)
1494 ++NumCSInlinedHitMaxLimit
;
1495 else if (SizeLimit
== (unsigned)ProfileInlineLimitMin
)
1496 ++NumCSInlinedHitMinLimit
;
1498 ++NumCSInlinedHitGrowthLimit
;
1501 // For CS profile, profile for not inlined context will be merged when
1502 // base profile is being retrieved.
1503 if (!FunctionSamples::ProfileIsCS
)
1504 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites
, F
);
1508 void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1509 MapVector
<CallBase
*, const FunctionSamples
*> NonInlinedCallSites
,
1510 const Function
&F
) {
1511 // Accumulate not inlined callsite information into notInlinedSamples
1512 for (const auto &Pair
: NonInlinedCallSites
) {
1513 CallBase
*I
= Pair
.first
;
1514 Function
*Callee
= I
->getCalledFunction();
1515 if (!Callee
|| Callee
->isDeclaration())
1519 OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
1520 I
->getDebugLoc(), I
->getParent())
1521 << "previous inlining not repeated: '" << ore::NV("Callee", Callee
)
1522 << "' into '" << ore::NV("Caller", &F
) << "'");
1525 const FunctionSamples
*FS
= Pair
.second
;
1526 if (FS
->getTotalSamples() == 0 && FS
->getHeadSamplesEstimate() == 0) {
1530 // Do not merge a context that is already duplicated into the base profile.
1531 if (FS
->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase
))
1534 if (ProfileMergeInlinee
) {
1535 // A function call can be replicated by optimizations like callsite
1536 // splitting or jump threading and the replicates end up sharing the
1537 // sample nested callee profile instead of slicing the original
1538 // inlinee's profile. We want to do merge exactly once by filtering out
1539 // callee profiles with a non-zero head sample count.
1540 if (FS
->getHeadSamples() == 0) {
1541 // Use entry samples as head samples during the merge, as inlinees
1542 // don't have head samples.
1543 const_cast<FunctionSamples
*>(FS
)->addHeadSamples(
1544 FS
->getHeadSamplesEstimate());
1546 // Note that we have to do the merge right after processing function.
1547 // This allows OutlineFS's profile to be used for annotation during
1548 // top-down processing of functions' annotation.
1549 FunctionSamples
*OutlineFS
= Reader
->getOrCreateSamplesFor(*Callee
);
1550 OutlineFS
->merge(*FS
, 1);
1551 // Set outlined profile to be synthetic to not bias the inliner.
1552 OutlineFS
->SetContextSynthetic();
1556 notInlinedCallInfo
.try_emplace(Callee
, NotInlinedProfileInfo
{0});
1557 pair
.first
->second
.entryCount
+= FS
->getHeadSamplesEstimate();
1562 /// Returns the sorted CallTargetMap \p M by count in descending order.
1563 static SmallVector
<InstrProfValueData
, 2>
1564 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap
&M
) {
1565 SmallVector
<InstrProfValueData
, 2> R
;
1566 for (const auto &I
: SampleRecord::SortCallTargets(M
)) {
1568 InstrProfValueData
{FunctionSamples::getGUID(I
.first
), I
.second
});
1573 // Generate MD_prof metadata for every branch instruction using the
1574 // edge weights computed during propagation.
1575 void SampleProfileLoader::generateMDProfMetadata(Function
&F
) {
1576 // Generate MD_prof metadata for every branch instruction using the
1577 // edge weights computed during propagation.
1578 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1579 LLVMContext
&Ctx
= F
.getContext();
1581 for (auto &BI
: F
) {
1582 BasicBlock
*BB
= &BI
;
1584 if (BlockWeights
[BB
]) {
1585 for (auto &I
: BB
->getInstList()) {
1586 if (!isa
<CallInst
>(I
) && !isa
<InvokeInst
>(I
))
1588 if (!cast
<CallBase
>(I
).getCalledFunction()) {
1589 const DebugLoc
&DLoc
= I
.getDebugLoc();
1592 const DILocation
*DIL
= DLoc
;
1593 const FunctionSamples
*FS
= findFunctionSamples(I
);
1596 auto CallSite
= FunctionSamples::getCallSiteIdentifier(DIL
);
1597 auto T
= FS
->findCallTargetMapAt(CallSite
);
1598 if (!T
|| T
.get().empty())
1600 if (FunctionSamples::ProfileIsProbeBased
) {
1601 // Prorate the callsite counts based on the pre-ICP distribution
1602 // factor to reflect what is already done to the callsite before
1603 // ICP, such as calliste cloning.
1604 if (Optional
<PseudoProbe
> Probe
= extractProbe(I
)) {
1605 if (Probe
->Factor
< 1)
1606 T
= SampleRecord::adjustCallTargets(T
.get(), Probe
->Factor
);
1609 SmallVector
<InstrProfValueData
, 2> SortedCallTargets
=
1610 GetSortedValueDataFromCallTargets(T
.get());
1612 for (const auto &C
: T
.get())
1614 // With CSSPGO all indirect call targets are counted torwards the
1615 // original indirect call site in the profile, including both
1616 // inlined and non-inlined targets.
1617 if (!FunctionSamples::ProfileIsCS
) {
1618 if (const FunctionSamplesMap
*M
=
1619 FS
->findFunctionSamplesMapAt(CallSite
)) {
1620 for (const auto &NameFS
: *M
)
1621 Sum
+= NameFS
.second
.getHeadSamplesEstimate();
1625 updateIDTMetaData(I
, SortedCallTargets
, Sum
);
1626 else if (OverwriteExistingWeights
)
1627 I
.setMetadata(LLVMContext::MD_prof
, nullptr);
1628 } else if (!isa
<IntrinsicInst
>(&I
)) {
1629 I
.setMetadata(LLVMContext::MD_prof
,
1630 MDB
.createBranchWeights(
1631 {static_cast<uint32_t>(BlockWeights
[BB
])}));
1634 } else if (OverwriteExistingWeights
|| ProfileSampleBlockAccurate
) {
1635 // Set profile metadata (possibly annotated by LTO prelink) to zero or
1636 // clear it for cold code.
1637 for (auto &I
: BB
->getInstList()) {
1638 if (isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
)) {
1639 if (cast
<CallBase
>(I
).isIndirectCall())
1640 I
.setMetadata(LLVMContext::MD_prof
, nullptr);
1642 I
.setMetadata(LLVMContext::MD_prof
, MDB
.createBranchWeights(0));
1647 Instruction
*TI
= BB
->getTerminator();
1648 if (TI
->getNumSuccessors() == 1)
1650 if (!isa
<BranchInst
>(TI
) && !isa
<SwitchInst
>(TI
) &&
1651 !isa
<IndirectBrInst
>(TI
))
1654 DebugLoc BranchLoc
= TI
->getDebugLoc();
1655 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1656 << ((BranchLoc
) ? Twine(BranchLoc
.getLine())
1657 : Twine("<UNKNOWN LOCATION>"))
1659 SmallVector
<uint32_t, 4> Weights
;
1660 uint32_t MaxWeight
= 0;
1661 Instruction
*MaxDestInst
;
1662 // Since profi treats multiple edges (multiway branches) as a single edge,
1663 // we need to distribute the computed weight among the branches. We do
1664 // this by evenly splitting the edge weight among destinations.
1665 DenseMap
<const BasicBlock
*, uint64_t> EdgeMultiplicity
;
1666 std::vector
<uint64_t> EdgeIndex
;
1667 if (SampleProfileUseProfi
) {
1668 EdgeIndex
.resize(TI
->getNumSuccessors());
1669 for (unsigned I
= 0; I
< TI
->getNumSuccessors(); ++I
) {
1670 const BasicBlock
*Succ
= TI
->getSuccessor(I
);
1671 EdgeIndex
[I
] = EdgeMultiplicity
[Succ
];
1672 EdgeMultiplicity
[Succ
]++;
1675 for (unsigned I
= 0; I
< TI
->getNumSuccessors(); ++I
) {
1676 BasicBlock
*Succ
= TI
->getSuccessor(I
);
1677 Edge E
= std::make_pair(BB
, Succ
);
1678 uint64_t Weight
= EdgeWeights
[E
];
1679 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E
));
1680 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1681 // if needed. Sample counts in profiles are 64-bit unsigned values,
1682 // but internally branch weights are expressed as 32-bit values.
1683 if (Weight
> std::numeric_limits
<uint32_t>::max()) {
1684 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1685 Weight
= std::numeric_limits
<uint32_t>::max();
1687 if (!SampleProfileUseProfi
) {
1688 // Weight is added by one to avoid propagation errors introduced by
1690 Weights
.push_back(static_cast<uint32_t>(Weight
+ 1));
1692 // Profi creates proper weights that do not require "+1" adjustments but
1693 // we evenly split the weight among branches with the same destination.
1694 uint64_t W
= Weight
/ EdgeMultiplicity
[Succ
];
1695 // Rounding up, if needed, so that first branches are hotter.
1696 if (EdgeIndex
[I
] < Weight
% EdgeMultiplicity
[Succ
])
1698 Weights
.push_back(static_cast<uint32_t>(W
));
1701 if (Weight
> MaxWeight
) {
1703 MaxDestInst
= Succ
->getFirstNonPHIOrDbgOrLifetime();
1708 // FIXME: Re-enable for sample profiling after investigating why the sum
1709 // of branch weights can be 0
1711 // misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
1713 uint64_t TempWeight
;
1714 // Only set weights if there is at least one non-zero weight.
1715 // In any other case, let the analyzer set weights.
1716 // Do not set weights if the weights are present unless under
1717 // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1718 // twice. If the first annotation already set the weights, the second pass
1719 // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1720 // weight should have their existing metadata (possibly annotated by LTO
1721 // prelink) cleared.
1722 if (MaxWeight
> 0 &&
1723 (!TI
->extractProfTotalWeight(TempWeight
) || OverwriteExistingWeights
)) {
1724 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1725 TI
->setMetadata(LLVMContext::MD_prof
, MDB
.createBranchWeights(Weights
));
1727 return OptimizationRemark(DEBUG_TYPE
, "PopularDest", MaxDestInst
)
1728 << "most popular destination for conditional branches at "
1729 << ore::NV("CondBranchesLoc", BranchLoc
);
1732 if (OverwriteExistingWeights
) {
1733 TI
->setMetadata(LLVMContext::MD_prof
, nullptr);
1734 LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1736 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1742 /// Once all the branch weights are computed, we emit the MD_prof
1743 /// metadata on BB using the computed values for each of its branches.
1745 /// \param F The function to query.
1747 /// \returns true if \p F was modified. Returns false, otherwise.
1748 bool SampleProfileLoader::emitAnnotations(Function
&F
) {
1749 bool Changed
= false;
1751 if (FunctionSamples::ProfileIsProbeBased
) {
1752 if (!ProbeManager
->profileIsValid(F
, *Samples
)) {
1754 dbgs() << "Profile is invalid due to CFG mismatch for Function "
1756 ++NumMismatchedProfile
;
1759 ++NumMatchedProfile
;
1761 if (getFunctionLoc(F
) == 0)
1764 LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1765 << F
.getName() << ": " << getFunctionLoc(F
) << "\n");
1768 DenseSet
<GlobalValue::GUID
> InlinedGUIDs
;
1769 if (CallsitePrioritizedInline
)
1770 Changed
|= inlineHotFunctionsWithPriority(F
, InlinedGUIDs
);
1772 Changed
|= inlineHotFunctions(F
, InlinedGUIDs
);
1774 Changed
|= computeAndPropagateWeights(F
, InlinedGUIDs
);
1777 generateMDProfMetadata(F
);
1779 emitCoverageRemarks(F
);
1783 std::unique_ptr
<ProfiledCallGraph
>
1784 SampleProfileLoader::buildProfiledCallGraph(CallGraph
&CG
) {
1785 std::unique_ptr
<ProfiledCallGraph
> ProfiledCG
;
1786 if (FunctionSamples::ProfileIsCS
)
1787 ProfiledCG
= std::make_unique
<ProfiledCallGraph
>(*ContextTracker
);
1789 ProfiledCG
= std::make_unique
<ProfiledCallGraph
>(Reader
->getProfiles());
1791 // Add all functions into the profiled call graph even if they are not in
1792 // the profile. This makes sure functions missing from the profile still
1793 // gets a chance to be processed.
1794 for (auto &Node
: CG
) {
1795 const auto *F
= Node
.first
;
1796 if (!F
|| F
->isDeclaration() || !F
->hasFnAttribute("use-sample-profile"))
1798 ProfiledCG
->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F
));
1804 std::vector
<Function
*>
1805 SampleProfileLoader::buildFunctionOrder(Module
&M
, CallGraph
*CG
) {
1806 std::vector
<Function
*> FunctionOrderList
;
1807 FunctionOrderList
.reserve(M
.size());
1809 if (!ProfileTopDownLoad
&& UseProfiledCallGraph
)
1810 errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1811 "together with -sample-profile-top-down-load.\n";
1813 if (!ProfileTopDownLoad
|| CG
== nullptr) {
1814 if (ProfileMergeInlinee
) {
1815 // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1816 // because the profile for a function may be used for the profile
1817 // annotation of its outline copy before the profile merging of its
1818 // non-inlined inline instances, and that is not the way how
1819 // ProfileMergeInlinee is supposed to work.
1820 ProfileMergeInlinee
= false;
1823 for (Function
&F
: M
)
1824 if (!F
.isDeclaration() && F
.hasFnAttribute("use-sample-profile"))
1825 FunctionOrderList
.push_back(&F
);
1826 return FunctionOrderList
;
1829 assert(&CG
->getModule() == &M
);
1831 if (UseProfiledCallGraph
|| (FunctionSamples::ProfileIsCS
&&
1832 !UseProfiledCallGraph
.getNumOccurrences())) {
1833 // Use profiled call edges to augment the top-down order. There are cases
1834 // that the top-down order computed based on the static call graph doesn't
1835 // reflect real execution order. For example
1837 // 1. Incomplete static call graph due to unknown indirect call targets.
1838 // Adjusting the order by considering indirect call edges from the
1839 // profile can enable the inlining of indirect call targets by allowing
1840 // the caller processed before them.
1841 // 2. Mutual call edges in an SCC. The static processing order computed for
1842 // an SCC may not reflect the call contexts in the context-sensitive
1843 // profile, thus may cause potential inlining to be overlooked. The
1844 // function order in one SCC is being adjusted to a top-down order based
1845 // on the profile to favor more inlining. This is only a problem with CS
1847 // 3. Transitive indirect call edges due to inlining. When a callee function
1848 // (say B) is inlined into into a caller function (say A) in LTO prelink,
1849 // every call edge originated from the callee B will be transferred to
1850 // the caller A. If any transferred edge (say A->C) is indirect, the
1851 // original profiled indirect edge B->C, even if considered, would not
1852 // enforce a top-down order from the caller A to the potential indirect
1853 // call target C in LTO postlink since the inlined callee B is gone from
1854 // the static call graph.
1855 // 4. #3 can happen even for direct call targets, due to functions defined
1856 // in header files. A header function (say A), when included into source
1857 // files, is defined multiple times but only one definition survives due
1858 // to ODR. Therefore, the LTO prelink inlining done on those dropped
1859 // definitions can be useless based on a local file scope. More
1860 // importantly, the inlinee (say B), once fully inlined to a
1861 // to-be-dropped A, will have no profile to consume when its outlined
1862 // version is compiled. This can lead to a profile-less prelink
1863 // compilation for the outlined version of B which may be called from
1864 // external modules. while this isn't easy to fix, we rely on the
1865 // postlink AutoFDO pipeline to optimize B. Since the survived copy of
1866 // the A can be inlined in its local scope in prelink, it may not exist
1867 // in the merged IR in postlink, and we'll need the profiled call edges
1868 // to enforce a top-down order for the rest of the functions.
1870 // Considering those cases, a profiled call graph completely independent of
1871 // the static call graph is constructed based on profile data, where
1872 // function objects are not even needed to handle case #3 and case 4.
1874 // Note that static callgraph edges are completely ignored since they
1875 // can be conflicting with profiled edges for cyclic SCCs and may result in
1876 // an SCC order incompatible with profile-defined one. Using strictly
1877 // profile order ensures a maximum inlining experience. On the other hand,
1878 // static call edges are not so important when they don't correspond to a
1879 // context in the profile.
1881 std::unique_ptr
<ProfiledCallGraph
> ProfiledCG
= buildProfiledCallGraph(*CG
);
1882 scc_iterator
<ProfiledCallGraph
*> CGI
= scc_begin(ProfiledCG
.get());
1883 while (!CGI
.isAtEnd()) {
1885 if (SortProfiledSCC
) {
1886 // Sort nodes in one SCC based on callsite hotness.
1887 scc_member_iterator
<ProfiledCallGraph
*> SI(*CGI
);
1890 for (auto *Node
: Range
) {
1891 Function
*F
= SymbolMap
.lookup(Node
->Name
);
1892 if (F
&& !F
->isDeclaration() && F
->hasFnAttribute("use-sample-profile"))
1893 FunctionOrderList
.push_back(F
);
1898 scc_iterator
<CallGraph
*> CGI
= scc_begin(CG
);
1899 while (!CGI
.isAtEnd()) {
1900 for (CallGraphNode
*Node
: *CGI
) {
1901 auto *F
= Node
->getFunction();
1902 if (F
&& !F
->isDeclaration() && F
->hasFnAttribute("use-sample-profile"))
1903 FunctionOrderList
.push_back(F
);
1910 dbgs() << "Function processing order:\n";
1911 for (auto F
: reverse(FunctionOrderList
)) {
1912 dbgs() << F
->getName() << "\n";
1916 std::reverse(FunctionOrderList
.begin(), FunctionOrderList
.end());
1917 return FunctionOrderList
;
1920 bool SampleProfileLoader::doInitialization(Module
&M
,
1921 FunctionAnalysisManager
*FAM
) {
1922 auto &Ctx
= M
.getContext();
1924 auto ReaderOrErr
= SampleProfileReader::create(
1925 Filename
, Ctx
, FSDiscriminatorPass::Base
, RemappingFilename
);
1926 if (std::error_code EC
= ReaderOrErr
.getError()) {
1927 std::string Msg
= "Could not open profile: " + EC
.message();
1928 Ctx
.diagnose(DiagnosticInfoSampleProfile(Filename
, Msg
));
1931 Reader
= std::move(ReaderOrErr
.get());
1932 Reader
->setSkipFlatProf(LTOPhase
== ThinOrFullLTOPhase::ThinLTOPostLink
);
1933 // set module before reading the profile so reader may be able to only
1934 // read the function profiles which are used by the current module.
1935 Reader
->setModule(&M
);
1936 if (std::error_code EC
= Reader
->read()) {
1937 std::string Msg
= "profile reading failed: " + EC
.message();
1938 Ctx
.diagnose(DiagnosticInfoSampleProfile(Filename
, Msg
));
1942 PSL
= Reader
->getProfileSymbolList();
1944 // While profile-sample-accurate is on, ignore symbol list.
1945 ProfAccForSymsInList
=
1946 ProfileAccurateForSymsInList
&& PSL
&& !ProfileSampleAccurate
;
1947 if (ProfAccForSymsInList
) {
1948 NamesInProfile
.clear();
1949 if (auto NameTable
= Reader
->getNameTable())
1950 NamesInProfile
.insert(NameTable
->begin(), NameTable
->end());
1951 CoverageTracker
.setProfAccForSymsInList(true);
1954 if (FAM
&& !ProfileInlineReplayFile
.empty()) {
1955 ExternalInlineAdvisor
= getReplayInlineAdvisor(
1956 M
, *FAM
, Ctx
, /*OriginalAdvisor=*/nullptr,
1957 ReplayInlinerSettings
{ProfileInlineReplayFile
,
1958 ProfileInlineReplayScope
,
1959 ProfileInlineReplayFallback
,
1960 {ProfileInlineReplayFormat
}},
1961 /*EmitRemarks=*/false, InlineContext
{LTOPhase
, InlinePass::ReplaySampleProfileInliner
});
1964 // Apply tweaks if context-sensitive or probe-based profile is available.
1965 if (Reader
->profileIsCS() || Reader
->profileIsPreInlined() ||
1966 Reader
->profileIsProbeBased()) {
1967 if (!UseIterativeBFIInference
.getNumOccurrences())
1968 UseIterativeBFIInference
= true;
1969 if (!SampleProfileUseProfi
.getNumOccurrences())
1970 SampleProfileUseProfi
= true;
1971 if (!EnableExtTspBlockPlacement
.getNumOccurrences())
1972 EnableExtTspBlockPlacement
= true;
1973 // Enable priority-base inliner and size inline by default for CSSPGO.
1974 if (!ProfileSizeInline
.getNumOccurrences())
1975 ProfileSizeInline
= true;
1976 if (!CallsitePrioritizedInline
.getNumOccurrences())
1977 CallsitePrioritizedInline
= true;
1978 // For CSSPGO, we also allow recursive inline to best use context profile.
1979 if (!AllowRecursiveInline
.getNumOccurrences())
1980 AllowRecursiveInline
= true;
1982 if (Reader
->profileIsPreInlined()) {
1983 if (!UsePreInlinerDecision
.getNumOccurrences())
1984 UsePreInlinerDecision
= true;
1987 if (!Reader
->profileIsCS()) {
1988 // Non-CS profile should be fine without a function size budget for the
1989 // inliner since the contexts in the profile are either all from inlining
1990 // in the prevoius build or pre-computed by the preinliner with a size
1991 // cap, thus they are bounded.
1992 if (!ProfileInlineLimitMin
.getNumOccurrences())
1993 ProfileInlineLimitMin
= std::numeric_limits
<unsigned>::max();
1994 if (!ProfileInlineLimitMax
.getNumOccurrences())
1995 ProfileInlineLimitMax
= std::numeric_limits
<unsigned>::max();
1999 if (Reader
->profileIsCS()) {
2000 // Tracker for profiles under different context
2001 ContextTracker
= std::make_unique
<SampleContextTracker
>(
2002 Reader
->getProfiles(), &GUIDToFuncNameMap
);
2005 // Load pseudo probe descriptors for probe-based function samples.
2006 if (Reader
->profileIsProbeBased()) {
2007 ProbeManager
= std::make_unique
<PseudoProbeManager
>(M
);
2008 if (!ProbeManager
->moduleIsProbed(M
)) {
2010 "Pseudo-probe-based profile requires SampleProfileProbePass";
2011 Ctx
.diagnose(DiagnosticInfoSampleProfile(M
.getModuleIdentifier(), Msg
,
2020 bool SampleProfileLoader::runOnModule(Module
&M
, ModuleAnalysisManager
*AM
,
2021 ProfileSummaryInfo
*_PSI
, CallGraph
*CG
) {
2022 GUIDToFuncNameMapper
Mapper(M
, *Reader
, GUIDToFuncNameMap
);
2025 if (M
.getProfileSummary(/* IsCS */ false) == nullptr) {
2026 M
.setProfileSummary(Reader
->getSummary().getMD(M
.getContext()),
2027 ProfileSummary::PSK_Sample
);
2030 // Compute the total number of samples collected in this profile.
2031 for (const auto &I
: Reader
->getProfiles())
2032 TotalCollectedSamples
+= I
.second
.getTotalSamples();
2034 auto Remapper
= Reader
->getRemapper();
2035 // Populate the symbol map.
2036 for (const auto &N_F
: M
.getValueSymbolTable()) {
2037 StringRef OrigName
= N_F
.getKey();
2038 Function
*F
= dyn_cast
<Function
>(N_F
.getValue());
2039 if (F
== nullptr || OrigName
.empty())
2041 SymbolMap
[OrigName
] = F
;
2042 StringRef NewName
= FunctionSamples::getCanonicalFnName(*F
);
2043 if (OrigName
!= NewName
&& !NewName
.empty()) {
2044 auto r
= SymbolMap
.insert(std::make_pair(NewName
, F
));
2045 // Failiing to insert means there is already an entry in SymbolMap,
2046 // thus there are multiple functions that are mapped to the same
2047 // stripped name. In this case of name conflicting, set the value
2048 // to nullptr to avoid confusion.
2050 r
.first
->second
= nullptr;
2053 // Insert the remapped names into SymbolMap.
2055 if (auto MapName
= Remapper
->lookUpNameInProfile(OrigName
)) {
2056 if (*MapName
!= OrigName
&& !MapName
->empty())
2057 SymbolMap
.insert(std::make_pair(*MapName
, F
));
2061 assert(SymbolMap
.count(StringRef()) == 0 &&
2062 "No empty StringRef should be added in SymbolMap");
2064 bool retval
= false;
2065 for (auto F
: buildFunctionOrder(M
, CG
)) {
2066 assert(!F
->isDeclaration());
2067 clearFunctionData();
2068 retval
|= runOnFunction(*F
, AM
);
2071 // Account for cold calls not inlined....
2072 if (!FunctionSamples::ProfileIsCS
)
2073 for (const std::pair
<Function
*, NotInlinedProfileInfo
> &pair
:
2075 updateProfileCallee(pair
.first
, pair
.second
.entryCount
);
2080 bool SampleProfileLoader::runOnFunction(Function
&F
, ModuleAnalysisManager
*AM
) {
2081 LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F
.getName() << "\n");
2082 DILocation2SampleMap
.clear();
2083 // By default the entry count is initialized to -1, which will be treated
2084 // conservatively by getEntryCount as the same as unknown (None). This is
2085 // to avoid newly added code to be treated as cold. If we have samples
2086 // this will be overwritten in emitAnnotations.
2087 uint64_t initialEntryCount
= -1;
2089 ProfAccForSymsInList
= ProfileAccurateForSymsInList
&& PSL
;
2090 if (ProfileSampleAccurate
|| F
.hasFnAttribute("profile-sample-accurate")) {
2091 // initialize all the function entry counts to 0. It means all the
2092 // functions without profile will be regarded as cold.
2093 initialEntryCount
= 0;
2094 // profile-sample-accurate is a user assertion which has a higher precedence
2095 // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2096 ProfAccForSymsInList
= false;
2098 CoverageTracker
.setProfAccForSymsInList(ProfAccForSymsInList
);
2100 // PSL -- profile symbol list include all the symbols in sampled binary.
2101 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2102 // old functions without samples being cold, without having to worry
2103 // about new and hot functions being mistakenly treated as cold.
2104 if (ProfAccForSymsInList
) {
2105 // Initialize the entry count to 0 for functions in the list.
2106 if (PSL
->contains(F
.getName()))
2107 initialEntryCount
= 0;
2109 // Function in the symbol list but without sample will be regarded as
2110 // cold. To minimize the potential negative performance impact it could
2111 // have, we want to be a little conservative here saying if a function
2112 // shows up in the profile, no matter as outline function, inline instance
2113 // or call targets, treat the function as not being cold. This will handle
2114 // the cases such as most callsites of a function are inlined in sampled
2115 // binary but not inlined in current build (because of source code drift,
2116 // imprecise debug information, or the callsites are all cold individually
2117 // but not cold accumulatively...), so the outline function showing up as
2118 // cold in sampled binary will actually not be cold after current build.
2119 StringRef CanonName
= FunctionSamples::getCanonicalFnName(F
);
2120 if (NamesInProfile
.count(CanonName
))
2121 initialEntryCount
= -1;
2124 // Initialize entry count when the function has no existing entry
2126 if (!F
.getEntryCount())
2127 F
.setEntryCount(ProfileCount(initialEntryCount
, Function::PCT_Real
));
2128 std::unique_ptr
<OptimizationRemarkEmitter
> OwnedORE
;
2131 AM
->getResult
<FunctionAnalysisManagerModuleProxy
>(*F
.getParent())
2133 ORE
= &FAM
.getResult
<OptimizationRemarkEmitterAnalysis
>(F
);
2135 OwnedORE
= std::make_unique
<OptimizationRemarkEmitter
>(&F
);
2136 ORE
= OwnedORE
.get();
2139 if (FunctionSamples::ProfileIsCS
)
2140 Samples
= ContextTracker
->getBaseSamplesFor(F
);
2142 Samples
= Reader
->getSamplesFor(F
);
2144 if (Samples
&& !Samples
->empty())
2145 return emitAnnotations(F
);
2149 PreservedAnalyses
SampleProfileLoaderPass::run(Module
&M
,
2150 ModuleAnalysisManager
&AM
) {
2151 FunctionAnalysisManager
&FAM
=
2152 AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
2154 auto GetAssumptionCache
= [&](Function
&F
) -> AssumptionCache
& {
2155 return FAM
.getResult
<AssumptionAnalysis
>(F
);
2157 auto GetTTI
= [&](Function
&F
) -> TargetTransformInfo
& {
2158 return FAM
.getResult
<TargetIRAnalysis
>(F
);
2160 auto GetTLI
= [&](Function
&F
) -> const TargetLibraryInfo
& {
2161 return FAM
.getResult
<TargetLibraryAnalysis
>(F
);
2164 SampleProfileLoader
SampleLoader(
2165 ProfileFileName
.empty() ? SampleProfileFile
: ProfileFileName
,
2166 ProfileRemappingFileName
.empty() ? SampleProfileRemappingFile
2167 : ProfileRemappingFileName
,
2168 LTOPhase
, GetAssumptionCache
, GetTTI
, GetTLI
);
2170 if (!SampleLoader
.doInitialization(M
, &FAM
))
2171 return PreservedAnalyses::all();
2173 ProfileSummaryInfo
*PSI
= &AM
.getResult
<ProfileSummaryAnalysis
>(M
);
2174 CallGraph
&CG
= AM
.getResult
<CallGraphAnalysis
>(M
);
2175 if (!SampleLoader
.runOnModule(M
, &AM
, PSI
, &CG
))
2176 return PreservedAnalyses::all();
2178 return PreservedAnalyses::none();