LLVM 24.0.0git
SampleProfile.cpp
Go to the documentation of this file.
1//===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SampleProfileLoader transformation. This pass
10// reads a profile file generated by a sampling profiler (e.g. Linux Perf -
11// http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
12// profile information in the given profile.
13//
14// This pass generates branch weight annotations on the IR:
15//
16// - prof: Represents branch weights. This annotation is added to branches
17// to indicate the weights of each edge coming out of the branch.
18// The weight of each edge is the weight of the target block for
19// that edge. The weight of a block B is computed as the maximum
20// number of samples found in B.
21//
22//===----------------------------------------------------------------------===//
23
25#include "IPOOptions.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/MapVector.h"
32#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/ADT/Twine.h"
47#include "llvm/IR/BasicBlock.h"
48#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
56#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/MDBuilder.h"
58#include "llvm/IR/Module.h"
59#include "llvm/IR/PassManager.h"
61#include "llvm/IR/PseudoProbe.h"
68#include "llvm/Support/Debug.h"
72#include "llvm/Transforms/IPO.h"
84#include <algorithm>
85#include <cassert>
86#include <cstdint>
87#include <functional>
88#include <limits>
89#include <memory>
90#include <queue>
91#include <string>
92#include <system_error>
93#include <utility>
94#include <vector>
95
96using namespace llvm;
97using namespace sampleprof;
98using namespace llvm::sampleprofutil;
99#define DEBUG_TYPE "sample-profile"
100#define CSINLINE_DEBUG DEBUG_TYPE "-inline"
101
102STATISTIC(NumCSInlined,
103 "Number of functions inlined with context sensitive profile");
104STATISTIC(NumCSNotInlined,
105 "Number of functions not inlined with context sensitive profile");
106STATISTIC(NumMismatchedProfile,
107 "Number of functions with CFG mismatched profile");
108STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
109STATISTIC(NumDuplicatedInlinesite,
110 "Number of inlined callsites with a partial distribution factor");
111
112STATISTIC(NumCSInlinedHitMinLimit,
113 "Number of functions with FDO inline stopped due to min size limit");
114STATISTIC(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");
119
120namespace llvm {
122}
123
124namespace {
125
126using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
127using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
128using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
129using BlockEdgeMap =
131
132class GUIDToFuncNameMapper {
133public:
134 GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
135 DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
136 : CurrentReader(Reader), CurrentModule(M),
137 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
138 if (!CurrentReader.useMD5())
139 return;
140
141 for (const auto &F : CurrentModule) {
142 StringRef OrigName = F.getName();
143 CurrentGUIDToFuncNameMap.insert(
144 {Function::getGUIDAssumingExternalLinkage(OrigName), OrigName});
145
146 // Local to global var promotion used by optimization like thinlto
147 // will rename the var and add suffix like ".llvm.xxx" to the
148 // original local name. In sample profile, the suffixes of function
149 // names are all stripped. Since it is possible that the mapper is
150 // built in post-thin-link phase and var promotion has been done,
151 // we need to add the substring of function name without the suffix
152 // into the GUIDToFuncNameMap.
154 if (CanonName != OrigName)
155 CurrentGUIDToFuncNameMap.insert(
156 {Function::getGUIDAssumingExternalLinkage(CanonName), CanonName});
157 }
158
159 // Update GUIDToFuncNameMap for each function including inlinees.
160 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
161 }
162
163 ~GUIDToFuncNameMapper() {
164 if (!CurrentReader.useMD5())
165 return;
166
167 CurrentGUIDToFuncNameMap.clear();
168
169 // Reset GUIDToFuncNameMap for of each function as they're no
170 // longer valid at this point.
171 SetGUIDToFuncNameMapForAll(nullptr);
172 }
173
174private:
175 void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
176 std::queue<FunctionSamples *> FSToUpdate;
177 for (auto &IFS : CurrentReader.getProfiles()) {
178 FSToUpdate.push(&IFS.second);
179 }
180
181 while (!FSToUpdate.empty()) {
182 FunctionSamples *FS = FSToUpdate.front();
183 FSToUpdate.pop();
184 FS->GUIDToFuncNameMap = Map;
185 for (const auto &ICS : FS->getCallsiteSamples()) {
186 const FunctionSamplesMap &FSMap = ICS.second;
187 for (const auto &IFS : FSMap) {
188 FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
189 FSToUpdate.push(&FS);
190 }
191 }
192 }
193 }
194
196 Module &CurrentModule;
197 DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
198};
199
200// Inline candidate used by iterative callsite prioritized inliner
201struct InlineCandidate {
202 CallBase *CallInstr;
203 const FunctionSamples *CalleeSamples;
204 // Prorated callsite count, which will be used to guide inlining. For example,
205 // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
206 // copies will get their own distribution factors and their prorated counts
207 // will be used to decide if they should be inlined independently.
208 uint64_t CallsiteCount;
209 // Call site distribution factor to prorate the profile samples for a
210 // duplicated callsite. Default value is 1.0.
211 float CallsiteDistribution;
212};
213
214// Inline candidate comparer using call site weight
215struct CandidateComparer {
216 bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
217 if (LHS.CallsiteCount != RHS.CallsiteCount)
218 return LHS.CallsiteCount < RHS.CallsiteCount;
219
220 const FunctionSamples *LCS = LHS.CalleeSamples;
221 const FunctionSamples *RCS = RHS.CalleeSamples;
222 // In inline replay mode, CalleeSamples may be null and the order doesn't
223 // matter.
224 if (!LCS || !RCS)
225 return LCS;
226
227 // Tie breaker using number of samples try to favor smaller functions first
228 if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
229 return LCS->getBodySamples().size() > RCS->getBodySamples().size();
230
231 // Tie breaker using GUID so we have stable/deterministic inlining order
232 return LCS->getGUID() < RCS->getGUID();
233 }
234};
235
236using CandidateQueue =
238 CandidateComparer>;
239
240/// Sample profile pass.
241///
242/// This pass reads profile data from the file specified by
243/// -sample-profile-file and annotates every affected function with the
244/// profile information found in that file.
245class SampleProfileLoader final : public SampleProfileLoaderBaseImpl<Function> {
246public:
247 SampleProfileLoader(
248 const IPOOptions &Opts, StringRef Name, StringRef RemapName,
249 ThinOrFullLTOPhase LTOPhase, IntrusiveRefCntPtr<vfs::FileSystem> FS,
250 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
251 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
252 std::function<const TargetLibraryInfo &(Function &)> GetTLI,
253 LazyCallGraph &CG, bool DisableSampleProfileInlining,
254 bool UseFlattenedProfile)
255 : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName),
256 std::move(FS)),
257 Opts(Opts), ProfileMergeInlinee(Opts.sample_profile_merge_inlinee),
258 ProfileSizeInline(valueOr(Opts.sample_profile_inline_size, false)),
259 CallsitePrioritizedInline(
260 valueOr(Opts.sample_profile_prioritized_inline, false)),
261 AllowRecursiveInline(
262 valueOr(Opts.sample_profile_recursive_inline, false)),
263 UsePreInlinerDecision(
264 valueOr(Opts.sample_profile_use_preinliner, false)),
265 SalvageStaleProfile(valueOr(Opts.salvage_stale_profile, false)),
266 SalvageUnusedProfile(valueOr(Opts.salvage_unused_profile, false)),
267 GetAC(std::move(GetAssumptionCache)),
268 GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
269 CG(CG), LTOPhase(LTOPhase),
270 AnnotatedPassName(Opts.annotate_sample_profile_inline_phase
271 ? llvm::AnnotateInlinePassName(InlineContext{
274 DisableSampleProfileInlining(DisableSampleProfileInlining),
275 UseFlattenedProfile(UseFlattenedProfile) {}
276
277 bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
278 bool runOnModule(Module &M, ModuleAnalysisManager &AM,
279 ProfileSummaryInfo *_PSI);
280
281protected:
282 const IPOOptions &Opts;
283 // Options the loader adjusts according to the profile.
284 bool ProfileMergeInlinee;
285 bool ProfileSizeInline;
286 bool CallsitePrioritizedInline;
287 bool AllowRecursiveInline;
288 bool UsePreInlinerDecision;
289 bool SalvageStaleProfile;
290 bool SalvageUnusedProfile;
291 SampleProfileInlineOptions InlineOpts;
292
294 bool emitAnnotations(Function &F);
295 ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
296 const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
297 const FunctionSamples *
298 findFunctionSamples(const Instruction &I) const override;
299 std::vector<const FunctionSamples *>
300 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
301 void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
302 DenseSet<GlobalValue::GUID> &InlinedGUIDs,
303 uint64_t Threshold);
304 // Attempt to promote indirect call and also inline the promoted call
305 bool tryPromoteAndInlineCandidate(
306 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
307 uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
308
309 bool inlineHotFunctions(Function &F,
310 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
311 std::optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
312 bool getExternalInlineAdvisorShouldInline(CallBase &CB);
313 InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
314 bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
315 bool
316 tryInlineCandidate(InlineCandidate &Candidate,
317 SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
318 bool
319 inlineHotFunctionsWithPriority(Function &F,
320 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
321 // Inline cold/small functions in addition to hot ones
322 bool shouldInlineColdCallee(CallBase &CallInst);
323 void emitOptimizationRemarksForInlineCandidates(
324 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
325 bool Hot);
326 void promoteMergeNotInlinedContextSamples(
327 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
328 const Function &F);
329 std::vector<Function *> buildFunctionOrder(Module &M, LazyCallGraph &CG);
330 std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(Module &M);
331 void generateMDProfMetadata(Function &F);
332 bool rejectHighStalenessProfile(Module &M, ProfileSummaryInfo *PSI,
333 const SampleProfileMap &Profiles);
334 void removePseudoProbeInstsDiscriminator(Module &M);
335
336 /// Map from function name to Function *. Used to find the function from
337 /// the function name. If the function name contains suffix, additional
338 /// entry is added to map from the stripped name to the function if there
339 /// is one-to-one mapping.
340 HashKeyMap<DenseMap, FunctionId, Function *> SymbolMap;
341
342 /// Map from canonical (or remapped) profile name to the clones
343 /// MemProfContextDisambiguation made of that function (F.memprof.1,
344 /// F.memprof.2, ...) in the ThinLTO backend. A clone uses the profile of its
345 /// original function. It is left out of the stripped name entries in
346 /// SymbolMap and is scheduled alongside its profiled call graph node.
347 HashKeyMap<DenseMap, FunctionId, SmallVector<Function *, 1>> MemProfClones;
348
349 /// Map from function name to profile name generated by call-graph based
350 /// profile fuzzy matching(--salvage-unused-profile).
351 HashKeyMap<DenseMap, FunctionId, FunctionId> FuncNameToProfNameMap;
352
353 std::function<AssumptionCache &(Function &)> GetAC;
354 std::function<TargetTransformInfo &(Function &)> GetTTI;
355 std::function<const TargetLibraryInfo &(Function &)> GetTLI;
356 LazyCallGraph &CG;
357
358 /// Profile tracker for different context.
359 std::unique_ptr<SampleContextTracker> ContextTracker;
360
361 /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
362 ///
363 /// We need to know the LTO phase because for example in ThinLTOPrelink
364 /// phase, in annotation, we should not promote indirect calls. Instead,
365 /// we will mark GUIDs that needs to be annotated to the function.
366 const ThinOrFullLTOPhase LTOPhase;
367 const std::string AnnotatedPassName;
368
369 /// Profle Symbol list tells whether a function name appears in the binary
370 /// used to generate the current profile.
371 std::shared_ptr<ProfileSymbolList> PSL;
372
373 // Information recorded when we declined to inline a call site
374 // because we have determined it is too cold is accumulated for
375 // each callee function. Initially this is just the entry count.
376 struct NotInlinedProfileInfo {
377 uint64_t entryCount;
378 };
379 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
380
381 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
382 // all the function symbols defined or declared in current module.
383 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
384
385 // For symbol in profile symbol list, whether to regard their profiles
386 // to be accurate. It is mainly decided by existance of profile symbol
387 // list and -profile-accurate-for-symsinlist flag, but it can be
388 // overriden by -profile-sample-accurate or profile-sample-accurate
389 // attribute.
390 bool ProfAccForSymsInList;
391
392 bool DisableSampleProfileInlining;
393
394 bool UseFlattenedProfile;
395
396 // External inline advisor used to replay inline decision from remarks.
397 std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
398
399 // A helper to implement the sample profile matching algorithm.
400 std::unique_ptr<SampleProfileMatcher> MatchingManager;
401
402private:
403 const char *getAnnotatedRemarkPassName() const {
404 return AnnotatedPassName.c_str();
405 }
406};
407} // end anonymous namespace
408
409namespace llvm {
410template <>
411inline bool SampleProfileInference<Function>::isExit(const BasicBlock *BB) {
412 return succ_empty(BB);
413}
414
415template <>
416inline void SampleProfileInference<Function>::findUnlikelyJumps(
417 const std::vector<const BasicBlockT *> &BasicBlocks,
418 BlockEdgeMap &Successors, FlowFunction &Func) {
419 for (auto &Jump : Func.Jumps) {
420 const auto *BB = BasicBlocks[Jump.Source];
421 const auto *Succ = BasicBlocks[Jump.Target];
422 const Instruction *TI = BB->getTerminator();
423 // Check if a block ends with InvokeInst and mark non-taken branch unlikely.
424 // In that case block Succ should be a landing pad
425 const auto &Succs = Successors[BB];
426 if (Succs.size() == 2 && Succs.back() == Succ) {
427 if (isa<InvokeInst>(TI)) {
428 Jump.IsUnlikely = true;
429 }
430 }
431 const Instruction *SuccTI = Succ->getTerminator();
432 // Check if the target block contains UnreachableInst and mark it unlikely
433 if (SuccTI->getNumSuccessors() == 0) {
434 if (isa<UnreachableInst>(SuccTI)) {
435 Jump.IsUnlikely = true;
436 }
437 }
438 }
439}
440
441template <>
443 Function &F) {
444 DT.reset(new DominatorTree);
445 DT->recalculate(F);
446
447 PDT.reset(new PostDominatorTree(F));
448
449 LI.reset(new LoopInfo);
450 LI->analyze(*DT);
451}
452} // namespace llvm
453
454ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
456 return getProbeWeight(Inst);
457
458 const DebugLoc &DLoc = Inst.getDebugLoc();
459 if (!DLoc)
460 return std::error_code();
461
462 // Ignore all intrinsics, phinodes and branch instructions.
463 // Branch and phinodes instruction usually contains debug info from sources
464 // outside of the residing basic block, thus we ignore them during annotation.
466 return std::error_code();
467
468 // For non-CS profile, if a direct call/invoke instruction is inlined in
469 // profile (findCalleeFunctionSamples returns non-empty result), but not
470 // inlined here, it means that the inlined callsite has no sample, thus the
471 // call instruction should have 0 count.
472 // For CS profile, the callsite count of previously inlined callees is
473 // populated with the entry count of the callees.
475 if (const auto *CB = dyn_cast<CallBase>(&Inst))
476 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
477 return 0;
478
479 return getInstWeightImpl(Inst);
480}
481
482/// Get the FunctionSamples for a call instruction.
483///
484/// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
485/// instance in which that call instruction is calling to. It contains
486/// all samples that resides in the inlined instance. We first find the
487/// inlined instance in which the call instruction is from, then we
488/// traverse its children to find the callsite with the matching
489/// location.
490///
491/// \param Inst Call/Invoke instruction to query.
492///
493/// \returns The FunctionSamples pointer to the inlined instance.
494const FunctionSamples *
495SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
496 const DILocation *DIL = Inst.getDebugLoc();
497 if (!DIL) {
498 return nullptr;
499 }
500
501 StringRef CalleeName;
502 if (Function *Callee = Inst.getCalledFunction())
503 CalleeName = Callee->getName();
504
506 return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
507
508 const FunctionSamples *FS = findFunctionSamples(Inst);
509 if (FS == nullptr)
510 return nullptr;
511
512 return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
513 CalleeName, Reader->getRemapper(),
514 &FuncNameToProfNameMap);
515}
516
517/// Returns a vector of FunctionSamples that are the indirect call targets
518/// of \p Inst. The vector is sorted by the total number of samples. Stores
519/// the total call count of the indirect call in \p Sum.
520std::vector<const FunctionSamples *>
521SampleProfileLoader::findIndirectCallFunctionSamples(
522 const Instruction &Inst, uint64_t &Sum) const {
523 const DILocation *DIL = Inst.getDebugLoc();
524 std::vector<const FunctionSamples *> R;
525
526 if (!DIL) {
527 return R;
528 }
529
530 auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
531 assert(L && R && "Expect non-null FunctionSamples");
532 if (L->getHeadSamplesEstimate() != R->getHeadSamplesEstimate())
533 return L->getHeadSamplesEstimate() > R->getHeadSamplesEstimate();
534 return L->getGUID() < R->getGUID();
535 };
536
538 auto CalleeSamples =
539 ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
540 if (CalleeSamples.empty())
541 return R;
542
543 // For CSSPGO, we only use target context profile's entry count
544 // as that already includes both inlined callee and non-inlined ones..
545 Sum = 0;
546 for (const auto *const FS : CalleeSamples) {
547 Sum += FS->getHeadSamplesEstimate();
548 R.push_back(FS);
549 }
550 llvm::sort(R, FSCompare);
551 return R;
552 }
553
554 const FunctionSamples *FS = findFunctionSamples(Inst);
555 if (FS == nullptr)
556 return R;
557
559 Sum = 0;
560 if (auto T = FS->findCallTargetMapAt(CallSite))
561 for (const auto &T_C : *T)
562 Sum += T_C.second;
563 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
564 if (M->empty())
565 return R;
566 for (const auto &NameFS : *M) {
567 Sum += NameFS.second.getHeadSamplesEstimate();
568 R.push_back(&NameFS.second);
569 }
570 llvm::sort(R, FSCompare);
571 }
572 return R;
573}
574
575const FunctionSamples *
576SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
578 std::optional<PseudoProbe> Probe = extractProbe(Inst);
579 if (!Probe)
580 return nullptr;
581 }
582
583 const DILocation *DIL = Inst.getDebugLoc();
584 if (!DIL)
585 return Samples;
586
587 auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
588 if (it.second) {
590 it.first->second = ContextTracker->getContextSamplesFor(DIL);
591 else
592 it.first->second = Samples->findFunctionSamples(
593 DIL, Reader->getRemapper(), &FuncNameToProfNameMap);
594 }
595 return it.first->second;
596}
597
598/// Check whether the indirect call promotion history of \p Inst allows
599/// the promotion for \p Candidate.
600/// If the profile count for the promotion candidate \p Candidate is
601/// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
602/// for \p Inst. If we already have at least MaxNumPromotions
603/// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
604/// cannot promote for \p Inst anymore.
605static bool doesHistoryAllowICP(const IPOOptions &Opts, const Instruction &Inst,
606 StringRef Candidate) {
607 uint64_t TotalCount = 0;
608 auto ValueData = getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
609 Opts.sample_profile_icp_max_prom,
610 TotalCount, true);
611 // No valid value profile so no promoted targets have been recorded
612 // before. Ok to do ICP.
613 if (ValueData.empty())
614 return true;
615
616 unsigned NumPromoted = 0;
617 for (const auto &V : ValueData) {
618 if (V.Count != NOMORE_ICP_MAGICNUM)
619 continue;
620
621 // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
622 // metadata, it means the candidate has been promoted for this
623 // indirect call.
624 if (V.Value == Function::getGUIDAssumingExternalLinkage(Candidate))
625 return false;
626 NumPromoted++;
627 // If already have MaxNumPromotions promotion, don't do it anymore.
628 if (NumPromoted == Opts.sample_profile_icp_max_prom)
629 return false;
630 }
631 return true;
632}
633
634/// Update indirect call target profile metadata for \p Inst.
635/// Usually \p Sum is the sum of counts of all the targets for \p Inst.
636/// If it is 0, it means updateIDTMetaData is used to mark a
637/// certain target to be promoted already. If it is not zero,
638/// we expect to use it to update the total count in the value profile.
639static void
640updateIDTMetaData(const IPOOptions &Opts, Instruction &Inst,
641 const SmallVectorImpl<InstrProfValueData> &CallTargets,
642 uint64_t Sum) {
643 // Bail out early if MaxNumPromotions is zero.
644 // This prevents allocating an array of zero length below.
645 //
646 // Note `updateIDTMetaData` is called in two places so check
647 // `MaxNumPromotions` inside it.
648 if (Opts.sample_profile_icp_max_prom == 0)
649 return;
650 // OldSum is the existing total count in the value profile data.
651 uint64_t OldSum = 0;
652 auto ValueData =
653 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
654 Opts.sample_profile_icp_max_prom, OldSum, true);
655
656 DenseMap<uint64_t, uint64_t> ValueCountMap;
657 if (Sum == 0) {
658 assert((CallTargets.size() == 1 &&
659 CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
660 "If sum is 0, assume only one element in CallTargets "
661 "with count being NOMORE_ICP_MAGICNUM");
662 // Initialize ValueCountMap with existing value profile data.
663 for (const auto &V : ValueData)
664 ValueCountMap[V.Value] = V.Count;
665 auto Pair =
666 ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
667 // If the target already exists in value profile, decrease the total
668 // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
669 if (!Pair.second) {
670 OldSum -= Pair.first->second;
671 Pair.first->second = NOMORE_ICP_MAGICNUM;
672 }
673 Sum = OldSum;
674 } else {
675 // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
676 // counts in the value profile.
677 for (const auto &V : ValueData) {
678 if (V.Count == NOMORE_ICP_MAGICNUM)
679 ValueCountMap[V.Value] = V.Count;
680 }
681
682 for (const auto &Data : CallTargets) {
683 auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
684 if (Pair.second)
685 continue;
686 // The target represented by Data.Value has already been promoted.
687 // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
688 // Sum by Data.Count.
689 assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
690 Sum -= Data.Count;
691 }
692 }
693
695 for (const auto &ValueCount : ValueCountMap) {
696 NewCallTargets.emplace_back(
697 InstrProfValueData{ValueCount.first, ValueCount.second});
698 }
699
700 llvm::sort(NewCallTargets,
701 [](const InstrProfValueData &L, const InstrProfValueData &R) {
702 return std::tie(L.Count, L.Value) > std::tie(R.Count, R.Value);
703 });
704
705 uint32_t MaxMDCount =
706 std::min(NewCallTargets.size(),
707 static_cast<size_t>(Opts.sample_profile_icp_max_prom));
708 annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
709 NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
710}
711
712/// Attempt to promote indirect call and also inline the promoted call.
713///
714/// \param F Caller function.
715/// \param Candidate ICP and inline candidate.
716/// \param SumOrigin Original sum of target counts for indirect call before
717/// promoting given candidate.
718/// \param Sum Prorated sum of remaining target counts for indirect call
719/// after promoting given candidate.
720/// \param InlinedCallSite Output vector for new call sites exposed after
721/// inlining.
722bool SampleProfileLoader::tryPromoteAndInlineCandidate(
723 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
724 SmallVector<CallBase *, 8> *InlinedCallSite) {
725 // Bail out early if sample-loader inliner is disabled.
726 if (DisableSampleProfileInlining)
727 return false;
728
729 // Bail out early if MaxNumPromotions is zero.
730 // This prevents allocating an array of zero length in callees below.
731 if (Opts.sample_profile_icp_max_prom == 0)
732 return false;
733 auto CalleeFunctionName = Candidate.CalleeSamples->getFunction();
734 auto R = SymbolMap.find(CalleeFunctionName);
735 if (R == SymbolMap.end() || !R->second)
736 return false;
737
738 auto &CI = *Candidate.CallInstr;
739 if (!doesHistoryAllowICP(Opts, CI, R->second->getName()))
740 return false;
741
742 const char *Reason = "Callee function not available";
743 // R->getValue() != &F is to prevent promoting a recursive call.
744 // If it is a recursive call, we do not inline it as it could bloat
745 // the code exponentially. There is way to better handle this, e.g.
746 // clone the caller first, and inline the cloned caller if it is
747 // recursive. As llvm does not inline recursive calls, we will
748 // simply ignore it instead of handling it explicitly.
749 if (!R->second->isDeclaration() && R->second->getSubprogram() &&
750 R->second->hasFnAttribute("use-sample-profile") &&
751 R->second != &F && isLegalToPromote(CI, R->second, &Reason)) {
752 // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
753 // in the value profile metadata so the target won't be promoted again.
754 SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
755 Function::getGUIDAssumingExternalLinkage(R->second->getName()),
757 updateIDTMetaData(Opts, CI, SortedCallTargets, 0);
758
759 auto *DI = &pgo::promoteIndirectCall(
760 CI, R->second, Candidate.CallsiteCount, Sum, false, ORE);
761 if (DI) {
762 Sum -= Candidate.CallsiteCount;
763 // Do not prorate the indirect callsite distribution since the original
764 // distribution will be used to scale down non-promoted profile target
765 // counts later. By doing this we lose track of the real callsite count
766 // for the leftover indirect callsite as a trade off for accurate call
767 // target counts.
768 // TODO: Ideally we would have two separate factors, one for call site
769 // counts and one is used to prorate call target counts.
770 // Do not update the promoted direct callsite distribution at this
771 // point since the original distribution combined with the callee profile
772 // will be used to prorate callsites from the callee if inlined. Once not
773 // inlined, the direct callsite distribution should be prorated so that
774 // the it will reflect the real callsite counts.
775 Candidate.CallInstr = DI;
776 if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
777 bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
778 if (!Inlined) {
779 // Prorate the direct callsite distribution so that it reflects real
780 // callsite counts.
782 *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
783 }
784 return Inlined;
785 }
786 }
787 } else {
788 LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
790 Candidate.CallInstr->getName())<< " because "
791 << Reason << "\n");
792 }
793 return false;
794}
795
796bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
797 if (!ProfileSizeInline)
798 return false;
799
800 if (CallInst.getCalledFunction() == nullptr)
801 return false;
802
803 InlineCost Cost =
804 getInlineCost(CallInst, getInlineParams(CallInst.getContext()),
805 GetTTI(*CallInst.getCaller()), GetAC, GetTLI);
806
807 if (Cost.isNever())
808 return false;
809
810 if (Cost.isAlways())
811 return true;
812
813 return Cost.getCost() <= InlineOpts.ColdCallSiteThreshold;
814}
815
816void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
817 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
818 bool Hot) {
819 for (auto *I : Candidates) {
820 Function *CalledFunction = I->getCalledFunction();
821 if (CalledFunction) {
822 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
823 "InlineAttempt", I->getDebugLoc(),
824 I->getParent())
825 << "previous inlining reattempted for "
826 << (Hot ? "hotness: '" : "size: '")
827 << ore::NV("Callee", CalledFunction) << "' into '"
828 << ore::NV("Caller", &F) << "'");
829 }
830 }
831}
832
833void SampleProfileLoader::findExternalInlineCandidate(
834 CallBase *CB, const FunctionSamples *Samples,
835 DenseSet<GlobalValue::GUID> &InlinedGUIDs, uint64_t Threshold) {
836 // Normally only functions defined outside this module need import hints.
837 // The targets of a deferred indirect call are an exception: another module
838 // that imports the caller must import them too, and no direct call to them
839 // may survive to create a summary edge.
840 bool IncludeLocalTargets = Opts.sample_profile_preserve_deferred_inlines &&
841 CB && CB->isIndirectCall();
842
843 // If ExternalInlineAdvisor(ReplayInlineAdvisor) wants to inline an external
844 // function make sure it's imported
845 if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
846 // Samples may not exist for replayed function, if so
847 // just add the direct GUID and move on
848 if (!Samples) {
849 InlinedGUIDs.insert(Function::getGUIDAssumingExternalLinkage(
850 CB->getCalledFunction()->getName()));
851 return;
852 }
853 // Otherwise, drop the threshold to import everything that we can
854 Threshold = 0;
855 }
856
857 // In some rare cases, call instruction could be changed after being pushed
858 // into inline candidate queue, this is because earlier inlining may expose
859 // constant propagation which can change indirect call to direct call. When
860 // this happens, we may fail to find matching function samples for the
861 // candidate later, even if a match was found when the candidate was enqueued.
862 if (!Samples)
863 return;
864
865 // For AutoFDO profile, retrieve candidate profiles by walking over
866 // the nested inlinee profiles.
868 // Set threshold to zero to honor pre-inliner decision.
869 if (UsePreInlinerDecision)
870 Threshold = 0;
871 Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold,
872 IncludeLocalTargets);
873 return;
874 }
875
876 ContextTrieNode *Caller = ContextTracker->getContextNodeForProfile(Samples);
877 std::queue<ContextTrieNode *> CalleeList;
878 CalleeList.push(Caller);
879 while (!CalleeList.empty()) {
880 ContextTrieNode *Node = CalleeList.front();
881 CalleeList.pop();
882 FunctionSamples *CalleeSample = Node->getFunctionSamples();
883 // For CSSPGO profile, retrieve candidate profile by walking over the
884 // trie built for context profile. Note that also take call targets
885 // even if callee doesn't have a corresponding context profile.
886 if (!CalleeSample)
887 continue;
888
889 // If pre-inliner decision is used, honor that for importing as well.
890 bool PreInline =
891 UsePreInlinerDecision &&
893 if (!PreInline && CalleeSample->getHeadSamplesEstimate() < Threshold)
894 continue;
895
896 // A pre-inlined context can have no samples. Unlike an external one, a
897 // local definition is then not worth importing into other modules.
899 InlinedGUIDs, SymbolMap, CalleeSample->getFunction(),
900 IncludeLocalTargets && CalleeSample->getTotalSamples());
901
902 // Import hot CallTargets, which may not be available in IR because full
903 // profile annotation cannot be done until backend compilation in ThinLTO.
904 for (const auto &BS : CalleeSample->getBodySamples())
905 for (const auto &TS : BS.second.getCallTargets())
906 if (TS.second > Threshold)
907 FunctionSamples::addImportGUID(InlinedGUIDs, SymbolMap, TS.first,
908 IncludeLocalTargets);
909
910 // Import hot child context profile associted with callees. Note that this
911 // may have some overlap with the call target loop above, but doing this
912 // based child context profile again effectively allow us to use the max of
913 // entry count and call target count to determine importing.
914 for (auto &Child : Node->getAllChildContext()) {
915 ContextTrieNode *CalleeNode = &Child.second;
916 CalleeList.push(CalleeNode);
917 }
918 }
919}
920
921/// Iteratively inline hot callsites of a function.
922///
923/// Iteratively traverse all callsites of the function \p F, so as to
924/// find out callsites with corresponding inline instances.
925///
926/// For such callsites,
927/// - If it is hot enough, inline the callsites and adds callsites of the callee
928/// into the caller. If the call is an indirect call, first promote
929/// it to direct call. Each indirect call is limited with a single target.
930///
931/// - If a callsite is not inlined, merge the its profile to the outline
932/// version (if --sample-profile-merge-inlinee is true), or scale the
933/// counters of standalone function based on the profile of inlined
934/// instances (if --sample-profile-merge-inlinee is false).
935///
936/// Later passes may consume the updated profiles.
937///
938/// \param F function to perform iterative inlining.
939/// \param InlinedGUIDs a set to be updated to include all GUIDs that are
940/// inlined in the profiled binary.
941///
942/// \returns True if there is any inline happened.
943bool SampleProfileLoader::inlineHotFunctions(
944 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
945 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
946 // Profile symbol list is ignored when profile-sample-accurate is on.
947 assert((!ProfAccForSymsInList ||
948 (!Opts.profile_sample_accurate &&
949 !F.hasFnAttribute("profile-sample-accurate"))) &&
950 "ProfAccForSymsInList should be false when profile-sample-accurate "
951 "is enabled");
952
953 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
954 bool Changed = false;
955 bool LocalChanged = true;
956 while (LocalChanged) {
957 LocalChanged = false;
959 for (auto &BB : F) {
960 bool Hot = false;
961 SmallVector<CallBase *, 10> AllCandidates;
962 SmallVector<CallBase *, 10> ColdCandidates;
963 for (auto &I : BB) {
964 const FunctionSamples *FS = nullptr;
965 if (auto *CB = dyn_cast<CallBase>(&I)) {
966 if (!isa<IntrinsicInst>(I)) {
967 if ((FS = findCalleeFunctionSamples(*CB))) {
968 assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
969 "GUIDToFuncNameMap has to be populated");
970 AllCandidates.push_back(CB);
971 if (FS->getHeadSamplesEstimate() > 0 ||
973 LocalNotInlinedCallSites.insert({CB, FS});
974 if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
975 Hot = true;
976 else if (shouldInlineColdCallee(*CB))
977 ColdCandidates.push_back(CB);
978 } else if (getExternalInlineAdvisorShouldInline(*CB)) {
979 AllCandidates.push_back(CB);
980 }
981 }
982 }
983 }
984 if (Hot || ExternalInlineAdvisor) {
985 CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
986 emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
987 } else {
988 CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
989 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
990 }
991 }
992 for (CallBase *I : CIS) {
993 Function *CalledFunction = I->getCalledFunction();
994 InlineCandidate Candidate = {I, LocalNotInlinedCallSites.lookup(I),
995 0 /* dummy count */,
996 1.0 /* dummy distribution factor */};
997 // Do not inline recursive calls.
998 if (CalledFunction == &F)
999 continue;
1000 if (I->isIndirectCall()) {
1001 uint64_t Sum;
1002 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1003 uint64_t SumOrigin = Sum;
1004 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1005 findExternalInlineCandidate(I, FS, InlinedGUIDs,
1006 PSI->getOrCompHotCountThreshold());
1007 continue;
1008 }
1009 if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1010 continue;
1011
1012 Candidate = {I, FS, FS->getHeadSamplesEstimate(), 1.0};
1013 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1014 LocalNotInlinedCallSites.erase(I);
1015 LocalChanged = true;
1016 }
1017 }
1018 } else if (CalledFunction && CalledFunction->getSubprogram() &&
1019 !CalledFunction->isDeclaration()) {
1020 if (tryInlineCandidate(Candidate)) {
1021 LocalNotInlinedCallSites.erase(I);
1022 LocalChanged = true;
1023 }
1024 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1025 findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
1026 InlinedGUIDs,
1027 PSI->getOrCompHotCountThreshold());
1028 }
1029 }
1030 Changed |= LocalChanged;
1031 }
1032
1033 // For CS profile, profile for not inlined context will be merged when
1034 // base profile is being retrieved.
1036 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1037 return Changed;
1038}
1039
1040bool SampleProfileLoader::tryInlineCandidate(
1041 InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1042 // Do not attempt to inline a candidate if
1043 // --disable-sample-loader-inlining is true.
1044 if (DisableSampleProfileInlining)
1045 return false;
1046
1047 CallBase &CB = *Candidate.CallInstr;
1048 Function *CalledFunction = CB.getCalledFunction();
1049 assert(CalledFunction && "Expect a callee with definition");
1050 DebugLoc DLoc = CB.getDebugLoc();
1051 BasicBlock *BB = CB.getParent();
1052
1053 InlineCost Cost = shouldInlineCandidate(Candidate);
1054 if (Cost.isNever()) {
1055 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1056 "InlineFail", DLoc, BB)
1057 << "incompatible inlining");
1058 return false;
1059 }
1060
1061 if (!Cost)
1062 return false;
1063
1064 InlineFunctionInfo IFI(GetAC);
1065 IFI.UpdateProfile = false;
1066 InlineResult IR = InlineFunction(CB, IFI,
1067 /*MergeAttributes=*/true);
1068 if (!IR.isSuccess())
1069 return false;
1070
1071 // The call to InlineFunction erases I, so we can't pass it here.
1072 emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(),
1073 Cost, true, getAnnotatedRemarkPassName());
1074
1075 // Now populate the list of newly exposed call sites.
1076 if (InlinedCallSites) {
1077 InlinedCallSites->clear();
1078 llvm::append_range(*InlinedCallSites, IFI.InlinedCallSites);
1079 }
1080
1082 ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1083 ++NumCSInlined;
1084
1085 // Prorate inlined probes for a duplicated inlining callsite which probably
1086 // has a distribution less than 100%. Samples for an inlinee should be
1087 // distributed among the copies of the original callsite based on each
1088 // callsite's distribution factor for counts accuracy. Note that an inlined
1089 // probe may come with its own distribution factor if it has been duplicated
1090 // in the inlinee body. The two factor are multiplied to reflect the
1091 // aggregation of duplication.
1092 if (Candidate.CallsiteDistribution < 1) {
1093 for (auto &I : IFI.InlinedCallSites) {
1094 if (std::optional<PseudoProbe> Probe = extractProbe(*I))
1095 setProbeDistributionFactor(*I, Probe->Factor *
1096 Candidate.CallsiteDistribution);
1097 }
1098 NumDuplicatedInlinesite++;
1099 }
1100
1101 return true;
1102}
1103
1104bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1105 CallBase *CB) {
1106 assert(CB && "Expect non-null call instruction");
1107
1108 if (isa<IntrinsicInst>(CB))
1109 return false;
1110
1111 // Find the callee's profile. For indirect call, find hottest target profile.
1112 const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1113 // If ExternalInlineAdvisor wants to inline this site, do so even
1114 // if Samples are not present.
1115 if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
1116 return false;
1117
1118 float Factor = 1.0;
1119 if (std::optional<PseudoProbe> Probe = extractProbe(*CB))
1120 Factor = Probe->Factor;
1121
1122 uint64_t CallsiteCount =
1123 CalleeSamples ? CalleeSamples->getHeadSamplesEstimate() * Factor : 0;
1124 *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1125 return true;
1126}
1127
1128std::optional<InlineCost>
1129SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
1130 std::unique_ptr<InlineAdvice> Advice = nullptr;
1131 if (ExternalInlineAdvisor) {
1132 Advice = ExternalInlineAdvisor->getAdvice(CB);
1133 if (Advice) {
1134 if (!Advice->isInliningRecommended()) {
1135 Advice->recordUnattemptedInlining();
1136 return InlineCost::getNever("not previously inlined");
1137 }
1138 Advice->recordInlining();
1139 return InlineCost::getAlways("previously inlined");
1140 }
1141 }
1142
1143 return {};
1144}
1145
1146bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
1147 std::optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
1148 return Cost ? !!*Cost : false;
1149}
1150
1151InlineCost
1152SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1153 if (std::optional<InlineCost> ReplayCost =
1154 getExternalInlineAdvisorCost(*Candidate.CallInstr))
1155 return *ReplayCost;
1156 // Adjust threshold based on call site hotness, only do this for callsite
1157 // prioritized inliner because otherwise cost-benefit check is done earlier.
1158 int SampleThreshold = InlineOpts.ColdCallSiteThreshold;
1159 if (CallsitePrioritizedInline) {
1160 if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1161 SampleThreshold = InlineOpts.HotCallSiteThreshold;
1162 else if (!ProfileSizeInline)
1163 return InlineCost::getNever("cold callsite");
1164 }
1165
1166 Function *Caller = Candidate.CallInstr->getCaller();
1167 Function *Callee = Candidate.CallInstr->getCalledFunction();
1168 assert(Callee && "Expect a definition for inline candidate of direct call");
1169
1170 InlineParams Params = getInlineParams(Caller->getContext());
1171 // We will ignore the threshold from inline cost, so always get full cost.
1172 Params.ComputeFullInlineCost = true;
1173 Params.AllowRecursiveCall = AllowRecursiveInline;
1174 // Checks if there is anything in the reachable portion of the callee at
1175 // this callsite that makes this inlining potentially illegal. Need to
1176 // set ComputeFullInlineCost, otherwise getInlineCost may return early
1177 // when cost exceeds threshold without checking all IRs in the callee.
1178 // The acutal cost does not matter because we only checks isNever() to
1179 // see if it is legal to inline the callsite.
1180 InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1181 GetTTI(*Caller), GetAC, GetTLI);
1182
1183 // Honor always inline and never inline from call analyzer
1184 if (Cost.isNever() || Cost.isAlways())
1185 return Cost;
1186
1187 // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1188 // decisions based on hotness as well as accurate function byte sizes for
1189 // given context using function/inlinee sizes from previous build. It
1190 // stores the decision in profile, and also adjust/merge context profile
1191 // aiming at better context-sensitive post-inline profile quality, assuming
1192 // all inline decision estimates are going to be honored by compiler. Here
1193 // we replay that inline decision under `sample-profile-use-preinliner`.
1194 // Note that we don't need to handle negative decision from preinliner as
1195 // context profile for not inlined calls are merged by preinliner already.
1196 if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1197 // Once two node are merged due to promotion, we're losing some context
1198 // so the original context-sensitive preinliner decision should be ignored
1199 // for SyntheticContext.
1200 SampleContext &Context = Candidate.CalleeSamples->getContext();
1201 if (!Context.hasState(SyntheticContext) &&
1202 Context.hasAttribute(ContextShouldBeInlined))
1203 return InlineCost::getAlways("preinliner");
1204 }
1205
1206 // For old FDO inliner, we inline the call site if it is below hot threshold,
1207 // even if the function is hot based on sample profile data. This is to
1208 // prevent huge functions from being inlined.
1209 if (!CallsitePrioritizedInline) {
1210 return InlineCost::get(Cost.getCost(), InlineOpts.HotCallSiteThreshold);
1211 }
1212
1213 // Otherwise only use the cost from call analyzer, but overwite threshold with
1214 // Sample PGO threshold.
1215 return InlineCost::get(Cost.getCost(), SampleThreshold);
1216}
1217
1218bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1219 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1220 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1221 // Profile symbol list is ignored when profile-sample-accurate is on.
1222 assert((!ProfAccForSymsInList ||
1223 (!Opts.profile_sample_accurate &&
1224 !F.hasFnAttribute("profile-sample-accurate"))) &&
1225 "ProfAccForSymsInList should be false when profile-sample-accurate "
1226 "is enabled");
1227
1228 // Populating worklist with initial call sites from root inliner, along
1229 // with call site weights.
1230 CandidateQueue CQueue;
1231 InlineCandidate NewCandidate;
1232 for (auto &BB : F) {
1233 for (CallBase &CB : make_isa_range<CallBase>(BB)) {
1234 if (getInlineCandidate(&NewCandidate, &CB))
1235 CQueue.push(NewCandidate);
1236 }
1237 }
1238
1239 // Cap the size growth from profile guided inlining. This is needed even
1240 // though cost of each inline candidate already accounts for callee size,
1241 // because with top-down inlining, we can grow inliner size significantly
1242 // with large number of smaller inlinees each pass the cost check.
1243 assert(InlineOpts.LimitMax >= InlineOpts.LimitMin &&
1244 "Max inline size limit should not be smaller than min inline size "
1245 "limit.");
1246 unsigned SizeLimit = F.getInstructionCount() * InlineOpts.GrowthLimit;
1247 SizeLimit = std::min(SizeLimit, InlineOpts.LimitMax);
1248 SizeLimit = std::max(SizeLimit, InlineOpts.LimitMin);
1249 if (ExternalInlineAdvisor)
1250 SizeLimit = std::numeric_limits<unsigned>::max();
1251
1252 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1253
1254 // Perform iterative BFS call site prioritized inlining
1255 bool Changed = false;
1256 while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1257 InlineCandidate Candidate = CQueue.top();
1258 CQueue.pop();
1259 CallBase *I = Candidate.CallInstr;
1260 Function *CalledFunction = I->getCalledFunction();
1261
1262 if (CalledFunction == &F)
1263 continue;
1264 if (I->isIndirectCall()) {
1265 uint64_t Sum = 0;
1266 auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1267 uint64_t SumOrigin = Sum;
1268 Sum *= Candidate.CallsiteDistribution;
1269 unsigned ICPCount = 0;
1270 for (const auto *FS : CalleeSamples) {
1271 // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1272 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1273 findExternalInlineCandidate(I, FS, InlinedGUIDs,
1274 PSI->getOrCompHotCountThreshold());
1275 continue;
1276 }
1277 uint64_t EntryCountDistributed =
1278 FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
1279 // In addition to regular inline cost check, we also need to make sure
1280 // ICP isn't introducing excessive speculative checks even if individual
1281 // target looks beneficial to promote and inline. That means we should
1282 // only do ICP when there's a small number dominant targets.
1283 if (ICPCount >= Opts.sample_profile_icp_relative_hotness_skip &&
1284 EntryCountDistributed * 100 <
1285 SumOrigin * Opts.sample_profile_icp_relative_hotness)
1286 break;
1287 // TODO: Fix CallAnalyzer to handle all indirect calls.
1288 // For indirect call, we don't run CallAnalyzer to get InlineCost
1289 // before actual inlining. This is because we could see two different
1290 // types from the same definition, which makes CallAnalyzer choke as
1291 // it's expecting matching parameter type on both caller and callee
1292 // side. See example from PR18962 for the triggering cases (the bug was
1293 // fixed, but we generate different types).
1294 if (!PSI->isHotCount(EntryCountDistributed))
1295 break;
1296 SmallVector<CallBase *, 8> InlinedCallSites;
1297 // Attach function profile for promoted indirect callee, and update
1298 // call site count for the promoted inline candidate too.
1299 Candidate = {I, FS, EntryCountDistributed,
1300 Candidate.CallsiteDistribution};
1301 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1302 &InlinedCallSites)) {
1303 for (auto *CB : InlinedCallSites) {
1304 if (getInlineCandidate(&NewCandidate, CB))
1305 CQueue.emplace(NewCandidate);
1306 }
1307 ICPCount++;
1308 Changed = true;
1309 } else if (!ContextTracker) {
1310 LocalNotInlinedCallSites.insert({I, FS});
1311 }
1312 }
1313 } else if (CalledFunction && CalledFunction->getSubprogram() &&
1314 !CalledFunction->isDeclaration()) {
1315 SmallVector<CallBase *, 8> InlinedCallSites;
1316 if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1317 for (auto *CB : InlinedCallSites) {
1318 if (getInlineCandidate(&NewCandidate, CB))
1319 CQueue.emplace(NewCandidate);
1320 }
1321 Changed = true;
1322 } else if (!ContextTracker) {
1323 LocalNotInlinedCallSites.insert({I, Candidate.CalleeSamples});
1324 }
1325 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1326 findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
1327 InlinedGUIDs,
1328 PSI->getOrCompHotCountThreshold());
1329 }
1330 }
1331
1332 if (!CQueue.empty()) {
1333 if (SizeLimit == InlineOpts.LimitMax)
1334 ++NumCSInlinedHitMaxLimit;
1335 else if (SizeLimit == InlineOpts.LimitMin)
1336 ++NumCSInlinedHitMinLimit;
1337 else
1338 ++NumCSInlinedHitGrowthLimit;
1339 }
1340
1341 // For CS profile, profile for not inlined context will be merged when
1342 // base profile is being retrieved.
1344 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1345 return Changed;
1346}
1347
1348void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1349 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
1350 const Function &F) {
1351 // Accumulate not inlined callsite information into notInlinedSamples
1352 for (const auto &Pair : NonInlinedCallSites) {
1353 CallBase *I = Pair.first;
1354 Function *Callee = I->getCalledFunction();
1355 if (!Callee || Callee->isDeclaration())
1356 continue;
1357
1358 ORE->emit(
1359 OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
1360 I->getDebugLoc(), I->getParent())
1361 << "previous inlining not repeated: '" << ore::NV("Callee", Callee)
1362 << "' into '" << ore::NV("Caller", &F) << "'");
1363
1364 ++NumCSNotInlined;
1365 const FunctionSamples *FS = Pair.second;
1366 if (FS->getTotalSamples() == 0 && FS->getHeadSamplesEstimate() == 0) {
1367 continue;
1368 }
1369
1370 // Do not merge a context that is already duplicated into the base profile.
1371 if (FS->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase))
1372 continue;
1373
1374 if (ProfileMergeInlinee) {
1375 // A function call can be replicated by optimizations like callsite
1376 // splitting or jump threading and the replicates end up sharing the
1377 // sample nested callee profile instead of slicing the original
1378 // inlinee's profile. We want to do merge exactly once by filtering out
1379 // callee profiles with a non-zero head sample count.
1380 if (FS->getHeadSamples() == 0) {
1381 // Use entry samples as head samples during the merge, as inlinees
1382 // don't have head samples.
1383 const_cast<FunctionSamples *>(FS)->addHeadSamples(
1384 FS->getHeadSamplesEstimate());
1385
1386 // Note that we have to do the merge right after processing function.
1387 // This allows OutlineFS's profile to be used for annotation during
1388 // top-down processing of functions' annotation.
1389 FunctionSamples *OutlineFS = Reader->getSamplesFor(*Callee);
1390 // If outlined function does not exist in the profile, add it to a
1391 // separate map so that it does not rehash the original profile.
1392 if (!OutlineFS)
1393 OutlineFS = &OutlineFunctionSamples[
1394 FunctionId(FunctionSamples::getCanonicalFnName(Callee->getName()))];
1395 OutlineFS->merge(*FS, 1);
1396 // Set outlined profile to be synthetic to not bias the inliner.
1397 OutlineFS->setContextSynthetic();
1398 }
1399 } else {
1400 auto pair =
1401 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1402 pair.first->second.entryCount += FS->getHeadSamplesEstimate();
1403 }
1404 }
1405}
1406
1407/// Returns the sorted CallTargetMap \p M by count in descending order.
1411 for (const auto &I : SampleRecord::sortCallTargets(M)) {
1412 R.emplace_back(
1413 InstrProfValueData{I.first.getHashCode(), I.second});
1414 }
1415 return R;
1416}
1417
1418// Generate MD_prof metadata for every branch instruction using the
1419// edge weights computed during propagation.
1420void SampleProfileLoader::generateMDProfMetadata(Function &F) {
1421 // Generate MD_prof metadata for every branch instruction using the
1422 // edge weights computed during propagation.
1423 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1424 LLVMContext &Ctx = F.getContext();
1425 MDBuilder MDB(Ctx);
1426 for (auto &BI : F) {
1427 BasicBlock *BB = &BI;
1428
1429 if (BlockWeights[BB]) {
1430 for (auto &I : *BB) {
1431 if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1432 continue;
1434 const DebugLoc &DLoc = I.getDebugLoc();
1435 if (!DLoc)
1436 continue;
1437 const DILocation *DIL = DLoc;
1438 const FunctionSamples *FS = findFunctionSamples(I);
1439 if (!FS)
1440 continue;
1442 ErrorOr<SampleRecord::CallTargetMap> T =
1443 FS->findCallTargetMapAt(CallSite);
1444 if (!T || T.get().empty())
1445 continue;
1447 // Prorate the callsite counts based on the pre-ICP distribution
1448 // factor to reflect what is already done to the callsite before
1449 // ICP, such as calliste cloning.
1450 if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
1451 if (Probe->Factor < 1)
1452 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1453 }
1454 }
1455 SmallVector<InstrProfValueData, 2> SortedCallTargets =
1457 uint64_t Sum = 0;
1458 for (const auto &C : T.get())
1459 Sum += C.second;
1460 // With CSSPGO all indirect call targets are counted torwards the
1461 // original indirect call site in the profile, including both
1462 // inlined and non-inlined targets.
1464 if (const FunctionSamplesMap *M =
1465 FS->findFunctionSamplesMapAt(CallSite)) {
1466 for (const auto &NameFS : *M)
1467 Sum += NameFS.second.getHeadSamplesEstimate();
1468 }
1469 }
1470 if (Sum)
1471 updateIDTMetaData(Opts, I, SortedCallTargets, Sum);
1472 else if (Opts.overwrite_existing_weights)
1473 I.setMetadata(LLVMContext::MD_prof, nullptr);
1474 } else if (!isa<IntrinsicInst>(&I)) {
1476 I, ArrayRef<uint32_t>{static_cast<uint32_t>(BlockWeights[BB])},
1477 /*IsExpected=*/false);
1478 }
1479 }
1480 } else if (Opts.overwrite_existing_weights ||
1481 Opts.profile_sample_block_accurate) {
1482 // Set profile metadata (possibly annotated by LTO prelink) to zero or
1483 // clear it for cold code.
1484 for (auto &I : *BB) {
1485 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1487 I.setMetadata(LLVMContext::MD_prof, nullptr);
1488 } else {
1489 setBranchWeights(I, ArrayRef<uint32_t>{uint32_t(0)},
1490 /*IsExpected=*/false);
1491 }
1492 }
1493 }
1494 }
1495
1496 Instruction *TI = BB->getTerminator();
1497 if (TI->getNumSuccessors() == 1)
1498 continue;
1499 if (!isa<CondBrInst>(TI) && !isa<SwitchInst>(TI) &&
1501 continue;
1502
1503 DebugLoc BranchLoc = TI->getDebugLoc();
1504 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1505 << ((BranchLoc) ? Twine(BranchLoc.getLine())
1506 : Twine("<UNKNOWN LOCATION>"))
1507 << ".\n");
1508 SmallVector<uint32_t, 4> Weights;
1509 uint32_t MaxWeight = 0;
1510 Instruction *MaxDestInst;
1511 // Since profi treats multiple edges (multiway branches) as a single edge,
1512 // we need to distribute the computed weight among the branches. We do
1513 // this by evenly splitting the edge weight among destinations.
1514 DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
1515 std::vector<uint64_t> EdgeIndex;
1517 EdgeIndex.resize(TI->getNumSuccessors());
1518 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1519 const BasicBlock *Succ = TI->getSuccessor(I);
1520 EdgeIndex[I] = EdgeMultiplicity[Succ];
1521 EdgeMultiplicity[Succ]++;
1522 }
1523 }
1524 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1525 BasicBlock *Succ = TI->getSuccessor(I);
1526 Edge E = std::make_pair(BB, Succ);
1527 uint64_t Weight = EdgeWeights[E];
1528 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1529 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1530 // if needed. Sample counts in profiles are 64-bit unsigned values,
1531 // but internally branch weights are expressed as 32-bit values.
1532 if (Weight > std::numeric_limits<uint32_t>::max()) {
1533 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)\n");
1534 Weight = std::numeric_limits<uint32_t>::max();
1535 }
1536 if (!SampleProfileUseProfi) {
1537 // Weight is added by one to avoid propagation errors introduced by
1538 // 0 weights.
1539 Weights.push_back(static_cast<uint32_t>(
1540 Weight == std::numeric_limits<uint32_t>::max() ? Weight
1541 : Weight + 1));
1542 } else {
1543 // Profi creates proper weights that do not require "+1" adjustments but
1544 // we evenly split the weight among branches with the same destination.
1545 uint64_t W = Weight / EdgeMultiplicity[Succ];
1546 // Rounding up, if needed, so that first branches are hotter.
1547 if (EdgeIndex[I] < Weight % EdgeMultiplicity[Succ])
1548 W++;
1549 Weights.push_back(static_cast<uint32_t>(W));
1550 }
1551 if (Weight != 0) {
1552 if (Weight > MaxWeight) {
1553 MaxWeight = Weight;
1554 MaxDestInst = &*Succ->getFirstNonPHIOrLifetime();
1555 }
1556 }
1557 }
1558
1559 misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
1560
1561 uint64_t TempWeight;
1562 // Only set weights if there is at least one non-zero weight.
1563 // In any other case, let the analyzer set weights.
1564 // Do not set weights if the weights are present unless under
1565 // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1566 // twice. If the first annotation already set the weights, the second pass
1567 // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1568 // weight should have their existing metadata (possibly annotated by LTO
1569 // prelink) cleared.
1570 if (MaxWeight > 0 && (!TI->extractProfTotalWeight(TempWeight) ||
1571 Opts.overwrite_existing_weights)) {
1572 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1573 setBranchWeights(*TI, Weights, /*IsExpected=*/false);
1574 ORE->emit([&]() {
1575 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1576 << "most popular destination for conditional branches at "
1577 << ore::NV("CondBranchesLoc", BranchLoc);
1578 });
1579 } else {
1580 if (Opts.overwrite_existing_weights) {
1581 TI->setMetadata(LLVMContext::MD_prof, nullptr);
1582 LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1583 } else {
1584 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1585 }
1586 }
1587 }
1588}
1589
1590/// Once all the branch weights are computed, we emit the MD_prof
1591/// metadata on BB using the computed values for each of its branches.
1592///
1593/// \param F The function to query.
1594///
1595/// \returns true if \p F was modified. Returns false, otherwise.
1596bool SampleProfileLoader::emitAnnotations(Function &F) {
1597 bool Changed = false;
1598
1600 LLVM_DEBUG({
1601 if (!ProbeManager->getDesc(F))
1602 dbgs() << "Probe descriptor missing for Function " << F.getName()
1603 << "\n";
1604 });
1605
1606 if (ProbeManager->profileIsValid(F, *Samples)) {
1607 ++NumMatchedProfile;
1608 } else {
1609 ++NumMismatchedProfile;
1610 LLVM_DEBUG(
1611 dbgs() << "Profile is invalid due to CFG mismatch for Function "
1612 << F.getName() << "\n");
1613 if (!SalvageStaleProfile)
1614 return false;
1615 }
1616 } else {
1617 if (getFunctionLoc(F) == 0)
1618 return false;
1619
1620 LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1621 << F.getName() << ": " << getFunctionLoc(F) << "\n");
1622 }
1623
1624 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1625 if (CallsitePrioritizedInline)
1626 Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1627 else
1628 Changed |= inlineHotFunctions(F, InlinedGUIDs);
1629
1630 Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
1631
1632 if (Changed)
1633 generateMDProfMetadata(F);
1634
1635 emitCoverageRemarks(F);
1636 return Changed;
1637}
1638
1639std::unique_ptr<ProfiledCallGraph>
1640SampleProfileLoader::buildProfiledCallGraph(Module &M) {
1641 std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1643 ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1644 else
1645 ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1646
1647 // Add all functions into the profiled call graph even if they are not in
1648 // the profile. This makes sure functions missing from the profile still
1649 // gets a chance to be processed.
1650 for (Function &F : M) {
1652 continue;
1653 ProfiledCG->addProfiledFunction(
1655 }
1656
1657 return ProfiledCG;
1658}
1659
1660std::vector<Function *>
1661SampleProfileLoader::buildFunctionOrder(Module &M, LazyCallGraph &CG) {
1662 std::vector<Function *> FunctionOrderList;
1663 FunctionOrderList.reserve(M.size());
1664
1665 if (!Opts.sample_profile_top_down_load && Opts.use_profiled_call_graph)
1666 errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1667 "together with -sample-profile-top-down-load.\n";
1668
1669 if (!Opts.sample_profile_top_down_load) {
1670 if (ProfileMergeInlinee) {
1671 // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1672 // because the profile for a function may be used for the profile
1673 // annotation of its outline copy before the profile merging of its
1674 // non-inlined inline instances, and that is not the way how
1675 // ProfileMergeInlinee is supposed to work.
1676 ProfileMergeInlinee = false;
1677 }
1678
1679 for (Function &F : M)
1681 FunctionOrderList.push_back(&F);
1682 return FunctionOrderList;
1683 }
1684
1685 if (Opts.use_profiled_call_graph) {
1686 // Use profiled call edges to augment the top-down order. There are cases
1687 // that the top-down order computed based on the static call graph doesn't
1688 // reflect real execution order. For example
1689 //
1690 // 1. Incomplete static call graph due to unknown indirect call targets.
1691 // Adjusting the order by considering indirect call edges from the
1692 // profile can enable the inlining of indirect call targets by allowing
1693 // the caller processed before them.
1694 // 2. Mutual call edges in an SCC. The static processing order computed for
1695 // an SCC may not reflect the call contexts in the context-sensitive
1696 // profile, thus may cause potential inlining to be overlooked. The
1697 // function order in one SCC is being adjusted to a top-down order based
1698 // on the profile to favor more inlining. This is only a problem with CS
1699 // profile.
1700 // 3. Transitive indirect call edges due to inlining. When a callee function
1701 // (say B) is inlined into a caller function (say A) in LTO prelink,
1702 // every call edge originated from the callee B will be transferred to
1703 // the caller A. If any transferred edge (say A->C) is indirect, the
1704 // original profiled indirect edge B->C, even if considered, would not
1705 // enforce a top-down order from the caller A to the potential indirect
1706 // call target C in LTO postlink since the inlined callee B is gone from
1707 // the static call graph.
1708 // 4. #3 can happen even for direct call targets, due to functions defined
1709 // in header files. A header function (say A), when included into source
1710 // files, is defined multiple times but only one definition survives due
1711 // to ODR. Therefore, the LTO prelink inlining done on those dropped
1712 // definitions can be useless based on a local file scope. More
1713 // importantly, the inlinee (say B), once fully inlined to a
1714 // to-be-dropped A, will have no profile to consume when its outlined
1715 // version is compiled. This can lead to a profile-less prelink
1716 // compilation for the outlined version of B which may be called from
1717 // external modules. while this isn't easy to fix, we rely on the
1718 // postlink AutoFDO pipeline to optimize B. Since the survived copy of
1719 // the A can be inlined in its local scope in prelink, it may not exist
1720 // in the merged IR in postlink, and we'll need the profiled call edges
1721 // to enforce a top-down order for the rest of the functions.
1722 //
1723 // Considering those cases, a profiled call graph completely independent of
1724 // the static call graph is constructed based on profile data, where
1725 // function objects are not even needed to handle case #3 and case 4.
1726 //
1727 // Note that static callgraph edges are completely ignored since they
1728 // can be conflicting with profiled edges for cyclic SCCs and may result in
1729 // an SCC order incompatible with profile-defined one. Using strictly
1730 // profile order ensures a maximum inlining experience. On the other hand,
1731 // static call edges are not so important when they don't correspond to a
1732 // context in the profile.
1733
1734 std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(M);
1735 scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1736 while (!CGI.isAtEnd()) {
1737 auto Range = *CGI;
1738 if (InlineOpts.SortProfiledSCC) {
1739 // Sort nodes in one SCC based on callsite hotness.
1740 scc_member_iterator<ProfiledCallGraph *> SI(*CGI);
1741 Range = *SI;
1742 }
1743 for (auto *Node : Range) {
1744 // MemProf clones share the profiled call graph node of their original
1745 // function. Push them in reverse before F so that after reversing
1746 // FunctionOrderList, F is processed first followed by its clones in
1747 // module order.
1748 if (auto It = MemProfClones.find(Node->Name); It != MemProfClones.end())
1749 for (Function *Clone : reverse(It->second))
1750 FunctionOrderList.push_back(Clone);
1751 Function *F = SymbolMap.lookup(Node->Name);
1752 if (F && !skipProfileForFunction(*F))
1753 FunctionOrderList.push_back(F);
1754 }
1755 ++CGI;
1756 }
1757 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1758 } else
1759 buildTopDownFuncOrder(CG, FunctionOrderList);
1760
1761 LLVM_DEBUG({
1762 dbgs() << "Function processing order:\n";
1763 for (auto F : FunctionOrderList) {
1764 dbgs() << F->getName() << "\n";
1765 }
1766 });
1767
1768 return FunctionOrderList;
1769}
1770
1771bool SampleProfileLoader::doInitialization(Module &M,
1773 auto &Ctx = M.getContext();
1774 InlineOpts =
1776
1777 auto ReaderOrErr = SampleProfileReader::create(
1778 Filename, Ctx, *FS, FSDiscriminatorPass::Base, RemappingFilename);
1779 if (std::error_code EC = ReaderOrErr.getError()) {
1780 std::string Msg = "Could not open profile: " + EC.message();
1781 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1782 return false;
1783 }
1784 Reader = std::move(ReaderOrErr.get());
1785 Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1786 // set module before reading the profile so reader may be able to only
1787 // read the function profiles which are used by the current module.
1788 Reader->setModule(&M);
1789 if (std::error_code EC = Reader->read()) {
1790 std::string Msg = "profile reading failed: " + EC.message();
1791 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1792 return false;
1793 }
1794
1795 PSL = Reader->getProfileSymbolList();
1796
1797 DisableSampleProfileInlining =
1798 !valueOr(Opts.sample_loader_inlining, !DisableSampleProfileInlining);
1799
1800 if (UseFlattenedProfile)
1801 ProfileConverter::flattenProfile(Reader->getProfiles(),
1802 Reader->profileIsCS());
1803
1804 // While profile-sample-accurate is on, ignore symbol list.
1805 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL &&
1806 !Opts.profile_sample_accurate;
1807 if (ProfAccForSymsInList)
1808 CoverageTracker.setProfAccForSymsInList(true);
1809
1810 if (FAM && !Opts.sample_profile_inline_replay.empty()) {
1811 ExternalInlineAdvisor = getReplayInlineAdvisor(
1812 M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr,
1813 ReplayInlinerSettings{Opts.sample_profile_inline_replay,
1814 Opts.sample_profile_inline_replay_scope,
1815 Opts.sample_profile_inline_replay_fallback,
1816 {Opts.sample_profile_inline_replay_format}},
1817 /*EmitRemarks=*/false,
1818 InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
1819 }
1820
1821 // Apply tweaks if context-sensitive or probe-based profile is available.
1822 if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
1823 Reader->profileIsProbeBased()) {
1827 SampleProfileUseProfi = true;
1830 // Enable priority-base inliner and size inline by default for CSSPGO.
1831 ProfileSizeInline = valueOr(Opts.sample_profile_inline_size, true);
1832 CallsitePrioritizedInline =
1833 valueOr(Opts.sample_profile_prioritized_inline, true);
1834 // For CSSPGO, we also allow recursive inline to best use context profile.
1835 AllowRecursiveInline = valueOr(Opts.sample_profile_recursive_inline, true);
1836
1837 if (Reader->profileIsPreInlined())
1838 UsePreInlinerDecision = valueOr(Opts.sample_profile_use_preinliner, true);
1839
1840 // Enable stale profile matching by default for probe-based profile.
1841 // Currently the matching relies on if the checksum mismatch is detected,
1842 // which is currently only available for pseudo-probe mode. Removing the
1843 // checksum check could cause regressions for some cases, so further tuning
1844 // might be needed if we want to enable it for all cases.
1845 if (Reader->profileIsProbeBased()) {
1846 SalvageStaleProfile = valueOr(Opts.salvage_stale_profile, true);
1847 SalvageUnusedProfile = valueOr(Opts.salvage_unused_profile, true);
1848 }
1849
1850 if (!Reader->profileIsCS()) {
1851 // Non-CS profile should be fine without a function size budget for the
1852 // inliner since the contexts in the profile are either all from inlining
1853 // in the prevoius build or pre-computed by the preinliner with a size
1854 // cap, thus they are bounded.
1855 InlineOpts.LimitMin = Opts.sample_profile_inline_limit_min.value_or(
1856 std::numeric_limits<unsigned>::max());
1857 InlineOpts.LimitMax =
1858 std::max(Opts.sample_profile_inline_limit_max.value_or(
1859 std::numeric_limits<unsigned>::max()),
1860 InlineOpts.LimitMin);
1861 }
1862 }
1863
1864 if (Reader->profileIsCS()) {
1865 // Tracker for profiles under different context
1866 ContextTracker = std::make_unique<SampleContextTracker>(
1867 Reader->getProfiles(), &GUIDToFuncNameMap);
1868 }
1869
1870 // Load pseudo probe descriptors for probe-based function samples.
1871 if (Reader->profileIsProbeBased()) {
1872 ProbeManager = std::make_unique<PseudoProbeManager>(M);
1873 if (!ProbeManager->moduleIsProbed(M)) {
1874 const char *Msg =
1875 "Pseudo-probe-based profile requires SampleProfileProbePass";
1876 Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg,
1877 DS_Warning));
1878 return false;
1879 }
1880 }
1881
1882 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
1883 SalvageStaleProfile) {
1884 MatchingManager = std::make_unique<SampleProfileMatcher>(
1885 Opts, M, *Reader, CG, ProbeManager.get(), LTOPhase, SymbolMap, PSL,
1886 FuncNameToProfNameMap, SalvageStaleProfile, SalvageUnusedProfile);
1887 }
1888
1889 return true;
1890}
1891
1892// Note that this is a module-level check. Even if one module is errored out,
1893// the entire build will be errored out. However, the user could make big
1894// changes to functions in single module but those changes might not be
1895// performance significant to the whole binary. Therefore, to avoid those false
1896// positives, we select a reasonable big set of hot functions that are supposed
1897// to be globally performance significant, only compute and check the mismatch
1898// within those functions. The function selection is based on two criteria:
1899// 1) The function is hot enough, which is tuned by a hotness-based
1900// flag(HotFuncCutoffForStalenessError). 2) The num of function is large enough
1901// which is tuned by the MinfuncsForStalenessError flag.
1902bool SampleProfileLoader::rejectHighStalenessProfile(
1903 Module &M, ProfileSummaryInfo *PSI, const SampleProfileMap &Profiles) {
1905 "Only support for probe-based profile");
1906 uint64_t TotalHotFunc = 0;
1907 uint64_t NumMismatchedFunc = 0;
1908 for (const auto &I : Profiles) {
1909 const auto &FS = I.second;
1910 const auto *FuncDesc = ProbeManager->getDesc(FS.getGUID());
1911 if (!FuncDesc)
1912 continue;
1913
1914 // Use a hotness-based threshold to control the function selection.
1915 if (!PSI->isHotCountNthPercentile(Opts.hot_func_cutoff_for_staleness_error,
1916 FS.getTotalSamples()))
1917 continue;
1918
1919 TotalHotFunc++;
1920 if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS) &&
1921 !ProbeManager->probeFromWeakSymbol(FS.getGUID()))
1922 NumMismatchedFunc++;
1923 }
1924 // Make sure that the num of selected function is not too small to distinguish
1925 // from the user's benign changes.
1926 if (TotalHotFunc < Opts.min_functions_for_staleness_error)
1927 return false;
1928
1929 // Finally check the mismatch percentage against the threshold.
1930 if (NumMismatchedFunc * 100 >=
1931 TotalHotFunc * Opts.percent_mismatch_for_staleness_error) {
1932 auto &Ctx = M.getContext();
1933 const char *Msg =
1934 "The input profile significantly mismatches current source code. "
1935 "Please recollect profile to avoid performance regression.";
1936 Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg));
1937 return true;
1938 }
1939 return false;
1940}
1941
1942void SampleProfileLoader::removePseudoProbeInstsDiscriminator(Module &M) {
1943 for (auto &F : M) {
1944 std::vector<Instruction *> InstsToDel;
1945 for (auto &BB : F) {
1946 for (auto &I : BB) {
1947 if (isa<PseudoProbeInst>(&I))
1948 InstsToDel.push_back(&I);
1949 else if (isa<CallBase>(&I))
1950 if (const DILocation *DIL = I.getDebugLoc().get()) {
1951 // Restore dwarf discriminator for call.
1952 unsigned Discriminator = DIL->getDiscriminator();
1953 if (DILocation::isPseudoProbeDiscriminator(Discriminator)) {
1954 std::optional<uint32_t> DwarfDiscriminator =
1956 Discriminator);
1957 I.setDebugLoc(
1958 DIL->cloneWithDiscriminator(DwarfDiscriminator.value_or(0)));
1959 }
1960 }
1961 }
1962 }
1963 for (auto *I : InstsToDel)
1964 I->eraseFromParent();
1965 }
1966}
1967
1968bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager &AM,
1969 ProfileSummaryInfo *_PSI) {
1970 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1971
1972 PSI = _PSI;
1973 if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
1974 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
1976 PSI->refresh();
1977 }
1978
1980 rejectHighStalenessProfile(M, PSI, Reader->getProfiles()))
1981 return false;
1982
1983 auto Remapper = Reader->getRemapper();
1984 // Populate the symbol map.
1985 for (const auto &N_F : M.getValueSymbolTable()) {
1986 StringRef OrigName = N_F.getKey();
1987 Function *F = dyn_cast<Function>(N_F.getValue());
1988 if (F == nullptr || OrigName.empty())
1989 continue;
1990 SymbolMap[FunctionId(OrigName)] = F;
1991 // A MemProf clone has the same stripped name as its original function.
1992 // Mapping that name to the clone too would mark it as ambiguous and hide
1993 // the original, so only the original gets the stripped name entries.
1994 if (isMemProfClone(*F))
1995 continue;
1996 StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
1997 if (OrigName != NewName && !NewName.empty()) {
1998 auto r = SymbolMap.emplace(FunctionId(NewName), F);
1999 // Failiing to insert means there is already an entry in SymbolMap,
2000 // thus there are multiple functions that are mapped to the same
2001 // stripped name. In this case of name conflicting, set the value
2002 // to nullptr to avoid confusion.
2003 if (!r.second)
2004 r.first->second = nullptr;
2005 OrigName = NewName;
2006 }
2007 // Insert the remapped names into SymbolMap.
2008 if (Remapper) {
2009 if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2010 if (*MapName != OrigName && !MapName->empty())
2011 SymbolMap.emplace(FunctionId(*MapName), F);
2012 }
2013 }
2014 }
2015
2016 // Record MemProf clones in module order, keyed by their canonical (or
2017 // remapped) profile name so buildFunctionOrder schedules them with their
2018 // profiled call graph node even if the original function was renamed
2019 // (e.g. .cfi) or is not defined in this module.
2020 for (Function &F : M) {
2022 continue;
2024 if (Name.empty() || Name == F.getName())
2025 continue;
2026 if (Remapper) {
2027 if (auto MapName = Remapper->lookUpNameInProfile(Name)) {
2028 if (!MapName->empty())
2029 Name = *MapName;
2030 }
2031 }
2032 MemProfClones[FunctionId(Name)].push_back(&F);
2033 }
2034
2035 // Stale profile matching.
2036 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
2037 SalvageStaleProfile) {
2038 MatchingManager->runOnModule();
2039 MatchingManager->clearMatchingData();
2040 }
2041 assert(SymbolMap.count(FunctionId()) == 0 &&
2042 "No empty StringRef should be added in SymbolMap");
2043 assert((SalvageUnusedProfile || FuncNameToProfNameMap.empty()) &&
2044 "FuncNameToProfNameMap is not empty when --salvage-unused-profile is "
2045 "not enabled");
2046
2047 bool retval = false;
2048 for (auto *F : buildFunctionOrder(M, CG)) {
2049 assert(!F->isDeclaration());
2050 clearFunctionData();
2051 retval |= runOnFunction(*F, AM);
2052 }
2053
2054 // Account for cold calls not inlined....
2056 for (const auto &[Fn, Info] : notInlinedCallInfo)
2057 updateProfileCallee(Fn, Info.entryCount);
2058
2059 if (Opts.sample_profile_remove_probe &&
2061 removePseudoProbeInstsDiscriminator(M);
2062 if (auto *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName))
2063 M.eraseNamedMetadata(FuncInfo);
2064 }
2065
2066 return retval;
2067}
2068
2069bool SampleProfileLoader::runOnFunction(Function &F,
2071 LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
2072 DILocation2SampleMap.clear();
2073 // By default the entry count is initialized to -1, which will be treated
2074 // conservatively by getEntryCount as the same as unknown (None). This is
2075 // to avoid newly added code to be treated as cold. If we have samples
2076 // this will be overwritten in emitAnnotations.
2077 uint64_t initialEntryCount = -1;
2078
2079 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL;
2080 if (Opts.profile_sample_accurate ||
2081 F.hasFnAttribute("profile-sample-accurate")) {
2082 // initialize all the function entry counts to 0. It means all the
2083 // functions without profile will be regarded as cold.
2084 initialEntryCount = 0;
2085 // profile-sample-accurate is a user assertion which has a higher precedence
2086 // than symbol list. When profile-sample-accurate is on, ignore symbol list.
2087 ProfAccForSymsInList = false;
2088 }
2089 CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
2090
2091 // PSL -- profile symbol list include all the symbols in sampled binary.
2092 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
2093 // old functions without samples being cold, without having to worry
2094 // about new and hot functions being mistakenly treated as cold.
2095 if (ProfAccForSymsInList) {
2096 // Initialize the entry count to 0 for functions in the list.
2097 if (PSL->contains(F.getName()))
2098 initialEntryCount = 0;
2099
2100 // Function in the symbol list but without sample will be regarded as
2101 // cold. To minimize the potential negative performance impact it could
2102 // have, we want to be a little conservative here saying if a function
2103 // shows up in the profile, no matter as outline function, inline instance
2104 // or call targets, treat the function as not being cold. This will handle
2105 // the cases such as most callsites of a function are inlined in sampled
2106 // binary but not inlined in current build (because of source code drift,
2107 // imprecise debug information, or the callsites are all cold individually
2108 // but not cold accumulatively...), so the outline function showing up as
2109 // cold in sampled binary will actually not be cold after current build.
2110 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2112 ? Reader->contains(
2113 Function::getGUIDAssumingExternalLinkage(CanonName))
2114 : Reader->contains(CanonName))
2115 initialEntryCount = -1;
2116 }
2117
2118 // Initialize entry count when the function has no existing entry
2119 // count value.
2120 if (!F.getEntryCount())
2121 F.setEntryCount(initialEntryCount);
2122 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
2123 .getManager();
2124 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2125
2127 Samples = ContextTracker->getBaseSamplesFor(F);
2128 else {
2129 Samples = Reader->getSamplesFor(F);
2130 // Try search in previously inlined functions that were split or duplicated
2131 // into base.
2132 if (!Samples) {
2133 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2134 auto It = OutlineFunctionSamples.find(FunctionId(CanonName));
2135 if (It != OutlineFunctionSamples.end()) {
2136 Samples = &It->second;
2137 } else if (auto Remapper = Reader->getRemapper()) {
2138 if (auto RemppedName = Remapper->lookUpNameInProfile(CanonName)) {
2139 It = OutlineFunctionSamples.find(FunctionId(*RemppedName));
2140 if (It != OutlineFunctionSamples.end())
2141 Samples = &It->second;
2142 }
2143 }
2144 }
2145 }
2146
2147 if (Samples && !Samples->empty())
2148 return emitAnnotations(F);
2149 return false;
2150}
2154
2157 SampleProfileInlineOptions Defaults) {
2158 const auto &Opts = C.get<IPOOptions>();
2159 Defaults.HotCallSiteThreshold =
2160 Opts.sample_profile_hot_inline_threshold.value_or(
2161 Defaults.HotCallSiteThreshold);
2162 Defaults.ColdCallSiteThreshold =
2163 Opts.sample_profile_cold_inline_threshold.value_or(
2164 Defaults.ColdCallSiteThreshold);
2165 Defaults.GrowthLimit =
2166 Opts.sample_profile_inline_growth_limit.value_or(Defaults.GrowthLimit);
2167 Defaults.LimitMin =
2168 Opts.sample_profile_inline_limit_min.value_or(Defaults.LimitMin);
2169 Defaults.LimitMax =
2170 Opts.sample_profile_inline_limit_max.value_or(Defaults.LimitMax);
2171 Defaults.SortProfiledSCC =
2172 valueOr(Opts.sort_profiled_scc_member, Defaults.SortProfiledSCC);
2173 return Defaults;
2174}
2175
2177 std::string File, std::string RemappingFile, ThinOrFullLTOPhase LTOPhase,
2178 IntrusiveRefCntPtr<vfs::FileSystem> FS, bool DisableSampleProfileInlining,
2179 bool UseFlattenedProfile)
2180 : ProfileFileName(File), ProfileRemappingFileName(RemappingFile),
2181 LTOPhase(LTOPhase), FS(std::move(FS)),
2182 DisableSampleProfileInlining(DisableSampleProfileInlining),
2183 UseFlattenedProfile(UseFlattenedProfile) {}
2184
2189
2190 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2191 return FAM.getResult<AssumptionAnalysis>(F);
2192 };
2193 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
2194 return FAM.getResult<TargetIRAnalysis>(F);
2195 };
2196 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2197 return FAM.getResult<TargetLibraryAnalysis>(F);
2198 };
2199
2200 if (!FS)
2203
2204 const IPOOptions &Opts = getIPOOptions(M);
2205 SampleProfileLoader SampleLoader(
2206 Opts,
2207 ProfileFileName.empty() ? Opts.sample_profile_file
2208 : StringRef(ProfileFileName),
2209 ProfileRemappingFileName.empty() ? Opts.sample_profile_remapping_file
2210 : StringRef(ProfileRemappingFileName),
2211 LTOPhase, FS, GetAssumptionCache, GetTTI, GetTLI, CG,
2212 DisableSampleProfileInlining, UseFlattenedProfile);
2213 if (!SampleLoader.doInitialization(M, &FAM))
2214 return PreservedAnalyses::all();
2215
2217 if (!SampleLoader.runOnModule(M, AM, PSI))
2218 return PreservedAnalyses::all();
2219
2220 return PreservedAnalyses::none();
2221}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Function Alias Analysis false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static bool runOnFunction(Function &F, bool PostInlining)
Provides ErrorOr<T> smart pointer.
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static LVReader * CurrentReader
Definition LVReader.cpp:179
Implements a lazy call graph analysis and related passes for the new pass manager.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
static const Function * getCalledFunction(const MachineInstr &MI)
This file implements a map that provides insertion order iteration.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static constexpr StringLiteral Filename
FunctionAnalysisManager FAM
This file defines the PriorityQueue class.
This file contains the declarations for profiling metadata utility functions.
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
const char * Msg
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file provides the interface for context-sensitive profile tracker used by CSSPGO.
This file provides the interface for the sampled PGO profile loader base implementation.
This file provides the utility functions for the sampled PGO loader base implementation.
This file provides the interface for SampleProfileMatcher.
This file provides the interface for the pseudo probe implementation for AutoFDO.
static void updateIDTMetaData(const IPOOptions &Opts, Instruction &Inst, const SmallVectorImpl< InstrProfValueData > &CallTargets, uint64_t Sum)
Update indirect call target profile metadata for Inst.
static bool doesHistoryAllowICP(const IPOOptions &Opts, const Instruction &Inst, StringRef Candidate)
Check whether the indirect call promotion history of Inst allows the promotion for Candidate.
static SmallVector< InstrProfValueData, 2 > GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M)
Returns the sorted CallTargetMap M by count in descending order.
#define CSINLINE_DEBUG
This file provides the interface for the sampled PGO loader pass.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
bool empty() const
Returns true if the analysis manager has an empty results cache.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
static bool isPseudoProbeDiscriminator(unsigned Discriminator)
const DILocation * cloneWithDiscriminator(unsigned Discriminator) const
Returns a new DILocation with updated Discriminator.
A debug info location.
Definition DebugLoc.h:126
LLVM_ABI unsigned getLine() const
Definition DebugLoc.cpp:43
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Represents either an error or a value T.
Definition ErrorOr.h:56
DISubprogram * getSubprogram() const
Get the attached subprogram.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
static InlineCost getNever(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:135
static InlineCost getAlways(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
Definition InlineCost.h:130
static InlineCost get(int Cost, int Threshold, int StaticBonus=0)
Definition InlineCost.h:124
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
An analysis pass which computes the call graph for a module.
A lazily constructed view of the call graph of a module.
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:111
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:211
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI void refresh(std::unique_ptr< ProfileSummary > &&Other=nullptr)
If a summary is provided as argument, use that.
LLVM_ABI bool isHotCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered hot with regard to a given hot percentile cutoff value.
void computeDominanceAndLoopInfo(FunctionT &F)
static LLVM_ABI SampleProfileInlineOptions getInlineOptions(const cl::LibraryOptionsContext &C, SampleProfileInlineOptions Defaults)
Return Defaults overridden by the inliner options given in C.
static LLVM_ABI StringRef getSampleProfileFile(const LLVMContext &C)
Return -sample-profile-file.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI SampleProfileLoaderPass(std::string File="", std::string RemappingFile="", ThinOrFullLTOPhase LTOPhase=ThinOrFullLTOPhase::None, IntrusiveRefCntPtr< vfs::FileSystem > FS=nullptr, bool DisableSampleProfileInlining=false, bool UseFlattenedProfile=false)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
size_type size() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
const ParentTy * getParent() const
Definition ilist_node.h:34
Representation of the samples collected for a function.
Definition SampleProf.h:854
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, uint64_t Threshold, bool IncludeLocalTargets=false) const
Recursively collect import GUIDs from contexts with total samples greater than Threshold,...
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
FunctionId getFunction() const
Return the function name.
SampleContext & getContext() const LLVM_LIFETIME_BOUND
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
static void addImportGUID(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, FunctionId Name, bool IncludeLocal)
Add the import GUID of profiled function Name to S.
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
const BodySampleMap & getBodySamples() const LLVM_LIFETIME_BOUND
Return all the samples collected in the body of the function.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
static LLVM_ABI std::atomic< bool > ProfileIsCS
static LLVM_ABI LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
uint64_t getHeadSamplesEstimate() const
Return an estimate of the sample count of the function entry basic block.
uint64_t getGUID() const
Return the GUID of the context's name.
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
bool hasAttribute(ContextAttributeMask A)
Definition SampleProf.h:717
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
static SortedCallTargetSet sortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
Definition SampleProf.h:509
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
Definition SampleProf.h:516
SortedVectorMap< FunctionId, uint64_t, 0 > CallTargetMap
Definition SampleProf.h:436
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI void checkExpectAnnotations(const Instruction &I, ArrayRef< uint32_t > ExistingWeights, bool IsFrontend)
checkExpectAnnotations - compares PGO counters to the thresholds used for llvm.expect and warns if th...
DiagnosticInfoOptimizationBase::Argument NV
LLVM_ABI CallBase & promoteIndirectCall(CallBase &CB, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:844
LLVM_ABI bool callsiteIsHot(const FunctionSamples *CallsiteFS, ProfileSummaryInfo *PSI, bool ProfAccForSymsInList)
Return true if the given callsite is hot wrt to hot cutoff threshold.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
static bool isIndirectCall(const MachineInstr &MI)
LLVM_ABI bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
InstructionCost Cost
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
LLVM_ABI InlineParams getInlineParams(const LLVMContext &C)
Generate the parameters to tune the inline cost analysis based only on the commandline options.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
static void buildTopDownFuncOrder(LazyCallGraph &CG, std::vector< Function * > &FunctionOrderList)
LLVM_ABI InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes=false, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true, bool TrackInlineHistory=false, Function *ForwardVarArgsTo=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
This function inlines the called function into the basic block of the caller.
LLVM_ABI void setProbeDistributionFactor(Instruction &Inst, float Factor)
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
LLVM_ABI std::string AnnotateInlinePassName(InlineContext IC)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:75
LLVM_ABI cl::opt< bool > SampleProfileUseProfi
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:44
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI llvm::cl::opt< bool > UseIterativeBFIInference
LLVM_ABI std::optional< PseudoProbe > extractProbe(const Instruction &Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void emitInlinedIntoBasedOnCost(OptimizationRemarkEmitter &ORE, DebugLoc DLoc, const BasicBlock *Block, const Function &Callee, const Function &Caller, const InlineCost &IC, bool ForProfileContext=false, const char *PassName=nullptr)
Emit ORE message based in cost (default heuristic).
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI std::unique_ptr< InlineAdvisor > getReplayInlineAdvisor(Module &M, FunctionAnalysisManager &FAM, LLVMContext &Context, std::unique_ptr< InlineAdvisor > OriginalAdvisor, const ReplayInlinerSettings &ReplaySettings, bool EmitRemarks, InlineContext IC)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void updateProfileCallee(Function *Callee, int64_t EntryDelta, const ValueMap< const Value *, WeakTrackingVH > *VMap=nullptr)
Updates profile information by adjusting the entry count by adding EntryDelta then scaling callsite i...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
bool isMemProfClone(const GlobalValue &GV)
Returns true if GV is a MemProf context-disambiguated clone.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static bool skipProfileForFunction(const Function &F)
constexpr bool valueOr(BoolOrDefault X, bool Default)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
cl::opt< bool > EnableExtTspBlockPlacement
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
Definition Metadata.h:60
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
constexpr const char * PseudoProbeDescMetadataName
Definition PseudoProbe.h:26
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
A wrapper of binary function with basic blocks and jumps.
std::optional< bool > AllowRecursiveCall
Indicate whether we allow inlining for recursive call.
Definition InlineCost.h:247
std::optional< bool > ComputeFullInlineCost
Compute inline cost even when the cost has exceeded the threshold.
Definition InlineCost.h:241
static std::optional< uint32_t > extractDwarfBaseDiscriminator(uint32_t Value)
Definition PseudoProbe.h:81
The thresholds of the priority-based sample profile loader inliner.