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/InlineAdvisor.h"
39 #include "llvm/Analysis/InlineCost.h"
40 #include "llvm/Analysis/LazyCallGraph.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/ProfDataUtils.h"
60 #include "llvm/IR/PseudoProbe.h"
61 #include "llvm/IR/ValueSymbolTable.h"
62 #include "llvm/ProfileData/InstrProf.h"
63 #include "llvm/ProfileData/SampleProf.h"
64 #include "llvm/ProfileData/SampleProfReader.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/ErrorOr.h"
69 #include "llvm/Support/VirtualFileSystem.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/SampleProfileMatcher.h"
75 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
76 #include "llvm/Transforms/Instrumentation.h"
77 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
78 #include "llvm/Transforms/Utils/Cloning.h"
79 #include "llvm/Transforms/Utils/MisExpect.h"
80 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
81 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
91 #include <system_error>
96 using namespace sampleprof
;
97 using namespace llvm::sampleprofutil
;
98 using ProfileCount
= Function::ProfileCount
;
99 #define DEBUG_TYPE "sample-profile"
100 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
102 STATISTIC(NumCSInlined
,
103 "Number of functions inlined with context sensitive profile");
104 STATISTIC(NumCSNotInlined
,
105 "Number of functions not inlined with context sensitive profile");
106 STATISTIC(NumMismatchedProfile
,
107 "Number of functions with CFG mismatched profile");
108 STATISTIC(NumMatchedProfile
, "Number of functions with CFG matched profile");
109 STATISTIC(NumDuplicatedInlinesite
,
110 "Number of inlined callsites with a partial distribution factor");
112 STATISTIC(NumCSInlinedHitMinLimit
,
113 "Number of functions with FDO inline stopped due to min size limit");
114 STATISTIC(NumCSInlinedHitMaxLimit
,
115 "Number of functions with FDO inline stopped due to max size limit");
117 NumCSInlinedHitGrowthLimit
,
118 "Number of functions with FDO inline stopped due to growth size limit");
120 // Command line option to specify the file to read samples from. This is
121 // mainly used for debugging.
122 static cl::opt
<std::string
> SampleProfileFile(
123 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
124 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden
);
126 // The named file contains a set of transformations that may have been applied
127 // to the symbol names between the program from which the sample data was
128 // collected and the current program's symbols.
129 static cl::opt
<std::string
> SampleProfileRemappingFile(
130 "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
131 cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden
);
133 cl::opt
<bool> SalvageStaleProfile(
134 "salvage-stale-profile", cl::Hidden
, cl::init(false),
135 cl::desc("Salvage stale profile by fuzzy matching and use the remapped "
136 "location for sample profile query."));
138 cl::opt
<bool> ReportProfileStaleness(
139 "report-profile-staleness", cl::Hidden
, cl::init(false),
140 cl::desc("Compute and report stale profile statistical metrics."));
142 cl::opt
<bool> PersistProfileStaleness(
143 "persist-profile-staleness", cl::Hidden
, cl::init(false),
144 cl::desc("Compute stale profile statistical metrics and write it into the "
145 "native object file(.llvm_stats section)."));
147 static cl::opt
<bool> ProfileSampleAccurate(
148 "profile-sample-accurate", cl::Hidden
, cl::init(false),
149 cl::desc("If the sample profile is accurate, we will mark all un-sampled "
150 "callsite and function as having 0 samples. Otherwise, treat "
151 "un-sampled callsites and functions conservatively as unknown. "));
153 static cl::opt
<bool> ProfileSampleBlockAccurate(
154 "profile-sample-block-accurate", cl::Hidden
, cl::init(false),
155 cl::desc("If the sample profile is accurate, we will mark all un-sampled "
156 "branches and calls as having 0 samples. Otherwise, treat "
157 "them conservatively as unknown. "));
159 static cl::opt
<bool> ProfileAccurateForSymsInList(
160 "profile-accurate-for-symsinlist", cl::Hidden
, cl::init(true),
161 cl::desc("For symbols in profile symbol list, regard their profiles to "
162 "be accurate. It may be overriden by profile-sample-accurate. "));
164 static cl::opt
<bool> ProfileMergeInlinee(
165 "sample-profile-merge-inlinee", cl::Hidden
, cl::init(true),
166 cl::desc("Merge past inlinee's profile to outline version if sample "
167 "profile loader decided not to inline a call site. It will "
168 "only be enabled when top-down order of profile loading is "
171 static cl::opt
<bool> ProfileTopDownLoad(
172 "sample-profile-top-down-load", cl::Hidden
, cl::init(true),
173 cl::desc("Do profile annotation and inlining for functions in top-down "
174 "order of call graph during sample profile loading. It only "
175 "works for new pass manager. "));
178 UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden
,
179 cl::desc("Process functions in a top-down order "
180 "defined by the profiled call graph when "
181 "-sample-profile-top-down-load is on."));
183 static cl::opt
<bool> ProfileSizeInline(
184 "sample-profile-inline-size", cl::Hidden
, cl::init(false),
185 cl::desc("Inline cold call sites in profile loader if it's beneficial "
188 // Since profiles are consumed by many passes, turning on this option has
189 // side effects. For instance, pre-link SCC inliner would see merged profiles
190 // and inline the hot functions (that are skipped in this pass).
191 static cl::opt
<bool> DisableSampleLoaderInlining(
192 "disable-sample-loader-inlining", cl::Hidden
, cl::init(false),
193 cl::desc("If true, artifically skip inline transformation in sample-loader "
194 "pass, and merge (or scale) profiles (as configured by "
195 "--sample-profile-merge-inlinee)."));
199 SortProfiledSCC("sort-profiled-scc-member", cl::init(true), cl::Hidden
,
200 cl::desc("Sort profiled recursion by edge weights."));
202 cl::opt
<int> ProfileInlineGrowthLimit(
203 "sample-profile-inline-growth-limit", cl::Hidden
, cl::init(12),
204 cl::desc("The size growth ratio limit for proirity-based sample profile "
205 "loader inlining."));
207 cl::opt
<int> ProfileInlineLimitMin(
208 "sample-profile-inline-limit-min", cl::Hidden
, cl::init(100),
209 cl::desc("The lower bound of size growth limit for "
210 "proirity-based sample profile loader inlining."));
212 cl::opt
<int> ProfileInlineLimitMax(
213 "sample-profile-inline-limit-max", cl::Hidden
, cl::init(10000),
214 cl::desc("The upper bound of size growth limit for "
215 "proirity-based sample profile loader inlining."));
217 cl::opt
<int> SampleHotCallSiteThreshold(
218 "sample-profile-hot-inline-threshold", cl::Hidden
, cl::init(3000),
219 cl::desc("Hot callsite threshold for proirity-based sample profile loader "
222 cl::opt
<int> SampleColdCallSiteThreshold(
223 "sample-profile-cold-inline-threshold", cl::Hidden
, cl::init(45),
224 cl::desc("Threshold for inlining cold callsites"));
227 static cl::opt
<unsigned> ProfileICPRelativeHotness(
228 "sample-profile-icp-relative-hotness", cl::Hidden
, cl::init(25),
230 "Relative hotness percentage threshold for indirect "
231 "call promotion in proirity-based sample profile loader inlining."));
233 static cl::opt
<unsigned> ProfileICPRelativeHotnessSkip(
234 "sample-profile-icp-relative-hotness-skip", cl::Hidden
, cl::init(1),
236 "Skip relative hotness check for ICP up to given number of targets."));
238 static cl::opt
<unsigned> HotFuncCutoffForStalenessError(
239 "hot-func-cutoff-for-staleness-error", cl::Hidden
, cl::init(800000),
240 cl::desc("A function is considered hot for staleness error check if its "
241 "total sample count is above the specified percentile"));
243 static cl::opt
<unsigned> MinfuncsForStalenessError(
244 "min-functions-for-staleness-error", cl::Hidden
, cl::init(50),
245 cl::desc("Skip the check if the number of hot functions is smaller than "
246 "the specified number."));
248 static cl::opt
<unsigned> PrecentMismatchForStalenessError(
249 "precent-mismatch-for-staleness-error", cl::Hidden
, cl::init(80),
250 cl::desc("Reject the profile if the mismatch percent is higher than the "
253 static cl::opt
<bool> CallsitePrioritizedInline(
254 "sample-profile-prioritized-inline", cl::Hidden
,
255 cl::desc("Use call site prioritized inlining for sample profile loader."
256 "Currently only CSSPGO is supported."));
258 static cl::opt
<bool> UsePreInlinerDecision(
259 "sample-profile-use-preinliner", cl::Hidden
,
260 cl::desc("Use the preinliner decisions stored in profile context."));
262 static cl::opt
<bool> AllowRecursiveInline(
263 "sample-profile-recursive-inline", cl::Hidden
,
264 cl::desc("Allow sample loader inliner to inline recursive calls."));
266 static cl::opt
<bool> RemoveProbeAfterProfileAnnotation(
267 "sample-profile-remove-probe", cl::Hidden
, cl::init(false),
268 cl::desc("Remove pseudo-probe after sample profile annotation."));
270 static cl::opt
<std::string
> ProfileInlineReplayFile(
271 "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
273 "Optimization remarks file containing inline remarks to be replayed "
274 "by inlining from sample profile loader."),
277 static cl::opt
<ReplayInlinerSettings::Scope
> ProfileInlineReplayScope(
278 "sample-profile-inline-replay-scope",
279 cl::init(ReplayInlinerSettings::Scope::Function
),
280 cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function
, "Function",
281 "Replay on functions that have remarks associated "
282 "with them (default)"),
283 clEnumValN(ReplayInlinerSettings::Scope::Module
, "Module",
284 "Replay on the entire module")),
285 cl::desc("Whether inline replay should be applied to the entire "
286 "Module or just the Functions (default) that are present as "
287 "callers in remarks during sample profile inlining."),
290 static cl::opt
<ReplayInlinerSettings::Fallback
> ProfileInlineReplayFallback(
291 "sample-profile-inline-replay-fallback",
292 cl::init(ReplayInlinerSettings::Fallback::Original
),
295 ReplayInlinerSettings::Fallback::Original
, "Original",
296 "All decisions not in replay send to original advisor (default)"),
297 clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline
,
298 "AlwaysInline", "All decisions not in replay are inlined"),
299 clEnumValN(ReplayInlinerSettings::Fallback::NeverInline
, "NeverInline",
300 "All decisions not in replay are not inlined")),
301 cl::desc("How sample profile inline replay treats sites that don't come "
302 "from the replay. Original: defers to original advisor, "
303 "AlwaysInline: inline all sites not in replay, NeverInline: "
304 "inline no sites not in replay"),
307 static cl::opt
<CallSiteFormat::Format
> ProfileInlineReplayFormat(
308 "sample-profile-inline-replay-format",
309 cl::init(CallSiteFormat::Format::LineColumnDiscriminator
),
311 clEnumValN(CallSiteFormat::Format::Line
, "Line", "<Line Number>"),
312 clEnumValN(CallSiteFormat::Format::LineColumn
, "LineColumn",
313 "<Line Number>:<Column Number>"),
314 clEnumValN(CallSiteFormat::Format::LineDiscriminator
,
315 "LineDiscriminator", "<Line Number>.<Discriminator>"),
316 clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator
,
317 "LineColumnDiscriminator",
318 "<Line Number>:<Column Number>.<Discriminator> (default)")),
319 cl::desc("How sample profile inline replay file is formatted"), cl::Hidden
);
321 static cl::opt
<unsigned>
322 MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden
,
323 cl::desc("Max number of promotions for a single indirect "
324 "call callsite in sample profile loader"));
326 static cl::opt
<bool> OverwriteExistingWeights(
327 "overwrite-existing-weights", cl::Hidden
, cl::init(false),
328 cl::desc("Ignore existing branch weights on IR and always overwrite."));
330 static cl::opt
<bool> AnnotateSampleProfileInlinePhase(
331 "annotate-sample-profile-inline-phase", cl::Hidden
, cl::init(false),
332 cl::desc("Annotate LTO phase (prelink / postlink), or main (no LTO) for "
333 "sample-profile inline pass name."));
336 extern cl::opt
<bool> EnableExtTspBlockPlacement
;
341 using BlockWeightMap
= DenseMap
<const BasicBlock
*, uint64_t>;
342 using EquivalenceClassMap
= DenseMap
<const BasicBlock
*, const BasicBlock
*>;
343 using Edge
= std::pair
<const BasicBlock
*, const BasicBlock
*>;
344 using EdgeWeightMap
= DenseMap
<Edge
, uint64_t>;
346 DenseMap
<const BasicBlock
*, SmallVector
<const BasicBlock
*, 8>>;
348 class GUIDToFuncNameMapper
{
350 GUIDToFuncNameMapper(Module
&M
, SampleProfileReader
&Reader
,
351 DenseMap
<uint64_t, StringRef
> &GUIDToFuncNameMap
)
352 : CurrentReader(Reader
), CurrentModule(M
),
353 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap
) {
354 if (!CurrentReader
.useMD5())
357 for (const auto &F
: CurrentModule
) {
358 StringRef OrigName
= F
.getName();
359 CurrentGUIDToFuncNameMap
.insert(
360 {Function::getGUID(OrigName
), OrigName
});
362 // Local to global var promotion used by optimization like thinlto
363 // will rename the var and add suffix like ".llvm.xxx" to the
364 // original local name. In sample profile, the suffixes of function
365 // names are all stripped. Since it is possible that the mapper is
366 // built in post-thin-link phase and var promotion has been done,
367 // we need to add the substring of function name without the suffix
368 // into the GUIDToFuncNameMap.
369 StringRef CanonName
= FunctionSamples::getCanonicalFnName(F
);
370 if (CanonName
!= OrigName
)
371 CurrentGUIDToFuncNameMap
.insert(
372 {Function::getGUID(CanonName
), CanonName
});
375 // Update GUIDToFuncNameMap for each function including inlinees.
376 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap
);
379 ~GUIDToFuncNameMapper() {
380 if (!CurrentReader
.useMD5())
383 CurrentGUIDToFuncNameMap
.clear();
385 // Reset GUIDToFuncNameMap for of each function as they're no
386 // longer valid at this point.
387 SetGUIDToFuncNameMapForAll(nullptr);
391 void SetGUIDToFuncNameMapForAll(DenseMap
<uint64_t, StringRef
> *Map
) {
392 std::queue
<FunctionSamples
*> FSToUpdate
;
393 for (auto &IFS
: CurrentReader
.getProfiles()) {
394 FSToUpdate
.push(&IFS
.second
);
397 while (!FSToUpdate
.empty()) {
398 FunctionSamples
*FS
= FSToUpdate
.front();
400 FS
->GUIDToFuncNameMap
= Map
;
401 for (const auto &ICS
: FS
->getCallsiteSamples()) {
402 const FunctionSamplesMap
&FSMap
= ICS
.second
;
403 for (const auto &IFS
: FSMap
) {
404 FunctionSamples
&FS
= const_cast<FunctionSamples
&>(IFS
.second
);
405 FSToUpdate
.push(&FS
);
411 SampleProfileReader
&CurrentReader
;
412 Module
&CurrentModule
;
413 DenseMap
<uint64_t, StringRef
> &CurrentGUIDToFuncNameMap
;
416 // Inline candidate used by iterative callsite prioritized inliner
417 struct InlineCandidate
{
419 const FunctionSamples
*CalleeSamples
;
420 // Prorated callsite count, which will be used to guide inlining. For example,
421 // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
422 // copies will get their own distribution factors and their prorated counts
423 // will be used to decide if they should be inlined independently.
424 uint64_t CallsiteCount
;
425 // Call site distribution factor to prorate the profile samples for a
426 // duplicated callsite. Default value is 1.0.
427 float CallsiteDistribution
;
430 // Inline candidate comparer using call site weight
431 struct CandidateComparer
{
432 bool operator()(const InlineCandidate
&LHS
, const InlineCandidate
&RHS
) {
433 if (LHS
.CallsiteCount
!= RHS
.CallsiteCount
)
434 return LHS
.CallsiteCount
< RHS
.CallsiteCount
;
436 const FunctionSamples
*LCS
= LHS
.CalleeSamples
;
437 const FunctionSamples
*RCS
= RHS
.CalleeSamples
;
438 assert(LCS
&& RCS
&& "Expect non-null FunctionSamples");
440 // Tie breaker using number of samples try to favor smaller functions first
441 if (LCS
->getBodySamples().size() != RCS
->getBodySamples().size())
442 return LCS
->getBodySamples().size() > RCS
->getBodySamples().size();
444 // Tie breaker using GUID so we have stable/deterministic inlining order
445 return LCS
->getGUID() < RCS
->getGUID();
449 using CandidateQueue
=
450 PriorityQueue
<InlineCandidate
, std::vector
<InlineCandidate
>,
453 /// Sample profile pass.
455 /// This pass reads profile data from the file specified by
456 /// -sample-profile-file and annotates every affected function with the
457 /// profile information found in that file.
458 class SampleProfileLoader final
: public SampleProfileLoaderBaseImpl
<Function
> {
461 StringRef Name
, StringRef RemapName
, ThinOrFullLTOPhase LTOPhase
,
462 IntrusiveRefCntPtr
<vfs::FileSystem
> FS
,
463 std::function
<AssumptionCache
&(Function
&)> GetAssumptionCache
,
464 std::function
<TargetTransformInfo
&(Function
&)> GetTargetTransformInfo
,
465 std::function
<const TargetLibraryInfo
&(Function
&)> GetTLI
)
466 : SampleProfileLoaderBaseImpl(std::string(Name
), std::string(RemapName
),
468 GetAC(std::move(GetAssumptionCache
)),
469 GetTTI(std::move(GetTargetTransformInfo
)), GetTLI(std::move(GetTLI
)),
471 AnnotatedPassName(AnnotateSampleProfileInlinePhase
472 ? llvm::AnnotateInlinePassName(InlineContext
{
473 LTOPhase
, InlinePass::SampleProfileInliner
})
476 bool doInitialization(Module
&M
, FunctionAnalysisManager
*FAM
= nullptr);
477 bool runOnModule(Module
&M
, ModuleAnalysisManager
*AM
,
478 ProfileSummaryInfo
*_PSI
, LazyCallGraph
&CG
);
481 bool runOnFunction(Function
&F
, ModuleAnalysisManager
*AM
);
482 bool emitAnnotations(Function
&F
);
483 ErrorOr
<uint64_t> getInstWeight(const Instruction
&I
) override
;
484 const FunctionSamples
*findCalleeFunctionSamples(const CallBase
&I
) const;
485 const FunctionSamples
*
486 findFunctionSamples(const Instruction
&I
) const override
;
487 std::vector
<const FunctionSamples
*>
488 findIndirectCallFunctionSamples(const Instruction
&I
, uint64_t &Sum
) const;
489 void findExternalInlineCandidate(CallBase
*CB
, const FunctionSamples
*Samples
,
490 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
,
492 // Attempt to promote indirect call and also inline the promoted call
493 bool tryPromoteAndInlineCandidate(
494 Function
&F
, InlineCandidate
&Candidate
, uint64_t SumOrigin
,
495 uint64_t &Sum
, SmallVector
<CallBase
*, 8> *InlinedCallSites
= nullptr);
497 bool inlineHotFunctions(Function
&F
,
498 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
);
499 std::optional
<InlineCost
> getExternalInlineAdvisorCost(CallBase
&CB
);
500 bool getExternalInlineAdvisorShouldInline(CallBase
&CB
);
501 InlineCost
shouldInlineCandidate(InlineCandidate
&Candidate
);
502 bool getInlineCandidate(InlineCandidate
*NewCandidate
, CallBase
*CB
);
504 tryInlineCandidate(InlineCandidate
&Candidate
,
505 SmallVector
<CallBase
*, 8> *InlinedCallSites
= nullptr);
507 inlineHotFunctionsWithPriority(Function
&F
,
508 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
);
509 // Inline cold/small functions in addition to hot ones
510 bool shouldInlineColdCallee(CallBase
&CallInst
);
511 void emitOptimizationRemarksForInlineCandidates(
512 const SmallVectorImpl
<CallBase
*> &Candidates
, const Function
&F
,
514 void promoteMergeNotInlinedContextSamples(
515 MapVector
<CallBase
*, const FunctionSamples
*> NonInlinedCallSites
,
517 std::vector
<Function
*> buildFunctionOrder(Module
&M
, LazyCallGraph
&CG
);
518 std::unique_ptr
<ProfiledCallGraph
> buildProfiledCallGraph(Module
&M
);
519 void generateMDProfMetadata(Function
&F
);
520 bool rejectHighStalenessProfile(Module
&M
, ProfileSummaryInfo
*PSI
,
521 const SampleProfileMap
&Profiles
);
522 void removePseudoProbeInsts(Module
&M
);
524 /// Map from function name to Function *. Used to find the function from
525 /// the function name. If the function name contains suffix, additional
526 /// entry is added to map from the stripped name to the function if there
527 /// is one-to-one mapping.
528 HashKeyMap
<std::unordered_map
, FunctionId
, Function
*> SymbolMap
;
530 std::function
<AssumptionCache
&(Function
&)> GetAC
;
531 std::function
<TargetTransformInfo
&(Function
&)> GetTTI
;
532 std::function
<const TargetLibraryInfo
&(Function
&)> GetTLI
;
534 /// Profile tracker for different context.
535 std::unique_ptr
<SampleContextTracker
> ContextTracker
;
537 /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
539 /// We need to know the LTO phase because for example in ThinLTOPrelink
540 /// phase, in annotation, we should not promote indirect calls. Instead,
541 /// we will mark GUIDs that needs to be annotated to the function.
542 const ThinOrFullLTOPhase LTOPhase
;
543 const std::string AnnotatedPassName
;
545 /// Profle Symbol list tells whether a function name appears in the binary
546 /// used to generate the current profile.
547 std::unique_ptr
<ProfileSymbolList
> PSL
;
549 /// Total number of samples collected in this profile.
551 /// This is the sum of all the samples collected in all the functions executed
553 uint64_t TotalCollectedSamples
= 0;
555 // Information recorded when we declined to inline a call site
556 // because we have determined it is too cold is accumulated for
557 // each callee function. Initially this is just the entry count.
558 struct NotInlinedProfileInfo
{
561 DenseMap
<Function
*, NotInlinedProfileInfo
> notInlinedCallInfo
;
563 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
564 // all the function symbols defined or declared in current module.
565 DenseMap
<uint64_t, StringRef
> GUIDToFuncNameMap
;
567 // All the Names used in FunctionSamples including outline function
568 // names, inline instance names and call target names.
569 StringSet
<> NamesInProfile
;
570 // MD5 version of NamesInProfile. Either NamesInProfile or GUIDsInProfile is
571 // populated, depends on whether the profile uses MD5. Because the name table
572 // generally contains several magnitude more entries than the number of
573 // functions, we do not want to convert all names from one form to another.
574 llvm::DenseSet
<uint64_t> GUIDsInProfile
;
576 // For symbol in profile symbol list, whether to regard their profiles
577 // to be accurate. It is mainly decided by existance of profile symbol
578 // list and -profile-accurate-for-symsinlist flag, but it can be
579 // overriden by -profile-sample-accurate or profile-sample-accurate
581 bool ProfAccForSymsInList
;
583 // External inline advisor used to replay inline decision from remarks.
584 std::unique_ptr
<InlineAdvisor
> ExternalInlineAdvisor
;
586 // A helper to implement the sample profile matching algorithm.
587 std::unique_ptr
<SampleProfileMatcher
> MatchingManager
;
590 const char *getAnnotatedRemarkPassName() const {
591 return AnnotatedPassName
.c_str();
594 } // end anonymous namespace
598 inline bool SampleProfileInference
<Function
>::isExit(const BasicBlock
*BB
) {
599 return succ_empty(BB
);
603 inline void SampleProfileInference
<Function
>::findUnlikelyJumps(
604 const std::vector
<const BasicBlockT
*> &BasicBlocks
,
605 BlockEdgeMap
&Successors
, FlowFunction
&Func
) {
606 for (auto &Jump
: Func
.Jumps
) {
607 const auto *BB
= BasicBlocks
[Jump
.Source
];
608 const auto *Succ
= BasicBlocks
[Jump
.Target
];
609 const Instruction
*TI
= BB
->getTerminator();
610 // Check if a block ends with InvokeInst and mark non-taken branch unlikely.
611 // In that case block Succ should be a landing pad
612 if (Successors
[BB
].size() == 2 && Successors
[BB
].back() == Succ
) {
613 if (isa
<InvokeInst
>(TI
)) {
614 Jump
.IsUnlikely
= true;
617 const Instruction
*SuccTI
= Succ
->getTerminator();
618 // Check if the target block contains UnreachableInst and mark it unlikely
619 if (SuccTI
->getNumSuccessors() == 0) {
620 if (isa
<UnreachableInst
>(SuccTI
)) {
621 Jump
.IsUnlikely
= true;
628 void SampleProfileLoaderBaseImpl
<Function
>::computeDominanceAndLoopInfo(
630 DT
.reset(new DominatorTree
);
633 PDT
.reset(new PostDominatorTree(F
));
635 LI
.reset(new LoopInfo
);
640 ErrorOr
<uint64_t> SampleProfileLoader::getInstWeight(const Instruction
&Inst
) {
641 if (FunctionSamples::ProfileIsProbeBased
)
642 return getProbeWeight(Inst
);
644 const DebugLoc
&DLoc
= Inst
.getDebugLoc();
646 return std::error_code();
648 // Ignore all intrinsics, phinodes and branch instructions.
649 // Branch and phinodes instruction usually contains debug info from sources
650 // outside of the residing basic block, thus we ignore them during annotation.
651 if (isa
<BranchInst
>(Inst
) || isa
<IntrinsicInst
>(Inst
) || isa
<PHINode
>(Inst
))
652 return std::error_code();
654 // For non-CS profile, if a direct call/invoke instruction is inlined in
655 // profile (findCalleeFunctionSamples returns non-empty result), but not
656 // inlined here, it means that the inlined callsite has no sample, thus the
657 // call instruction should have 0 count.
658 // For CS profile, the callsite count of previously inlined callees is
659 // populated with the entry count of the callees.
660 if (!FunctionSamples::ProfileIsCS
)
661 if (const auto *CB
= dyn_cast
<CallBase
>(&Inst
))
662 if (!CB
->isIndirectCall() && findCalleeFunctionSamples(*CB
))
665 return getInstWeightImpl(Inst
);
668 /// Get the FunctionSamples for a call instruction.
670 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
671 /// instance in which that call instruction is calling to. It contains
672 /// all samples that resides in the inlined instance. We first find the
673 /// inlined instance in which the call instruction is from, then we
674 /// traverse its children to find the callsite with the matching
677 /// \param Inst Call/Invoke instruction to query.
679 /// \returns The FunctionSamples pointer to the inlined instance.
680 const FunctionSamples
*
681 SampleProfileLoader::findCalleeFunctionSamples(const CallBase
&Inst
) const {
682 const DILocation
*DIL
= Inst
.getDebugLoc();
687 StringRef CalleeName
;
688 if (Function
*Callee
= Inst
.getCalledFunction())
689 CalleeName
= Callee
->getName();
691 if (FunctionSamples::ProfileIsCS
)
692 return ContextTracker
->getCalleeContextSamplesFor(Inst
, CalleeName
);
694 const FunctionSamples
*FS
= findFunctionSamples(Inst
);
698 return FS
->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL
),
699 CalleeName
, Reader
->getRemapper());
702 /// Returns a vector of FunctionSamples that are the indirect call targets
703 /// of \p Inst. The vector is sorted by the total number of samples. Stores
704 /// the total call count of the indirect call in \p Sum.
705 std::vector
<const FunctionSamples
*>
706 SampleProfileLoader::findIndirectCallFunctionSamples(
707 const Instruction
&Inst
, uint64_t &Sum
) const {
708 const DILocation
*DIL
= Inst
.getDebugLoc();
709 std::vector
<const FunctionSamples
*> R
;
715 auto FSCompare
= [](const FunctionSamples
*L
, const FunctionSamples
*R
) {
716 assert(L
&& R
&& "Expect non-null FunctionSamples");
717 if (L
->getHeadSamplesEstimate() != R
->getHeadSamplesEstimate())
718 return L
->getHeadSamplesEstimate() > R
->getHeadSamplesEstimate();
719 return L
->getGUID() < R
->getGUID();
722 if (FunctionSamples::ProfileIsCS
) {
724 ContextTracker
->getIndirectCalleeContextSamplesFor(DIL
);
725 if (CalleeSamples
.empty())
728 // For CSSPGO, we only use target context profile's entry count
729 // as that already includes both inlined callee and non-inlined ones..
731 for (const auto *const FS
: CalleeSamples
) {
732 Sum
+= FS
->getHeadSamplesEstimate();
735 llvm::sort(R
, FSCompare
);
739 const FunctionSamples
*FS
= findFunctionSamples(Inst
);
743 auto CallSite
= FunctionSamples::getCallSiteIdentifier(DIL
);
745 if (auto T
= FS
->findCallTargetMapAt(CallSite
))
746 for (const auto &T_C
: *T
)
748 if (const FunctionSamplesMap
*M
= FS
->findFunctionSamplesMapAt(CallSite
)) {
751 for (const auto &NameFS
: *M
) {
752 Sum
+= NameFS
.second
.getHeadSamplesEstimate();
753 R
.push_back(&NameFS
.second
);
755 llvm::sort(R
, FSCompare
);
760 const FunctionSamples
*
761 SampleProfileLoader::findFunctionSamples(const Instruction
&Inst
) const {
762 if (FunctionSamples::ProfileIsProbeBased
) {
763 std::optional
<PseudoProbe
> Probe
= extractProbe(Inst
);
768 const DILocation
*DIL
= Inst
.getDebugLoc();
772 auto it
= DILocation2SampleMap
.try_emplace(DIL
,nullptr);
774 if (FunctionSamples::ProfileIsCS
)
775 it
.first
->second
= ContextTracker
->getContextSamplesFor(DIL
);
778 Samples
->findFunctionSamples(DIL
, Reader
->getRemapper());
780 return it
.first
->second
;
783 /// Check whether the indirect call promotion history of \p Inst allows
784 /// the promotion for \p Candidate.
785 /// If the profile count for the promotion candidate \p Candidate is
786 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
787 /// for \p Inst. If we already have at least MaxNumPromotions
788 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
789 /// cannot promote for \p Inst anymore.
790 static bool doesHistoryAllowICP(const Instruction
&Inst
, StringRef Candidate
) {
791 uint32_t NumVals
= 0;
792 uint64_t TotalCount
= 0;
793 std::unique_ptr
<InstrProfValueData
[]> ValueData
=
794 std::make_unique
<InstrProfValueData
[]>(MaxNumPromotions
);
796 getValueProfDataFromInst(Inst
, IPVK_IndirectCallTarget
, MaxNumPromotions
,
797 ValueData
.get(), NumVals
, TotalCount
, true);
798 // No valid value profile so no promoted targets have been recorded
799 // before. Ok to do ICP.
803 unsigned NumPromoted
= 0;
804 for (uint32_t I
= 0; I
< NumVals
; I
++) {
805 if (ValueData
[I
].Count
!= NOMORE_ICP_MAGICNUM
)
808 // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
809 // metadata, it means the candidate has been promoted for this
811 if (ValueData
[I
].Value
== Function::getGUID(Candidate
))
814 // If already have MaxNumPromotions promotion, don't do it anymore.
815 if (NumPromoted
== MaxNumPromotions
)
821 /// Update indirect call target profile metadata for \p Inst.
822 /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
823 /// If it is 0, it means updateIDTMetaData is used to mark a
824 /// certain target to be promoted already. If it is not zero,
825 /// we expect to use it to update the total count in the value profile.
827 updateIDTMetaData(Instruction
&Inst
,
828 const SmallVectorImpl
<InstrProfValueData
> &CallTargets
,
830 // Bail out early if MaxNumPromotions is zero.
831 // This prevents allocating an array of zero length below.
833 // Note `updateIDTMetaData` is called in two places so check
834 // `MaxNumPromotions` inside it.
835 if (MaxNumPromotions
== 0)
837 uint32_t NumVals
= 0;
838 // OldSum is the existing total count in the value profile data.
840 std::unique_ptr
<InstrProfValueData
[]> ValueData
=
841 std::make_unique
<InstrProfValueData
[]>(MaxNumPromotions
);
843 getValueProfDataFromInst(Inst
, IPVK_IndirectCallTarget
, MaxNumPromotions
,
844 ValueData
.get(), NumVals
, OldSum
, true);
846 DenseMap
<uint64_t, uint64_t> ValueCountMap
;
848 assert((CallTargets
.size() == 1 &&
849 CallTargets
[0].Count
== NOMORE_ICP_MAGICNUM
) &&
850 "If sum is 0, assume only one element in CallTargets "
851 "with count being NOMORE_ICP_MAGICNUM");
852 // Initialize ValueCountMap with existing value profile data.
854 for (uint32_t I
= 0; I
< NumVals
; I
++)
855 ValueCountMap
[ValueData
[I
].Value
] = ValueData
[I
].Count
;
858 ValueCountMap
.try_emplace(CallTargets
[0].Value
, CallTargets
[0].Count
);
859 // If the target already exists in value profile, decrease the total
860 // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
862 OldSum
-= Pair
.first
->second
;
863 Pair
.first
->second
= NOMORE_ICP_MAGICNUM
;
867 // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
868 // counts in the value profile.
870 for (uint32_t I
= 0; I
< NumVals
; I
++) {
871 if (ValueData
[I
].Count
== NOMORE_ICP_MAGICNUM
)
872 ValueCountMap
[ValueData
[I
].Value
] = ValueData
[I
].Count
;
876 for (const auto &Data
: CallTargets
) {
877 auto Pair
= ValueCountMap
.try_emplace(Data
.Value
, Data
.Count
);
880 // The target represented by Data.Value has already been promoted.
881 // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
882 // Sum by Data.Count.
883 assert(Sum
>= Data
.Count
&& "Sum should never be less than Data.Count");
888 SmallVector
<InstrProfValueData
, 8> NewCallTargets
;
889 for (const auto &ValueCount
: ValueCountMap
) {
890 NewCallTargets
.emplace_back(
891 InstrProfValueData
{ValueCount
.first
, ValueCount
.second
});
894 llvm::sort(NewCallTargets
,
895 [](const InstrProfValueData
&L
, const InstrProfValueData
&R
) {
896 if (L
.Count
!= R
.Count
)
897 return L
.Count
> R
.Count
;
898 return L
.Value
> R
.Value
;
901 uint32_t MaxMDCount
=
902 std::min(NewCallTargets
.size(), static_cast<size_t>(MaxNumPromotions
));
903 annotateValueSite(*Inst
.getParent()->getParent()->getParent(), Inst
,
904 NewCallTargets
, Sum
, IPVK_IndirectCallTarget
, MaxMDCount
);
907 /// Attempt to promote indirect call and also inline the promoted call.
909 /// \param F Caller function.
910 /// \param Candidate ICP and inline candidate.
911 /// \param SumOrigin Original sum of target counts for indirect call before
912 /// promoting given candidate.
913 /// \param Sum Prorated sum of remaining target counts for indirect call
914 /// after promoting given candidate.
915 /// \param InlinedCallSite Output vector for new call sites exposed after
917 bool SampleProfileLoader::tryPromoteAndInlineCandidate(
918 Function
&F
, InlineCandidate
&Candidate
, uint64_t SumOrigin
, uint64_t &Sum
,
919 SmallVector
<CallBase
*, 8> *InlinedCallSite
) {
920 // Bail out early if sample-loader inliner is disabled.
921 if (DisableSampleLoaderInlining
)
924 // Bail out early if MaxNumPromotions is zero.
925 // This prevents allocating an array of zero length in callees below.
926 if (MaxNumPromotions
== 0)
928 auto CalleeFunctionName
= Candidate
.CalleeSamples
->getFunction();
929 auto R
= SymbolMap
.find(CalleeFunctionName
);
930 if (R
== SymbolMap
.end() || !R
->second
)
933 auto &CI
= *Candidate
.CallInstr
;
934 if (!doesHistoryAllowICP(CI
, R
->second
->getName()))
937 const char *Reason
= "Callee function not available";
938 // R->getValue() != &F is to prevent promoting a recursive call.
939 // If it is a recursive call, we do not inline it as it could bloat
940 // the code exponentially. There is way to better handle this, e.g.
941 // clone the caller first, and inline the cloned caller if it is
942 // recursive. As llvm does not inline recursive calls, we will
943 // simply ignore it instead of handling it explicitly.
944 if (!R
->second
->isDeclaration() && R
->second
->getSubprogram() &&
945 R
->second
->hasFnAttribute("use-sample-profile") &&
946 R
->second
!= &F
&& isLegalToPromote(CI
, R
->second
, &Reason
)) {
947 // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
948 // in the value profile metadata so the target won't be promoted again.
949 SmallVector
<InstrProfValueData
, 1> SortedCallTargets
= {InstrProfValueData
{
950 Function::getGUID(R
->second
->getName()), NOMORE_ICP_MAGICNUM
}};
951 updateIDTMetaData(CI
, SortedCallTargets
, 0);
953 auto *DI
= &pgo::promoteIndirectCall(
954 CI
, R
->second
, Candidate
.CallsiteCount
, Sum
, false, ORE
);
956 Sum
-= Candidate
.CallsiteCount
;
957 // Do not prorate the indirect callsite distribution since the original
958 // distribution will be used to scale down non-promoted profile target
959 // counts later. By doing this we lose track of the real callsite count
960 // for the leftover indirect callsite as a trade off for accurate call
962 // TODO: Ideally we would have two separate factors, one for call site
963 // counts and one is used to prorate call target counts.
964 // Do not update the promoted direct callsite distribution at this
965 // point since the original distribution combined with the callee profile
966 // will be used to prorate callsites from the callee if inlined. Once not
967 // inlined, the direct callsite distribution should be prorated so that
968 // the it will reflect the real callsite counts.
969 Candidate
.CallInstr
= DI
;
970 if (isa
<CallInst
>(DI
) || isa
<InvokeInst
>(DI
)) {
971 bool Inlined
= tryInlineCandidate(Candidate
, InlinedCallSite
);
973 // Prorate the direct callsite distribution so that it reflects real
975 setProbeDistributionFactor(
976 *DI
, static_cast<float>(Candidate
.CallsiteCount
) / SumOrigin
);
982 LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
983 << FunctionSamples::getCanonicalFnName(
984 Candidate
.CallInstr
->getName())<< " because "
990 bool SampleProfileLoader::shouldInlineColdCallee(CallBase
&CallInst
) {
991 if (!ProfileSizeInline
)
994 Function
*Callee
= CallInst
.getCalledFunction();
995 if (Callee
== nullptr)
998 InlineCost Cost
= getInlineCost(CallInst
, getInlineParams(), GetTTI(*Callee
),
1004 if (Cost
.isAlways())
1007 return Cost
.getCost() <= SampleColdCallSiteThreshold
;
1010 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
1011 const SmallVectorImpl
<CallBase
*> &Candidates
, const Function
&F
,
1013 for (auto *I
: Candidates
) {
1014 Function
*CalledFunction
= I
->getCalledFunction();
1015 if (CalledFunction
) {
1016 ORE
->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1017 "InlineAttempt", I
->getDebugLoc(),
1019 << "previous inlining reattempted for "
1020 << (Hot
? "hotness: '" : "size: '")
1021 << ore::NV("Callee", CalledFunction
) << "' into '"
1022 << ore::NV("Caller", &F
) << "'");
1027 void SampleProfileLoader::findExternalInlineCandidate(
1028 CallBase
*CB
, const FunctionSamples
*Samples
,
1029 DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
, uint64_t Threshold
) {
1031 // If ExternalInlineAdvisor(ReplayInlineAdvisor) wants to inline an external
1032 // function make sure it's imported
1033 if (CB
&& getExternalInlineAdvisorShouldInline(*CB
)) {
1034 // Samples may not exist for replayed function, if so
1035 // just add the direct GUID and move on
1037 InlinedGUIDs
.insert(
1038 Function::getGUID(CB
->getCalledFunction()->getName()));
1041 // Otherwise, drop the threshold to import everything that we can
1045 // In some rare cases, call instruction could be changed after being pushed
1046 // into inline candidate queue, this is because earlier inlining may expose
1047 // constant propagation which can change indirect call to direct call. When
1048 // this happens, we may fail to find matching function samples for the
1049 // candidate later, even if a match was found when the candidate was enqueued.
1053 // For AutoFDO profile, retrieve candidate profiles by walking over
1054 // the nested inlinee profiles.
1055 if (!FunctionSamples::ProfileIsCS
) {
1056 // Set threshold to zero to honor pre-inliner decision.
1057 if (UsePreInlinerDecision
)
1059 Samples
->findInlinedFunctions(InlinedGUIDs
, SymbolMap
, Threshold
);
1063 ContextTrieNode
*Caller
= ContextTracker
->getContextNodeForProfile(Samples
);
1064 std::queue
<ContextTrieNode
*> CalleeList
;
1065 CalleeList
.push(Caller
);
1066 while (!CalleeList
.empty()) {
1067 ContextTrieNode
*Node
= CalleeList
.front();
1069 FunctionSamples
*CalleeSample
= Node
->getFunctionSamples();
1070 // For CSSPGO profile, retrieve candidate profile by walking over the
1071 // trie built for context profile. Note that also take call targets
1072 // even if callee doesn't have a corresponding context profile.
1076 // If pre-inliner decision is used, honor that for importing as well.
1078 UsePreInlinerDecision
&&
1079 CalleeSample
->getContext().hasAttribute(ContextShouldBeInlined
);
1080 if (!PreInline
&& CalleeSample
->getHeadSamplesEstimate() < Threshold
)
1083 Function
*Func
= SymbolMap
.lookup(CalleeSample
->getFunction());
1084 // Add to the import list only when it's defined out of module.
1085 if (!Func
|| Func
->isDeclaration())
1086 InlinedGUIDs
.insert(CalleeSample
->getGUID());
1088 // Import hot CallTargets, which may not be available in IR because full
1089 // profile annotation cannot be done until backend compilation in ThinLTO.
1090 for (const auto &BS
: CalleeSample
->getBodySamples())
1091 for (const auto &TS
: BS
.second
.getCallTargets())
1092 if (TS
.second
> Threshold
) {
1093 const Function
*Callee
= SymbolMap
.lookup(TS
.first
);
1094 if (!Callee
|| Callee
->isDeclaration())
1095 InlinedGUIDs
.insert(TS
.first
.getHashCode());
1098 // Import hot child context profile associted with callees. Note that this
1099 // may have some overlap with the call target loop above, but doing this
1100 // based child context profile again effectively allow us to use the max of
1101 // entry count and call target count to determine importing.
1102 for (auto &Child
: Node
->getAllChildContext()) {
1103 ContextTrieNode
*CalleeNode
= &Child
.second
;
1104 CalleeList
.push(CalleeNode
);
1109 /// Iteratively inline hot callsites of a function.
1111 /// Iteratively traverse all callsites of the function \p F, so as to
1112 /// find out callsites with corresponding inline instances.
1114 /// For such callsites,
1115 /// - If it is hot enough, inline the callsites and adds callsites of the callee
1116 /// into the caller. If the call is an indirect call, first promote
1117 /// it to direct call. Each indirect call is limited with a single target.
1119 /// - If a callsite is not inlined, merge the its profile to the outline
1120 /// version (if --sample-profile-merge-inlinee is true), or scale the
1121 /// counters of standalone function based on the profile of inlined
1122 /// instances (if --sample-profile-merge-inlinee is false).
1124 /// Later passes may consume the updated profiles.
1126 /// \param F function to perform iterative inlining.
1127 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1128 /// inlined in the profiled binary.
1130 /// \returns True if there is any inline happened.
1131 bool SampleProfileLoader::inlineHotFunctions(
1132 Function
&F
, DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
) {
1133 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1134 // Profile symbol list is ignored when profile-sample-accurate is on.
1135 assert((!ProfAccForSymsInList
||
1136 (!ProfileSampleAccurate
&&
1137 !F
.hasFnAttribute("profile-sample-accurate"))) &&
1138 "ProfAccForSymsInList should be false when profile-sample-accurate "
1141 MapVector
<CallBase
*, const FunctionSamples
*> LocalNotInlinedCallSites
;
1142 bool Changed
= false;
1143 bool LocalChanged
= true;
1144 while (LocalChanged
) {
1145 LocalChanged
= false;
1146 SmallVector
<CallBase
*, 10> CIS
;
1147 for (auto &BB
: F
) {
1149 SmallVector
<CallBase
*, 10> AllCandidates
;
1150 SmallVector
<CallBase
*, 10> ColdCandidates
;
1151 for (auto &I
: BB
) {
1152 const FunctionSamples
*FS
= nullptr;
1153 if (auto *CB
= dyn_cast
<CallBase
>(&I
)) {
1154 if (!isa
<IntrinsicInst
>(I
)) {
1155 if ((FS
= findCalleeFunctionSamples(*CB
))) {
1156 assert((!FunctionSamples::UseMD5
|| FS
->GUIDToFuncNameMap
) &&
1157 "GUIDToFuncNameMap has to be populated");
1158 AllCandidates
.push_back(CB
);
1159 if (FS
->getHeadSamplesEstimate() > 0 ||
1160 FunctionSamples::ProfileIsCS
)
1161 LocalNotInlinedCallSites
.insert({CB
, FS
});
1162 if (callsiteIsHot(FS
, PSI
, ProfAccForSymsInList
))
1164 else if (shouldInlineColdCallee(*CB
))
1165 ColdCandidates
.push_back(CB
);
1166 } else if (getExternalInlineAdvisorShouldInline(*CB
)) {
1167 AllCandidates
.push_back(CB
);
1172 if (Hot
|| ExternalInlineAdvisor
) {
1173 CIS
.insert(CIS
.begin(), AllCandidates
.begin(), AllCandidates
.end());
1174 emitOptimizationRemarksForInlineCandidates(AllCandidates
, F
, true);
1176 CIS
.insert(CIS
.begin(), ColdCandidates
.begin(), ColdCandidates
.end());
1177 emitOptimizationRemarksForInlineCandidates(ColdCandidates
, F
, false);
1180 for (CallBase
*I
: CIS
) {
1181 Function
*CalledFunction
= I
->getCalledFunction();
1182 InlineCandidate Candidate
= {I
, LocalNotInlinedCallSites
.lookup(I
),
1183 0 /* dummy count */,
1184 1.0 /* dummy distribution factor */};
1185 // Do not inline recursive calls.
1186 if (CalledFunction
== &F
)
1188 if (I
->isIndirectCall()) {
1190 for (const auto *FS
: findIndirectCallFunctionSamples(*I
, Sum
)) {
1191 uint64_t SumOrigin
= Sum
;
1192 if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1193 findExternalInlineCandidate(I
, FS
, InlinedGUIDs
,
1194 PSI
->getOrCompHotCountThreshold());
1197 if (!callsiteIsHot(FS
, PSI
, ProfAccForSymsInList
))
1200 Candidate
= {I
, FS
, FS
->getHeadSamplesEstimate(), 1.0};
1201 if (tryPromoteAndInlineCandidate(F
, Candidate
, SumOrigin
, Sum
)) {
1202 LocalNotInlinedCallSites
.erase(I
);
1203 LocalChanged
= true;
1206 } else if (CalledFunction
&& CalledFunction
->getSubprogram() &&
1207 !CalledFunction
->isDeclaration()) {
1208 if (tryInlineCandidate(Candidate
)) {
1209 LocalNotInlinedCallSites
.erase(I
);
1210 LocalChanged
= true;
1212 } else if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1213 findExternalInlineCandidate(I
, findCalleeFunctionSamples(*I
),
1215 PSI
->getOrCompHotCountThreshold());
1218 Changed
|= LocalChanged
;
1221 // For CS profile, profile for not inlined context will be merged when
1222 // base profile is being retrieved.
1223 if (!FunctionSamples::ProfileIsCS
)
1224 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites
, F
);
1228 bool SampleProfileLoader::tryInlineCandidate(
1229 InlineCandidate
&Candidate
, SmallVector
<CallBase
*, 8> *InlinedCallSites
) {
1230 // Do not attempt to inline a candidate if
1231 // --disable-sample-loader-inlining is true.
1232 if (DisableSampleLoaderInlining
)
1235 CallBase
&CB
= *Candidate
.CallInstr
;
1236 Function
*CalledFunction
= CB
.getCalledFunction();
1237 assert(CalledFunction
&& "Expect a callee with definition");
1238 DebugLoc DLoc
= CB
.getDebugLoc();
1239 BasicBlock
*BB
= CB
.getParent();
1241 InlineCost Cost
= shouldInlineCandidate(Candidate
);
1242 if (Cost
.isNever()) {
1243 ORE
->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1244 "InlineFail", DLoc
, BB
)
1245 << "incompatible inlining");
1252 InlineFunctionInfo
IFI(GetAC
);
1253 IFI
.UpdateProfile
= false;
1254 InlineResult IR
= InlineFunction(CB
, IFI
,
1255 /*MergeAttributes=*/true);
1256 if (!IR
.isSuccess())
1259 // The call to InlineFunction erases I, so we can't pass it here.
1260 emitInlinedIntoBasedOnCost(*ORE
, DLoc
, BB
, *CalledFunction
, *BB
->getParent(),
1261 Cost
, true, getAnnotatedRemarkPassName());
1263 // Now populate the list of newly exposed call sites.
1264 if (InlinedCallSites
) {
1265 InlinedCallSites
->clear();
1266 for (auto &I
: IFI
.InlinedCallSites
)
1267 InlinedCallSites
->push_back(I
);
1270 if (FunctionSamples::ProfileIsCS
)
1271 ContextTracker
->markContextSamplesInlined(Candidate
.CalleeSamples
);
1274 // Prorate inlined probes for a duplicated inlining callsite which probably
1275 // has a distribution less than 100%. Samples for an inlinee should be
1276 // distributed among the copies of the original callsite based on each
1277 // callsite's distribution factor for counts accuracy. Note that an inlined
1278 // probe may come with its own distribution factor if it has been duplicated
1279 // in the inlinee body. The two factor are multiplied to reflect the
1280 // aggregation of duplication.
1281 if (Candidate
.CallsiteDistribution
< 1) {
1282 for (auto &I
: IFI
.InlinedCallSites
) {
1283 if (std::optional
<PseudoProbe
> Probe
= extractProbe(*I
))
1284 setProbeDistributionFactor(*I
, Probe
->Factor
*
1285 Candidate
.CallsiteDistribution
);
1287 NumDuplicatedInlinesite
++;
1293 bool SampleProfileLoader::getInlineCandidate(InlineCandidate
*NewCandidate
,
1295 assert(CB
&& "Expect non-null call instruction");
1297 if (isa
<IntrinsicInst
>(CB
))
1300 // Find the callee's profile. For indirect call, find hottest target profile.
1301 const FunctionSamples
*CalleeSamples
= findCalleeFunctionSamples(*CB
);
1302 // If ExternalInlineAdvisor wants to inline this site, do so even
1303 // if Samples are not present.
1304 if (!CalleeSamples
&& !getExternalInlineAdvisorShouldInline(*CB
))
1308 if (std::optional
<PseudoProbe
> Probe
= extractProbe(*CB
))
1309 Factor
= Probe
->Factor
;
1311 uint64_t CallsiteCount
=
1312 CalleeSamples
? CalleeSamples
->getHeadSamplesEstimate() * Factor
: 0;
1313 *NewCandidate
= {CB
, CalleeSamples
, CallsiteCount
, Factor
};
1317 std::optional
<InlineCost
>
1318 SampleProfileLoader::getExternalInlineAdvisorCost(CallBase
&CB
) {
1319 std::unique_ptr
<InlineAdvice
> Advice
= nullptr;
1320 if (ExternalInlineAdvisor
) {
1321 Advice
= ExternalInlineAdvisor
->getAdvice(CB
);
1323 if (!Advice
->isInliningRecommended()) {
1324 Advice
->recordUnattemptedInlining();
1325 return InlineCost::getNever("not previously inlined");
1327 Advice
->recordInlining();
1328 return InlineCost::getAlways("previously inlined");
1335 bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase
&CB
) {
1336 std::optional
<InlineCost
> Cost
= getExternalInlineAdvisorCost(CB
);
1337 return Cost
? !!*Cost
: false;
1341 SampleProfileLoader::shouldInlineCandidate(InlineCandidate
&Candidate
) {
1342 if (std::optional
<InlineCost
> ReplayCost
=
1343 getExternalInlineAdvisorCost(*Candidate
.CallInstr
))
1345 // Adjust threshold based on call site hotness, only do this for callsite
1346 // prioritized inliner because otherwise cost-benefit check is done earlier.
1347 int SampleThreshold
= SampleColdCallSiteThreshold
;
1348 if (CallsitePrioritizedInline
) {
1349 if (Candidate
.CallsiteCount
> PSI
->getHotCountThreshold())
1350 SampleThreshold
= SampleHotCallSiteThreshold
;
1351 else if (!ProfileSizeInline
)
1352 return InlineCost::getNever("cold callsite");
1355 Function
*Callee
= Candidate
.CallInstr
->getCalledFunction();
1356 assert(Callee
&& "Expect a definition for inline candidate of direct call");
1358 InlineParams Params
= getInlineParams();
1359 // We will ignore the threshold from inline cost, so always get full cost.
1360 Params
.ComputeFullInlineCost
= true;
1361 Params
.AllowRecursiveCall
= AllowRecursiveInline
;
1362 // Checks if there is anything in the reachable portion of the callee at
1363 // this callsite that makes this inlining potentially illegal. Need to
1364 // set ComputeFullInlineCost, otherwise getInlineCost may return early
1365 // when cost exceeds threshold without checking all IRs in the callee.
1366 // The acutal cost does not matter because we only checks isNever() to
1367 // see if it is legal to inline the callsite.
1368 InlineCost Cost
= getInlineCost(*Candidate
.CallInstr
, Callee
, Params
,
1369 GetTTI(*Callee
), GetAC
, GetTLI
);
1371 // Honor always inline and never inline from call analyzer
1372 if (Cost
.isNever() || Cost
.isAlways())
1375 // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1376 // decisions based on hotness as well as accurate function byte sizes for
1377 // given context using function/inlinee sizes from previous build. It
1378 // stores the decision in profile, and also adjust/merge context profile
1379 // aiming at better context-sensitive post-inline profile quality, assuming
1380 // all inline decision estimates are going to be honored by compiler. Here
1381 // we replay that inline decision under `sample-profile-use-preinliner`.
1382 // Note that we don't need to handle negative decision from preinliner as
1383 // context profile for not inlined calls are merged by preinliner already.
1384 if (UsePreInlinerDecision
&& Candidate
.CalleeSamples
) {
1385 // Once two node are merged due to promotion, we're losing some context
1386 // so the original context-sensitive preinliner decision should be ignored
1387 // for SyntheticContext.
1388 SampleContext
&Context
= Candidate
.CalleeSamples
->getContext();
1389 if (!Context
.hasState(SyntheticContext
) &&
1390 Context
.hasAttribute(ContextShouldBeInlined
))
1391 return InlineCost::getAlways("preinliner");
1394 // For old FDO inliner, we inline the call site as long as cost is not
1395 // "Never". The cost-benefit check is done earlier.
1396 if (!CallsitePrioritizedInline
) {
1397 return InlineCost::get(Cost
.getCost(), INT_MAX
);
1400 // Otherwise only use the cost from call analyzer, but overwite threshold with
1401 // Sample PGO threshold.
1402 return InlineCost::get(Cost
.getCost(), SampleThreshold
);
1405 bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1406 Function
&F
, DenseSet
<GlobalValue::GUID
> &InlinedGUIDs
) {
1407 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1408 // Profile symbol list is ignored when profile-sample-accurate is on.
1409 assert((!ProfAccForSymsInList
||
1410 (!ProfileSampleAccurate
&&
1411 !F
.hasFnAttribute("profile-sample-accurate"))) &&
1412 "ProfAccForSymsInList should be false when profile-sample-accurate "
1415 // Populating worklist with initial call sites from root inliner, along
1416 // with call site weights.
1417 CandidateQueue CQueue
;
1418 InlineCandidate NewCandidate
;
1419 for (auto &BB
: F
) {
1420 for (auto &I
: BB
) {
1421 auto *CB
= dyn_cast
<CallBase
>(&I
);
1424 if (getInlineCandidate(&NewCandidate
, CB
))
1425 CQueue
.push(NewCandidate
);
1429 // Cap the size growth from profile guided inlining. This is needed even
1430 // though cost of each inline candidate already accounts for callee size,
1431 // because with top-down inlining, we can grow inliner size significantly
1432 // with large number of smaller inlinees each pass the cost check.
1433 assert(ProfileInlineLimitMax
>= ProfileInlineLimitMin
&&
1434 "Max inline size limit should not be smaller than min inline size "
1436 unsigned SizeLimit
= F
.getInstructionCount() * ProfileInlineGrowthLimit
;
1437 SizeLimit
= std::min(SizeLimit
, (unsigned)ProfileInlineLimitMax
);
1438 SizeLimit
= std::max(SizeLimit
, (unsigned)ProfileInlineLimitMin
);
1439 if (ExternalInlineAdvisor
)
1440 SizeLimit
= std::numeric_limits
<unsigned>::max();
1442 MapVector
<CallBase
*, const FunctionSamples
*> LocalNotInlinedCallSites
;
1444 // Perform iterative BFS call site prioritized inlining
1445 bool Changed
= false;
1446 while (!CQueue
.empty() && F
.getInstructionCount() < SizeLimit
) {
1447 InlineCandidate Candidate
= CQueue
.top();
1449 CallBase
*I
= Candidate
.CallInstr
;
1450 Function
*CalledFunction
= I
->getCalledFunction();
1452 if (CalledFunction
== &F
)
1454 if (I
->isIndirectCall()) {
1456 auto CalleeSamples
= findIndirectCallFunctionSamples(*I
, Sum
);
1457 uint64_t SumOrigin
= Sum
;
1458 Sum
*= Candidate
.CallsiteDistribution
;
1459 unsigned ICPCount
= 0;
1460 for (const auto *FS
: CalleeSamples
) {
1461 // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1462 if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1463 findExternalInlineCandidate(I
, FS
, InlinedGUIDs
,
1464 PSI
->getOrCompHotCountThreshold());
1467 uint64_t EntryCountDistributed
=
1468 FS
->getHeadSamplesEstimate() * Candidate
.CallsiteDistribution
;
1469 // In addition to regular inline cost check, we also need to make sure
1470 // ICP isn't introducing excessive speculative checks even if individual
1471 // target looks beneficial to promote and inline. That means we should
1472 // only do ICP when there's a small number dominant targets.
1473 if (ICPCount
>= ProfileICPRelativeHotnessSkip
&&
1474 EntryCountDistributed
* 100 < SumOrigin
* ProfileICPRelativeHotness
)
1476 // TODO: Fix CallAnalyzer to handle all indirect calls.
1477 // For indirect call, we don't run CallAnalyzer to get InlineCost
1478 // before actual inlining. This is because we could see two different
1479 // types from the same definition, which makes CallAnalyzer choke as
1480 // it's expecting matching parameter type on both caller and callee
1481 // side. See example from PR18962 for the triggering cases (the bug was
1482 // fixed, but we generate different types).
1483 if (!PSI
->isHotCount(EntryCountDistributed
))
1485 SmallVector
<CallBase
*, 8> InlinedCallSites
;
1486 // Attach function profile for promoted indirect callee, and update
1487 // call site count for the promoted inline candidate too.
1488 Candidate
= {I
, FS
, EntryCountDistributed
,
1489 Candidate
.CallsiteDistribution
};
1490 if (tryPromoteAndInlineCandidate(F
, Candidate
, SumOrigin
, Sum
,
1491 &InlinedCallSites
)) {
1492 for (auto *CB
: InlinedCallSites
) {
1493 if (getInlineCandidate(&NewCandidate
, CB
))
1494 CQueue
.emplace(NewCandidate
);
1498 } else if (!ContextTracker
) {
1499 LocalNotInlinedCallSites
.insert({I
, FS
});
1502 } else if (CalledFunction
&& CalledFunction
->getSubprogram() &&
1503 !CalledFunction
->isDeclaration()) {
1504 SmallVector
<CallBase
*, 8> InlinedCallSites
;
1505 if (tryInlineCandidate(Candidate
, &InlinedCallSites
)) {
1506 for (auto *CB
: InlinedCallSites
) {
1507 if (getInlineCandidate(&NewCandidate
, CB
))
1508 CQueue
.emplace(NewCandidate
);
1511 } else if (!ContextTracker
) {
1512 LocalNotInlinedCallSites
.insert({I
, Candidate
.CalleeSamples
});
1514 } else if (LTOPhase
== ThinOrFullLTOPhase::ThinLTOPreLink
) {
1515 findExternalInlineCandidate(I
, findCalleeFunctionSamples(*I
),
1517 PSI
->getOrCompHotCountThreshold());
1521 if (!CQueue
.empty()) {
1522 if (SizeLimit
== (unsigned)ProfileInlineLimitMax
)
1523 ++NumCSInlinedHitMaxLimit
;
1524 else if (SizeLimit
== (unsigned)ProfileInlineLimitMin
)
1525 ++NumCSInlinedHitMinLimit
;
1527 ++NumCSInlinedHitGrowthLimit
;
1530 // For CS profile, profile for not inlined context will be merged when
1531 // base profile is being retrieved.
1532 if (!FunctionSamples::ProfileIsCS
)
1533 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites
, F
);
1537 void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1538 MapVector
<CallBase
*, const FunctionSamples
*> NonInlinedCallSites
,
1539 const Function
&F
) {
1540 // Accumulate not inlined callsite information into notInlinedSamples
1541 for (const auto &Pair
: NonInlinedCallSites
) {
1542 CallBase
*I
= Pair
.first
;
1543 Function
*Callee
= I
->getCalledFunction();
1544 if (!Callee
|| Callee
->isDeclaration())
1548 OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
1549 I
->getDebugLoc(), I
->getParent())
1550 << "previous inlining not repeated: '" << ore::NV("Callee", Callee
)
1551 << "' into '" << ore::NV("Caller", &F
) << "'");
1554 const FunctionSamples
*FS
= Pair
.second
;
1555 if (FS
->getTotalSamples() == 0 && FS
->getHeadSamplesEstimate() == 0) {
1559 // Do not merge a context that is already duplicated into the base profile.
1560 if (FS
->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase
))
1563 if (ProfileMergeInlinee
) {
1564 // A function call can be replicated by optimizations like callsite
1565 // splitting or jump threading and the replicates end up sharing the
1566 // sample nested callee profile instead of slicing the original
1567 // inlinee's profile. We want to do merge exactly once by filtering out
1568 // callee profiles with a non-zero head sample count.
1569 if (FS
->getHeadSamples() == 0) {
1570 // Use entry samples as head samples during the merge, as inlinees
1571 // don't have head samples.
1572 const_cast<FunctionSamples
*>(FS
)->addHeadSamples(
1573 FS
->getHeadSamplesEstimate());
1575 // Note that we have to do the merge right after processing function.
1576 // This allows OutlineFS's profile to be used for annotation during
1577 // top-down processing of functions' annotation.
1578 FunctionSamples
*OutlineFS
= Reader
->getSamplesFor(*Callee
);
1579 // If outlined function does not exist in the profile, add it to a
1580 // separate map so that it does not rehash the original profile.
1582 OutlineFS
= &OutlineFunctionSamples
[
1583 FunctionId(FunctionSamples::getCanonicalFnName(Callee
->getName()))];
1584 OutlineFS
->merge(*FS
, 1);
1585 // Set outlined profile to be synthetic to not bias the inliner.
1586 OutlineFS
->SetContextSynthetic();
1590 notInlinedCallInfo
.try_emplace(Callee
, NotInlinedProfileInfo
{0});
1591 pair
.first
->second
.entryCount
+= FS
->getHeadSamplesEstimate();
1596 /// Returns the sorted CallTargetMap \p M by count in descending order.
1597 static SmallVector
<InstrProfValueData
, 2>
1598 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap
&M
) {
1599 SmallVector
<InstrProfValueData
, 2> R
;
1600 for (const auto &I
: SampleRecord::SortCallTargets(M
)) {
1602 InstrProfValueData
{I
.first
.getHashCode(), I
.second
});
1607 // Generate MD_prof metadata for every branch instruction using the
1608 // edge weights computed during propagation.
1609 void SampleProfileLoader::generateMDProfMetadata(Function
&F
) {
1610 // Generate MD_prof metadata for every branch instruction using the
1611 // edge weights computed during propagation.
1612 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1613 LLVMContext
&Ctx
= F
.getContext();
1615 for (auto &BI
: F
) {
1616 BasicBlock
*BB
= &BI
;
1618 if (BlockWeights
[BB
]) {
1619 for (auto &I
: *BB
) {
1620 if (!isa
<CallInst
>(I
) && !isa
<InvokeInst
>(I
))
1622 if (!cast
<CallBase
>(I
).getCalledFunction()) {
1623 const DebugLoc
&DLoc
= I
.getDebugLoc();
1626 const DILocation
*DIL
= DLoc
;
1627 const FunctionSamples
*FS
= findFunctionSamples(I
);
1630 auto CallSite
= FunctionSamples::getCallSiteIdentifier(DIL
);
1631 ErrorOr
<SampleRecord::CallTargetMap
> T
=
1632 FS
->findCallTargetMapAt(CallSite
);
1633 if (!T
|| T
.get().empty())
1635 if (FunctionSamples::ProfileIsProbeBased
) {
1636 // Prorate the callsite counts based on the pre-ICP distribution
1637 // factor to reflect what is already done to the callsite before
1638 // ICP, such as calliste cloning.
1639 if (std::optional
<PseudoProbe
> Probe
= extractProbe(I
)) {
1640 if (Probe
->Factor
< 1)
1641 T
= SampleRecord::adjustCallTargets(T
.get(), Probe
->Factor
);
1644 SmallVector
<InstrProfValueData
, 2> SortedCallTargets
=
1645 GetSortedValueDataFromCallTargets(T
.get());
1647 for (const auto &C
: T
.get())
1649 // With CSSPGO all indirect call targets are counted torwards the
1650 // original indirect call site in the profile, including both
1651 // inlined and non-inlined targets.
1652 if (!FunctionSamples::ProfileIsCS
) {
1653 if (const FunctionSamplesMap
*M
=
1654 FS
->findFunctionSamplesMapAt(CallSite
)) {
1655 for (const auto &NameFS
: *M
)
1656 Sum
+= NameFS
.second
.getHeadSamplesEstimate();
1660 updateIDTMetaData(I
, SortedCallTargets
, Sum
);
1661 else if (OverwriteExistingWeights
)
1662 I
.setMetadata(LLVMContext::MD_prof
, nullptr);
1663 } else if (!isa
<IntrinsicInst
>(&I
)) {
1664 setBranchWeights(I
, {static_cast<uint32_t>(BlockWeights
[BB
])});
1667 } else if (OverwriteExistingWeights
|| ProfileSampleBlockAccurate
) {
1668 // Set profile metadata (possibly annotated by LTO prelink) to zero or
1669 // clear it for cold code.
1670 for (auto &I
: *BB
) {
1671 if (isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
)) {
1672 if (cast
<CallBase
>(I
).isIndirectCall()) {
1673 I
.setMetadata(LLVMContext::MD_prof
, nullptr);
1675 setBranchWeights(I
, {uint32_t(0)});
1681 Instruction
*TI
= BB
->getTerminator();
1682 if (TI
->getNumSuccessors() == 1)
1684 if (!isa
<BranchInst
>(TI
) && !isa
<SwitchInst
>(TI
) &&
1685 !isa
<IndirectBrInst
>(TI
))
1688 DebugLoc BranchLoc
= TI
->getDebugLoc();
1689 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1690 << ((BranchLoc
) ? Twine(BranchLoc
.getLine())
1691 : Twine("<UNKNOWN LOCATION>"))
1693 SmallVector
<uint32_t, 4> Weights
;
1694 uint32_t MaxWeight
= 0;
1695 Instruction
*MaxDestInst
;
1696 // Since profi treats multiple edges (multiway branches) as a single edge,
1697 // we need to distribute the computed weight among the branches. We do
1698 // this by evenly splitting the edge weight among destinations.
1699 DenseMap
<const BasicBlock
*, uint64_t> EdgeMultiplicity
;
1700 std::vector
<uint64_t> EdgeIndex
;
1701 if (SampleProfileUseProfi
) {
1702 EdgeIndex
.resize(TI
->getNumSuccessors());
1703 for (unsigned I
= 0; I
< TI
->getNumSuccessors(); ++I
) {
1704 const BasicBlock
*Succ
= TI
->getSuccessor(I
);
1705 EdgeIndex
[I
] = EdgeMultiplicity
[Succ
];
1706 EdgeMultiplicity
[Succ
]++;
1709 for (unsigned I
= 0; I
< TI
->getNumSuccessors(); ++I
) {
1710 BasicBlock
*Succ
= TI
->getSuccessor(I
);
1711 Edge E
= std::make_pair(BB
, Succ
);
1712 uint64_t Weight
= EdgeWeights
[E
];
1713 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E
));
1714 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1715 // if needed. Sample counts in profiles are 64-bit unsigned values,
1716 // but internally branch weights are expressed as 32-bit values.
1717 if (Weight
> std::numeric_limits
<uint32_t>::max()) {
1718 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)\n");
1719 Weight
= std::numeric_limits
<uint32_t>::max();
1721 if (!SampleProfileUseProfi
) {
1722 // Weight is added by one to avoid propagation errors introduced by
1724 Weights
.push_back(static_cast<uint32_t>(
1725 Weight
== std::numeric_limits
<uint32_t>::max() ? Weight
1728 // Profi creates proper weights that do not require "+1" adjustments but
1729 // we evenly split the weight among branches with the same destination.
1730 uint64_t W
= Weight
/ EdgeMultiplicity
[Succ
];
1731 // Rounding up, if needed, so that first branches are hotter.
1732 if (EdgeIndex
[I
] < Weight
% EdgeMultiplicity
[Succ
])
1734 Weights
.push_back(static_cast<uint32_t>(W
));
1737 if (Weight
> MaxWeight
) {
1739 MaxDestInst
= Succ
->getFirstNonPHIOrDbgOrLifetime();
1744 misexpect::checkExpectAnnotations(*TI
, Weights
, /*IsFrontend=*/false);
1746 uint64_t TempWeight
;
1747 // Only set weights if there is at least one non-zero weight.
1748 // In any other case, let the analyzer set weights.
1749 // Do not set weights if the weights are present unless under
1750 // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1751 // twice. If the first annotation already set the weights, the second pass
1752 // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1753 // weight should have their existing metadata (possibly annotated by LTO
1754 // prelink) cleared.
1755 if (MaxWeight
> 0 &&
1756 (!TI
->extractProfTotalWeight(TempWeight
) || OverwriteExistingWeights
)) {
1757 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1758 setBranchWeights(*TI
, Weights
);
1760 return OptimizationRemark(DEBUG_TYPE
, "PopularDest", MaxDestInst
)
1761 << "most popular destination for conditional branches at "
1762 << ore::NV("CondBranchesLoc", BranchLoc
);
1765 if (OverwriteExistingWeights
) {
1766 TI
->setMetadata(LLVMContext::MD_prof
, nullptr);
1767 LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1769 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1775 /// Once all the branch weights are computed, we emit the MD_prof
1776 /// metadata on BB using the computed values for each of its branches.
1778 /// \param F The function to query.
1780 /// \returns true if \p F was modified. Returns false, otherwise.
1781 bool SampleProfileLoader::emitAnnotations(Function
&F
) {
1782 bool Changed
= false;
1784 if (FunctionSamples::ProfileIsProbeBased
) {
1786 if (!ProbeManager
->getDesc(F
))
1787 dbgs() << "Probe descriptor missing for Function " << F
.getName()
1791 if (ProbeManager
->profileIsValid(F
, *Samples
)) {
1792 ++NumMatchedProfile
;
1794 ++NumMismatchedProfile
;
1796 dbgs() << "Profile is invalid due to CFG mismatch for Function "
1797 << F
.getName() << "\n");
1798 if (!SalvageStaleProfile
)
1802 if (getFunctionLoc(F
) == 0)
1805 LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1806 << F
.getName() << ": " << getFunctionLoc(F
) << "\n");
1809 DenseSet
<GlobalValue::GUID
> InlinedGUIDs
;
1810 if (CallsitePrioritizedInline
)
1811 Changed
|= inlineHotFunctionsWithPriority(F
, InlinedGUIDs
);
1813 Changed
|= inlineHotFunctions(F
, InlinedGUIDs
);
1815 Changed
|= computeAndPropagateWeights(F
, InlinedGUIDs
);
1818 generateMDProfMetadata(F
);
1820 emitCoverageRemarks(F
);
1824 std::unique_ptr
<ProfiledCallGraph
>
1825 SampleProfileLoader::buildProfiledCallGraph(Module
&M
) {
1826 std::unique_ptr
<ProfiledCallGraph
> ProfiledCG
;
1827 if (FunctionSamples::ProfileIsCS
)
1828 ProfiledCG
= std::make_unique
<ProfiledCallGraph
>(*ContextTracker
);
1830 ProfiledCG
= std::make_unique
<ProfiledCallGraph
>(Reader
->getProfiles());
1832 // Add all functions into the profiled call graph even if they are not in
1833 // the profile. This makes sure functions missing from the profile still
1834 // gets a chance to be processed.
1835 for (Function
&F
: M
) {
1836 if (skipProfileForFunction(F
))
1838 ProfiledCG
->addProfiledFunction(
1839 getRepInFormat(FunctionSamples::getCanonicalFnName(F
)));
1845 std::vector
<Function
*>
1846 SampleProfileLoader::buildFunctionOrder(Module
&M
, LazyCallGraph
&CG
) {
1847 std::vector
<Function
*> FunctionOrderList
;
1848 FunctionOrderList
.reserve(M
.size());
1850 if (!ProfileTopDownLoad
&& UseProfiledCallGraph
)
1851 errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1852 "together with -sample-profile-top-down-load.\n";
1854 if (!ProfileTopDownLoad
) {
1855 if (ProfileMergeInlinee
) {
1856 // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1857 // because the profile for a function may be used for the profile
1858 // annotation of its outline copy before the profile merging of its
1859 // non-inlined inline instances, and that is not the way how
1860 // ProfileMergeInlinee is supposed to work.
1861 ProfileMergeInlinee
= false;
1864 for (Function
&F
: M
)
1865 if (!skipProfileForFunction(F
))
1866 FunctionOrderList
.push_back(&F
);
1867 return FunctionOrderList
;
1870 if (UseProfiledCallGraph
|| (FunctionSamples::ProfileIsCS
&&
1871 !UseProfiledCallGraph
.getNumOccurrences())) {
1872 // Use profiled call edges to augment the top-down order. There are cases
1873 // that the top-down order computed based on the static call graph doesn't
1874 // reflect real execution order. For example
1876 // 1. Incomplete static call graph due to unknown indirect call targets.
1877 // Adjusting the order by considering indirect call edges from the
1878 // profile can enable the inlining of indirect call targets by allowing
1879 // the caller processed before them.
1880 // 2. Mutual call edges in an SCC. The static processing order computed for
1881 // an SCC may not reflect the call contexts in the context-sensitive
1882 // profile, thus may cause potential inlining to be overlooked. The
1883 // function order in one SCC is being adjusted to a top-down order based
1884 // on the profile to favor more inlining. This is only a problem with CS
1886 // 3. Transitive indirect call edges due to inlining. When a callee function
1887 // (say B) is inlined into a caller function (say A) in LTO prelink,
1888 // every call edge originated from the callee B will be transferred to
1889 // the caller A. If any transferred edge (say A->C) is indirect, the
1890 // original profiled indirect edge B->C, even if considered, would not
1891 // enforce a top-down order from the caller A to the potential indirect
1892 // call target C in LTO postlink since the inlined callee B is gone from
1893 // the static call graph.
1894 // 4. #3 can happen even for direct call targets, due to functions defined
1895 // in header files. A header function (say A), when included into source
1896 // files, is defined multiple times but only one definition survives due
1897 // to ODR. Therefore, the LTO prelink inlining done on those dropped
1898 // definitions can be useless based on a local file scope. More
1899 // importantly, the inlinee (say B), once fully inlined to a
1900 // to-be-dropped A, will have no profile to consume when its outlined
1901 // version is compiled. This can lead to a profile-less prelink
1902 // compilation for the outlined version of B which may be called from
1903 // external modules. while this isn't easy to fix, we rely on the
1904 // postlink AutoFDO pipeline to optimize B. Since the survived copy of
1905 // the A can be inlined in its local scope in prelink, it may not exist
1906 // in the merged IR in postlink, and we'll need the profiled call edges
1907 // to enforce a top-down order for the rest of the functions.
1909 // Considering those cases, a profiled call graph completely independent of
1910 // the static call graph is constructed based on profile data, where
1911 // function objects are not even needed to handle case #3 and case 4.
1913 // Note that static callgraph edges are completely ignored since they
1914 // can be conflicting with profiled edges for cyclic SCCs and may result in
1915 // an SCC order incompatible with profile-defined one. Using strictly
1916 // profile order ensures a maximum inlining experience. On the other hand,
1917 // static call edges are not so important when they don't correspond to a
1918 // context in the profile.
1920 std::unique_ptr
<ProfiledCallGraph
> ProfiledCG
= buildProfiledCallGraph(M
);
1921 scc_iterator
<ProfiledCallGraph
*> CGI
= scc_begin(ProfiledCG
.get());
1922 while (!CGI
.isAtEnd()) {
1924 if (SortProfiledSCC
) {
1925 // Sort nodes in one SCC based on callsite hotness.
1926 scc_member_iterator
<ProfiledCallGraph
*> SI(*CGI
);
1929 for (auto *Node
: Range
) {
1930 Function
*F
= SymbolMap
.lookup(Node
->Name
);
1931 if (F
&& !skipProfileForFunction(*F
))
1932 FunctionOrderList
.push_back(F
);
1938 for (LazyCallGraph::RefSCC
&RC
: CG
.postorder_ref_sccs()) {
1939 for (LazyCallGraph::SCC
&C
: RC
) {
1940 for (LazyCallGraph::Node
&N
: C
) {
1941 Function
&F
= N
.getFunction();
1942 if (!skipProfileForFunction(F
))
1943 FunctionOrderList
.push_back(&F
);
1949 std::reverse(FunctionOrderList
.begin(), FunctionOrderList
.end());
1952 dbgs() << "Function processing order:\n";
1953 for (auto F
: FunctionOrderList
) {
1954 dbgs() << F
->getName() << "\n";
1958 return FunctionOrderList
;
1961 bool SampleProfileLoader::doInitialization(Module
&M
,
1962 FunctionAnalysisManager
*FAM
) {
1963 auto &Ctx
= M
.getContext();
1965 auto ReaderOrErr
= SampleProfileReader::create(
1966 Filename
, Ctx
, *FS
, FSDiscriminatorPass::Base
, RemappingFilename
);
1967 if (std::error_code EC
= ReaderOrErr
.getError()) {
1968 std::string Msg
= "Could not open profile: " + EC
.message();
1969 Ctx
.diagnose(DiagnosticInfoSampleProfile(Filename
, Msg
));
1972 Reader
= std::move(ReaderOrErr
.get());
1973 Reader
->setSkipFlatProf(LTOPhase
== ThinOrFullLTOPhase::ThinLTOPostLink
);
1974 // set module before reading the profile so reader may be able to only
1975 // read the function profiles which are used by the current module.
1976 Reader
->setModule(&M
);
1977 if (std::error_code EC
= Reader
->read()) {
1978 std::string Msg
= "profile reading failed: " + EC
.message();
1979 Ctx
.diagnose(DiagnosticInfoSampleProfile(Filename
, Msg
));
1983 PSL
= Reader
->getProfileSymbolList();
1985 // While profile-sample-accurate is on, ignore symbol list.
1986 ProfAccForSymsInList
=
1987 ProfileAccurateForSymsInList
&& PSL
&& !ProfileSampleAccurate
;
1988 if (ProfAccForSymsInList
) {
1989 NamesInProfile
.clear();
1990 GUIDsInProfile
.clear();
1991 if (auto NameTable
= Reader
->getNameTable()) {
1992 if (FunctionSamples::UseMD5
) {
1993 for (auto Name
: *NameTable
)
1994 GUIDsInProfile
.insert(Name
.getHashCode());
1996 for (auto Name
: *NameTable
)
1997 NamesInProfile
.insert(Name
.stringRef());
2000 CoverageTracker
.setProfAccForSymsInList(true);
2003 if (FAM
&& !ProfileInlineReplayFile
.empty()) {
2004 ExternalInlineAdvisor
= getReplayInlineAdvisor(
2005 M
, *FAM
, Ctx
, /*OriginalAdvisor=*/nullptr,
2006 ReplayInlinerSettings
{ProfileInlineReplayFile
,
2007 ProfileInlineReplayScope
,
2008 ProfileInlineReplayFallback
,
2009 {ProfileInlineReplayFormat
}},
2010 /*EmitRemarks=*/false, InlineContext
{LTOPhase
, InlinePass::ReplaySampleProfileInliner
});
2013 // Apply tweaks if context-sensitive or probe-based profile is available.
2014 if (Reader
->profileIsCS() || Reader
->profileIsPreInlined() ||
2015 Reader
->profileIsProbeBased()) {
2016 if (!UseIterativeBFIInference
.getNumOccurrences())
2017 UseIterativeBFIInference
= true;
2018 if (!SampleProfileUseProfi
.getNumOccurrences())
2019 SampleProfileUseProfi
= true;
2020 if (!EnableExtTspBlockPlacement
.getNumOccurrences())
2021 EnableExtTspBlockPlacement
= true;
2022 // Enable priority-base inliner and size inline by default for CSSPGO.
2023 if (!ProfileSizeInline
.getNumOccurrences())
2024 ProfileSizeInline
= true;
2025 if (!CallsitePrioritizedInline
.getNumOccurrences())
2026 CallsitePrioritizedInline
= true;
2027 // For CSSPGO, we also allow recursive inline to best use context profile.
2028 if (!AllowRecursiveInline
.getNumOccurrences())
2029 AllowRecursiveInline
= true;
2031 if (Reader
->profileIsPreInlined()) {
2032 if (!UsePreInlinerDecision
.getNumOccurrences())
2033 UsePreInlinerDecision
= true;
2036 // Enable stale profile matching by default for probe-based profile.
2037 // Currently the matching relies on if the checksum mismatch is detected,
2038 // which is currently only available for pseudo-probe mode. Removing the
2039 // checksum check could cause regressions for some cases, so further tuning
2040 // might be needed if we want to enable it for all cases.
2041 if (Reader
->profileIsProbeBased() &&
2042 !SalvageStaleProfile
.getNumOccurrences()) {
2043 SalvageStaleProfile
= true;
2046 if (!Reader
->profileIsCS()) {
2047 // Non-CS profile should be fine without a function size budget for the
2048 // inliner since the contexts in the profile are either all from inlining
2049 // in the prevoius build or pre-computed by the preinliner with a size
2050 // cap, thus they are bounded.
2051 if (!ProfileInlineLimitMin
.getNumOccurrences())
2052 ProfileInlineLimitMin
= std::numeric_limits
<unsigned>::max();
2053 if (!ProfileInlineLimitMax
.getNumOccurrences())
2054 ProfileInlineLimitMax
= std::numeric_limits
<unsigned>::max();
2058 if (Reader
->profileIsCS()) {
2059 // Tracker for profiles under different context
2060 ContextTracker
= std::make_unique
<SampleContextTracker
>(
2061 Reader
->getProfiles(), &GUIDToFuncNameMap
);
2064 // Load pseudo probe descriptors for probe-based function samples.
2065 if (Reader
->profileIsProbeBased()) {
2066 ProbeManager
= std::make_unique
<PseudoProbeManager
>(M
);
2067 if (!ProbeManager
->moduleIsProbed(M
)) {
2069 "Pseudo-probe-based profile requires SampleProfileProbePass";
2070 Ctx
.diagnose(DiagnosticInfoSampleProfile(M
.getModuleIdentifier(), Msg
,
2076 if (ReportProfileStaleness
|| PersistProfileStaleness
||
2077 SalvageStaleProfile
) {
2078 MatchingManager
= std::make_unique
<SampleProfileMatcher
>(
2079 M
, *Reader
, ProbeManager
.get(), LTOPhase
);
2085 // Note that this is a module-level check. Even if one module is errored out,
2086 // the entire build will be errored out. However, the user could make big
2087 // changes to functions in single module but those changes might not be
2088 // performance significant to the whole binary. Therefore, to avoid those false
2089 // positives, we select a reasonable big set of hot functions that are supposed
2090 // to be globally performance significant, only compute and check the mismatch
2091 // within those functions. The function selection is based on two criteria:
2092 // 1) The function is hot enough, which is tuned by a hotness-based
2093 // flag(HotFuncCutoffForStalenessError). 2) The num of function is large enough
2094 // which is tuned by the MinfuncsForStalenessError flag.
2095 bool SampleProfileLoader::rejectHighStalenessProfile(
2096 Module
&M
, ProfileSummaryInfo
*PSI
, const SampleProfileMap
&Profiles
) {
2097 assert(FunctionSamples::ProfileIsProbeBased
&&
2098 "Only support for probe-based profile");
2099 uint64_t TotalHotFunc
= 0;
2100 uint64_t NumMismatchedFunc
= 0;
2101 for (const auto &I
: Profiles
) {
2102 const auto &FS
= I
.second
;
2103 const auto *FuncDesc
= ProbeManager
->getDesc(FS
.getGUID());
2107 // Use a hotness-based threshold to control the function selection.
2108 if (!PSI
->isHotCountNthPercentile(HotFuncCutoffForStalenessError
,
2109 FS
.getTotalSamples()))
2113 if (ProbeManager
->profileIsHashMismatched(*FuncDesc
, FS
))
2114 NumMismatchedFunc
++;
2116 // Make sure that the num of selected function is not too small to distinguish
2117 // from the user's benign changes.
2118 if (TotalHotFunc
< MinfuncsForStalenessError
)
2121 // Finally check the mismatch percentage against the threshold.
2122 if (NumMismatchedFunc
* 100 >=
2123 TotalHotFunc
* PrecentMismatchForStalenessError
) {
2124 auto &Ctx
= M
.getContext();
2126 "The input profile significantly mismatches current source code. "
2127 "Please recollect profile to avoid performance regression.";
2128 Ctx
.diagnose(DiagnosticInfoSampleProfile(M
.getModuleIdentifier(), Msg
));
2134 void SampleProfileLoader::removePseudoProbeInsts(Module
&M
) {
2136 std::vector
<Instruction
*> InstsToDel
;
2137 for (auto &BB
: F
) {
2138 for (auto &I
: BB
) {
2139 if (isa
<PseudoProbeInst
>(&I
))
2140 InstsToDel
.push_back(&I
);
2143 for (auto *I
: InstsToDel
)
2144 I
->eraseFromParent();
2148 bool SampleProfileLoader::runOnModule(Module
&M
, ModuleAnalysisManager
*AM
,
2149 ProfileSummaryInfo
*_PSI
,
2150 LazyCallGraph
&CG
) {
2151 GUIDToFuncNameMapper
Mapper(M
, *Reader
, GUIDToFuncNameMap
);
2154 if (M
.getProfileSummary(/* IsCS */ false) == nullptr) {
2155 M
.setProfileSummary(Reader
->getSummary().getMD(M
.getContext()),
2156 ProfileSummary::PSK_Sample
);
2160 if (FunctionSamples::ProfileIsProbeBased
&&
2161 rejectHighStalenessProfile(M
, PSI
, Reader
->getProfiles()))
2164 // Compute the total number of samples collected in this profile.
2165 for (const auto &I
: Reader
->getProfiles())
2166 TotalCollectedSamples
+= I
.second
.getTotalSamples();
2168 auto Remapper
= Reader
->getRemapper();
2169 // Populate the symbol map.
2170 for (const auto &N_F
: M
.getValueSymbolTable()) {
2171 StringRef OrigName
= N_F
.getKey();
2172 Function
*F
= dyn_cast
<Function
>(N_F
.getValue());
2173 if (F
== nullptr || OrigName
.empty())
2175 SymbolMap
[FunctionId(OrigName
)] = F
;
2176 StringRef NewName
= FunctionSamples::getCanonicalFnName(*F
);
2177 if (OrigName
!= NewName
&& !NewName
.empty()) {
2178 auto r
= SymbolMap
.emplace(FunctionId(NewName
), F
);
2179 // Failiing to insert means there is already an entry in SymbolMap,
2180 // thus there are multiple functions that are mapped to the same
2181 // stripped name. In this case of name conflicting, set the value
2182 // to nullptr to avoid confusion.
2184 r
.first
->second
= nullptr;
2187 // Insert the remapped names into SymbolMap.
2189 if (auto MapName
= Remapper
->lookUpNameInProfile(OrigName
)) {
2190 if (*MapName
!= OrigName
&& !MapName
->empty())
2191 SymbolMap
.emplace(FunctionId(*MapName
), F
);
2195 assert(SymbolMap
.count(FunctionId()) == 0 &&
2196 "No empty StringRef should be added in SymbolMap");
2198 if (ReportProfileStaleness
|| PersistProfileStaleness
||
2199 SalvageStaleProfile
) {
2200 MatchingManager
->runOnModule();
2201 MatchingManager
->clearMatchingData();
2204 bool retval
= false;
2205 for (auto *F
: buildFunctionOrder(M
, CG
)) {
2206 assert(!F
->isDeclaration());
2207 clearFunctionData();
2208 retval
|= runOnFunction(*F
, AM
);
2211 // Account for cold calls not inlined....
2212 if (!FunctionSamples::ProfileIsCS
)
2213 for (const std::pair
<Function
*, NotInlinedProfileInfo
> &pair
:
2215 updateProfileCallee(pair
.first
, pair
.second
.entryCount
);
2217 if (RemoveProbeAfterProfileAnnotation
&& FunctionSamples::ProfileIsProbeBased
)
2218 removePseudoProbeInsts(M
);
2223 bool SampleProfileLoader::runOnFunction(Function
&F
, ModuleAnalysisManager
*AM
) {
2224 LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F
.getName() << "\n");
2225 DILocation2SampleMap
.clear();
2226 // By default the entry count is initialized to -1, which will be treated
2227 // conservatively by getEntryCount as the same as unknown (None). This is
2228 // to avoid newly added code to be treated as cold. If we have samples
2229 // this will be overwritten in emitAnnotations.
2230 uint64_t initialEntryCount
= -1;
2232 ProfAccForSymsInList
= ProfileAccurateForSymsInList
&& PSL
;
2233 if (ProfileSampleAccurate
|| F
.hasFnAttribute("profile-sample-accurate")) {
2234 // initialize all the function entry counts to 0. It means all the
2235 // functions without profile will be regarded as cold.
2236 initialEntryCount
= 0;
2237 // profile-sample-accurate is a user assertion which has a higher precedence
2238 // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2239 ProfAccForSymsInList
= false;
2241 CoverageTracker
.setProfAccForSymsInList(ProfAccForSymsInList
);
2243 // PSL -- profile symbol list include all the symbols in sampled binary.
2244 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2245 // old functions without samples being cold, without having to worry
2246 // about new and hot functions being mistakenly treated as cold.
2247 if (ProfAccForSymsInList
) {
2248 // Initialize the entry count to 0 for functions in the list.
2249 if (PSL
->contains(F
.getName()))
2250 initialEntryCount
= 0;
2252 // Function in the symbol list but without sample will be regarded as
2253 // cold. To minimize the potential negative performance impact it could
2254 // have, we want to be a little conservative here saying if a function
2255 // shows up in the profile, no matter as outline function, inline instance
2256 // or call targets, treat the function as not being cold. This will handle
2257 // the cases such as most callsites of a function are inlined in sampled
2258 // binary but not inlined in current build (because of source code drift,
2259 // imprecise debug information, or the callsites are all cold individually
2260 // but not cold accumulatively...), so the outline function showing up as
2261 // cold in sampled binary will actually not be cold after current build.
2262 StringRef CanonName
= FunctionSamples::getCanonicalFnName(F
);
2263 if ((FunctionSamples::UseMD5
&&
2264 GUIDsInProfile
.count(Function::getGUID(CanonName
))) ||
2265 (!FunctionSamples::UseMD5
&& NamesInProfile
.count(CanonName
)))
2266 initialEntryCount
= -1;
2269 // Initialize entry count when the function has no existing entry
2271 if (!F
.getEntryCount())
2272 F
.setEntryCount(ProfileCount(initialEntryCount
, Function::PCT_Real
));
2273 std::unique_ptr
<OptimizationRemarkEmitter
> OwnedORE
;
2276 AM
->getResult
<FunctionAnalysisManagerModuleProxy
>(*F
.getParent())
2278 ORE
= &FAM
.getResult
<OptimizationRemarkEmitterAnalysis
>(F
);
2280 OwnedORE
= std::make_unique
<OptimizationRemarkEmitter
>(&F
);
2281 ORE
= OwnedORE
.get();
2284 if (FunctionSamples::ProfileIsCS
)
2285 Samples
= ContextTracker
->getBaseSamplesFor(F
);
2287 Samples
= Reader
->getSamplesFor(F
);
2288 // Try search in previously inlined functions that were split or duplicated
2291 StringRef CanonName
= FunctionSamples::getCanonicalFnName(F
);
2292 auto It
= OutlineFunctionSamples
.find(FunctionId(CanonName
));
2293 if (It
!= OutlineFunctionSamples
.end()) {
2294 Samples
= &It
->second
;
2295 } else if (auto Remapper
= Reader
->getRemapper()) {
2296 if (auto RemppedName
= Remapper
->lookUpNameInProfile(CanonName
)) {
2297 It
= OutlineFunctionSamples
.find(FunctionId(*RemppedName
));
2298 if (It
!= OutlineFunctionSamples
.end())
2299 Samples
= &It
->second
;
2305 if (Samples
&& !Samples
->empty())
2306 return emitAnnotations(F
);
2309 SampleProfileLoaderPass::SampleProfileLoaderPass(
2310 std::string File
, std::string RemappingFile
, ThinOrFullLTOPhase LTOPhase
,
2311 IntrusiveRefCntPtr
<vfs::FileSystem
> FS
)
2312 : ProfileFileName(File
), ProfileRemappingFileName(RemappingFile
),
2313 LTOPhase(LTOPhase
), FS(std::move(FS
)) {}
2315 PreservedAnalyses
SampleProfileLoaderPass::run(Module
&M
,
2316 ModuleAnalysisManager
&AM
) {
2317 FunctionAnalysisManager
&FAM
=
2318 AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
2320 auto GetAssumptionCache
= [&](Function
&F
) -> AssumptionCache
& {
2321 return FAM
.getResult
<AssumptionAnalysis
>(F
);
2323 auto GetTTI
= [&](Function
&F
) -> TargetTransformInfo
& {
2324 return FAM
.getResult
<TargetIRAnalysis
>(F
);
2326 auto GetTLI
= [&](Function
&F
) -> const TargetLibraryInfo
& {
2327 return FAM
.getResult
<TargetLibraryAnalysis
>(F
);
2331 FS
= vfs::getRealFileSystem();
2333 SampleProfileLoader
SampleLoader(
2334 ProfileFileName
.empty() ? SampleProfileFile
: ProfileFileName
,
2335 ProfileRemappingFileName
.empty() ? SampleProfileRemappingFile
2336 : ProfileRemappingFileName
,
2337 LTOPhase
, FS
, GetAssumptionCache
, GetTTI
, GetTLI
);
2339 if (!SampleLoader
.doInitialization(M
, &FAM
))
2340 return PreservedAnalyses::all();
2342 ProfileSummaryInfo
*PSI
= &AM
.getResult
<ProfileSummaryAnalysis
>(M
);
2343 LazyCallGraph
&CG
= AM
.getResult
<LazyCallGraphAnalysis
>(M
);
2344 if (!SampleLoader
.runOnModule(M
, &AM
, PSI
, CG
))
2345 return PreservedAnalyses::all();
2347 return PreservedAnalyses::none();