[llvm-branch-commits] [llvm] [SampleProfile] Recover missing inline contexts from top-level profiles (PR #245375)
Kunal Pathak via llvm-branch-commits
llvm-branch-commits at lists.llvm.org
Mon Nov 23 12:55:41 PST 2026
https://github.com/kunalspathak created https://github.com/llvm/llvm-project/pull/245375
The compiler and the sample pre-inliner can make different inlining decisions. When the compiler inlines a function that the profile kept separate, the sample loader can lose access to that function’s profile and its nested inline decisions.
For example, consider `G -> R -> ext`. The profile keeps `R` as a top-level function and marks `ext` for inlining into it. During ThinLTO pre-link, the regular inliner instead inlines `R` into `G` and removes its standalone definition.
In post-link, the loader looks for `R` underneath `G`’s profile. That context does not exist: `R`’s samples, including the decision to inline `ext`, are still stored in its separate root profile. Even when `ext` has been imported, the loader can miss that decision.
This patch lets the loader recover a missing inline context from the function’s top-level profile. It also makes those profiles available to the stale-profile matcher, so it can match locations inside an inlined function whose standalone definition has disappeared.
Recovery also handles deeper inline chains and frames inside imported code, including cases where an outer frame has no profile. For extbinary profiles, it selectively loads missing roots in batches and prefers an existing nested profile.
Finding a root does not automatically allow its samples to be reused. Recovery retains checks on the surviving definition, call counts, and available probe checksum information.
The behavior is controlled by `-sample-profile-preserve-orphaned-inlines`, enabled by default.
This is the profile-recovery follow-up to the import-hint preservation change in #243577
Assisted-by: GPT-6 Astra
>From 76cd07eceb984b3c248387a1c8f6ee0e891e7343 Mon Sep 17 00:00:00 2001
From: Kunal Pathak <kupathak at meta.com>
Date: Fri, 20 Nov 2026 12:29:23 -0800
Subject: [PATCH] [SampleProfile] Retrieve root profiles for inlined functions
Pre-link inlining can leave an inline frame whose samples are stored in a
separate root. Reading profiles only for surviving Function objects misses
that root. Looking only under the caller also fails when the profile and
IR inline trees disagree, including when an inner function is inlined first.
Put selective inline-root retrieval in the sample-profile reader so sample
loading and stale matching can both use it. Collect inline frames once,
prefer matching nested profiles, and batch missing-root reads by depth.
Do not let a missing outer profile hide a deeper frame or repeatedly request
names that are absent from the profile.
Let stale matching collect anchors inside eliminated inline frames and
reuse its existing matching algorithm and location-map distribution. For
MD5 profiles, resolve known callee hashes before the comparison loop.
Keep retrieval separate from permission to reuse sample counts. Post-link
fallback still checks the caller's count and probe checksum. Reject zero-head
roots, and allow imported optimization-only bodies without treating them as
surviving emitted definitions.
Assisted-by: GPT-6 Astra
---
llvm/include/llvm/ProfileData/SampleProf.h | 14 +-
.../llvm/ProfileData/SampleProfReader.h | 7 +
.../Transforms/IPO/SampleProfileMatcher.h | 8 +-
llvm/lib/ProfileData/SampleProf.cpp | 20 +-
llvm/lib/ProfileData/SampleProfReader.cpp | 97 ++++++
llvm/lib/Transforms/IPO/SampleProfile.cpp | 84 ++++-
.../Transforms/IPO/SampleProfileMatcher.cpp | 172 +++++-----
.../thinlto-orphaned-local-root.ll | 306 ++++++++++++++++++
.../thinlto-orphaned-nonlocal-root.ll | 104 ++++++
9 files changed, 714 insertions(+), 98 deletions(-)
create mode 100644 llvm/test/Transforms/SampleProfile/thinlto-orphaned-local-root.ll
create mode 100644 llvm/test/Transforms/SampleProfile/thinlto-orphaned-nonlocal-root.ll
diff --git a/llvm/include/llvm/ProfileData/SampleProf.h b/llvm/include/llvm/ProfileData/SampleProf.h
index 9944fdb8a08aa2..87dfc48691b09f 100644
--- a/llvm/include/llvm/ProfileData/SampleProf.h
+++ b/llvm/include/llvm/ProfileData/SampleProf.h
@@ -18,6 +18,7 @@
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Eytzinger.h"
#include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SortedVectorMap.h"
#include "llvm/ADT/StringExtras.h"
@@ -1304,6 +1305,10 @@ class FunctionSamples {
uint64_t getFunctionHash() const { return FunctionHash; }
+ bool hasIRToProfileLocationMap() const {
+ return IRToProfileLocationMap && !IRToProfileLocationMap->empty();
+ }
+
void setIRToProfileLocationMap(const LocToLocMap *LTLM) {
assert(IRToProfileLocationMap == nullptr && "this should be set only once");
IRToProfileLocationMap = LTLM;
@@ -1426,12 +1431,17 @@ class FunctionSamples {
/// \returns the FunctionSamples pointer to the inlined instance.
/// If \p Remapper or \p FuncNameToProfNameMap is not nullptr, it will be used
/// to find matching FunctionSamples with not exactly the same but equivalent
- /// name.
+ /// name. If \p Fallback is not null, it is called for an inlined frame that
+ /// has no profile under its caller, with the caller's profile, the call site,
+ /// and the frame's name; a non-null result is used instead.
LLVM_ABI const FunctionSamples *findFunctionSamples(
const DILocation *DIL,
SampleProfileReaderItaniumRemapper *Remapper = nullptr,
const HashKeyMap<DenseMap, FunctionId, FunctionId>
- *FuncNameToProfNameMap = nullptr) const LLVM_LIFETIME_BOUND;
+ *FuncNameToProfNameMap = nullptr,
+ function_ref<const FunctionSamples *(const FunctionSamples &,
+ const LineLocation &, StringRef)>
+ Fallback = nullptr) const LLVM_LIFETIME_BOUND;
SampleContext &getContext() const LLVM_LIFETIME_BOUND { return Context; }
diff --git a/llvm/include/llvm/ProfileData/SampleProfReader.h b/llvm/include/llvm/ProfileData/SampleProfReader.h
index 2bb616bb94b1fb..f40c5b5ade84dd 100644
--- a/llvm/include/llvm/ProfileData/SampleProfReader.h
+++ b/llvm/include/llvm/ProfileData/SampleProfReader.h
@@ -607,6 +607,13 @@ class SampleProfileReader {
return sampleprof_error::success;
}
+ /// Load missing roots referenced by inline frames, preferring existing
+ /// nested profiles. Collect the frames once and batch reads by inline depth;
+ /// each missing name is requested at most once. Matching also needs roots
+ /// when the caller's recorded locations no longer match the IR.
+ LLVM_ABI std::error_code readInlineFunctionProfiles(const Module &M,
+ bool ForMatching = false);
+
/// The implementaion to read sample profiles from the associated file.
virtual std::error_code readImpl() = 0;
diff --git a/llvm/include/llvm/Transforms/IPO/SampleProfileMatcher.h b/llvm/include/llvm/Transforms/IPO/SampleProfileMatcher.h
index c78eba37dafa7a..0c78c9809e0d20 100644
--- a/llvm/include/llvm/Transforms/IPO/SampleProfileMatcher.h
+++ b/llvm/include/llvm/Transforms/IPO/SampleProfileMatcher.h
@@ -162,8 +162,10 @@ class SampleProfileMatcher {
const AnchorMap &ProfileAnchors,
AnchorList &FilteredIRAnchorsList,
AnchorList &FilteredProfileAnchorList);
- void runOnFunction(Function &F);
- void findIRAnchors(const Function &F, AnchorMap &IRAnchors) const;
+ void runOnFunction(Function &F, StringMap<AnchorMap> &InlineAnchors);
+ void findIRAnchors(const Function &F, AnchorMap &IRAnchors,
+ StringMap<AnchorMap> *InlineAnchors = nullptr) const;
+ void matchInlinedFunctions(const StringMap<AnchorMap> &InlineAnchors);
void findProfileAnchors(const FunctionSamples &FS,
AnchorMap &ProfileAnchors) const;
bool anchorsMatch(const FunctionId &IRAnchor,
@@ -217,7 +219,7 @@ class SampleProfileMatcher {
void matchNonCallsiteLocs(const LocToLocMap &AnchorMatchings,
const AnchorMap &IRAnchors,
LocToLocMap &IRToProfileLocationMap);
- void runStaleProfileMatching(const Function &F, const AnchorMap &IRAnchors,
+ void runStaleProfileMatching(StringRef Name, const AnchorMap &IRAnchors,
const AnchorMap &ProfileAnchors,
LocToLocMap &IRToProfileLocationMap,
bool RunCFGMatching, bool RunCGMatching);
diff --git a/llvm/lib/ProfileData/SampleProf.cpp b/llvm/lib/ProfileData/SampleProf.cpp
index 5e090d6e5c765c..11b4fc4517a377 100644
--- a/llvm/lib/ProfileData/SampleProf.cpp
+++ b/llvm/lib/ProfileData/SampleProf.cpp
@@ -303,20 +303,18 @@ LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL,
const FunctionSamples *FunctionSamples::findFunctionSamples(
const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper,
- const HashKeyMap<DenseMap, FunctionId, FunctionId> *FuncNameToProfNameMap)
- const {
+ const HashKeyMap<DenseMap, FunctionId, FunctionId> *FuncNameToProfNameMap,
+ function_ref<const FunctionSamples *(const FunctionSamples &,
+ const LineLocation &, StringRef)>
+ Fallback) const {
assert(DIL);
SmallVector<std::pair<LineLocation, StringRef>, 10> S;
const DILocation *PrevDIL = DIL;
for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
- // Use C++ linkage name if possible.
- StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName();
- if (Name.empty())
- Name = PrevDIL->getScope()->getSubprogram()->getName();
S.emplace_back(FunctionSamples::getCallSiteIdentifier(
DIL, FunctionSamples::ProfileIsFS),
- Name);
+ PrevDIL->getSubprogramLinkageName());
PrevDIL = DIL;
}
@@ -324,8 +322,12 @@ const FunctionSamples *FunctionSamples::findFunctionSamples(
return this;
const FunctionSamples *FS = this;
for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
- FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper,
- FuncNameToProfNameMap);
+ const auto &[Loc, Name] = S[i];
+ const FunctionSamples *Inlinee =
+ FS->findFunctionSamplesAt(Loc, Name, Remapper, FuncNameToProfNameMap);
+ if (!Inlinee && Fallback)
+ Inlinee = Fallback(*FS, Loc, Name);
+ FS = Inlinee;
}
return FS;
}
diff --git a/llvm/lib/ProfileData/SampleProfReader.cpp b/llvm/lib/ProfileData/SampleProfReader.cpp
index b8b33c11f5662c..620e17e10a5834 100644
--- a/llvm/lib/ProfileData/SampleProfReader.cpp
+++ b/llvm/lib/ProfileData/SampleProfReader.cpp
@@ -24,12 +24,16 @@
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringRef.h"
+#include "llvm/IR/DebugInfoMetadata.h"
+#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ProfileSummary.h"
+#include "llvm/IR/PseudoProbe.h"
#include "llvm/ProfileData/ProfileCommon.h"
#include "llvm/ProfileData/SampleProf.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compression.h"
+#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/LEB128.h"
@@ -1121,6 +1125,99 @@ SampleProfileReaderExtBinaryBase::read(const DenseSet<StringRef> &FuncsToUse,
return sampleprof_error::success;
}
+std::error_code
+SampleProfileReader::readInlineFunctionProfiles(const Module &M,
+ bool ForMatching) {
+ if (getFormat() != SPF_Ext_Binary || profileIsCS())
+ return sampleprof_error::success;
+
+ struct Frame {
+ const FunctionSamples *Samples;
+ const DILocation *Location;
+ unsigned Parent, Depth;
+ };
+ SmallVector<Frame> Frames;
+ SmallVector<SmallVector<unsigned>> Levels(1);
+ using FrameKey = std::pair<const DILocation *, const DISubprogram *>;
+ for (const Function &F : M) {
+ if (F.isDeclaration() || !F.hasFnAttribute("use-sample-profile"))
+ continue;
+ unsigned Root = Frames.size();
+ Frames.push_back({getSamplesFor(F), nullptr, Root, 0});
+ DenseMap<FrameKey, unsigned> Seen;
+ for (const Instruction &I : instructions(F)) {
+ const DILocation *DIL = I.getDebugLoc();
+ if (!DIL || (profileIsProbeBased() && !extractProbe(I)))
+ continue;
+ SmallVector<const DILocation *, 4> Path;
+ unsigned Parent = Root;
+ for (; DIL->getInlinedAt(); DIL = DIL->getInlinedAt()) {
+ FrameKey Key = {DIL->getInlinedAt(), DIL->getScope()->getSubprogram()};
+ auto It = Seen.find(Key);
+ if (It != Seen.end()) {
+ Parent = It->second;
+ break;
+ }
+ Path.push_back(DIL);
+ }
+ for (const DILocation *DIL : reverse(Path)) {
+ unsigned ID = Frames.size();
+ unsigned Depth = Frames[Parent].Depth + 1;
+ Frames.push_back({nullptr, DIL, Parent, Depth});
+ Seen.try_emplace(
+ FrameKey{DIL->getInlinedAt(), DIL->getScope()->getSubprogram()},
+ ID);
+ if (Levels.size() <= Depth)
+ Levels.resize(Depth + 1);
+ Levels[Depth].push_back(ID);
+ Parent = ID;
+ }
+ }
+ }
+
+ DenseSet<StringRef> Requested;
+ for (const auto &Level : Levels) {
+ DenseSet<StringRef> Names;
+ SmallVector<std::pair<StringRef, Frame *>> Missing;
+ for (unsigned ID : Level) {
+ Frame &F = Frames[ID];
+ StringRef Name = FunctionSamples::getCanonicalFnName(
+ F.Location->getSubprogramLinkageName());
+ const FunctionSamples *Parent = Frames[F.Parent].Samples;
+ LineLocation Loc = FunctionSamples::getCallSiteIdentifier(
+ F.Location->getInlinedAt(), FunctionSamples::ProfileIsFS);
+ if (Parent)
+ F.Samples = Parent->findFunctionSamplesAt(Loc, Name, getRemapper(),
+ FuncNameToProfNameMap);
+ if (F.Samples)
+ continue;
+ // A known caller without this target cannot use its root for annotation.
+ // An unknown caller must not hide deeper frames: it may itself be inlined
+ // later, acquiring a nested profile in its new caller.
+ if (Parent && !ForMatching) {
+ auto Targets = Parent->findCallTargetMapAt(Loc);
+ if (!Targets || Targets->find(getRepInFormat(Name)) == Targets->end())
+ continue;
+ }
+ F.Samples = getSamplesFor(Name);
+ if (!F.Samples) {
+ Missing.emplace_back(Name, &F);
+ if (Requested.insert(Name).second)
+ Names.insert(Name);
+ }
+ }
+ if (std::error_code EC = read(Names))
+ return EC;
+ for (const auto &[Name, F] : Missing)
+ F->Samples = getSamplesFor(Name);
+ LLVM_DEBUG(for (StringRef Name : Names) {
+ if (getSamplesFor(Name))
+ dbgs() << "Loaded inline frame root: " << Name << "\n";
+ });
+ }
+ return sampleprof_error::success;
+}
+
bool SampleProfileReaderExtBinaryBase::collectFuncsFromModule() {
if (!M)
return false;
diff --git a/llvm/lib/Transforms/IPO/SampleProfile.cpp b/llvm/lib/Transforms/IPO/SampleProfile.cpp
index 67a30fe80b2b5d..f8a4c04d716d5f 100644
--- a/llvm/lib/Transforms/IPO/SampleProfile.cpp
+++ b/llvm/lib/Transforms/IPO/SampleProfile.cpp
@@ -48,6 +48,7 @@
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
+#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
@@ -106,6 +107,8 @@ STATISTIC(NumMismatchedProfile,
STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
STATISTIC(NumDuplicatedInlinesite,
"Number of inlined callsites with a partial distribution factor");
+STATISTIC(NumOrphanedRootsLoaded,
+ "Number of orphaned root profiles loaded on demand");
STATISTIC(NumCSInlinedHitMinLimit,
"Number of functions with FDO inline stopped due to min size limit");
@@ -154,8 +157,9 @@ static cl::opt<bool> PreserveDeferredInlines(
static cl::opt<bool> PreserveOrphanedInlines(
"sample-profile-preserve-orphaned-inlines", cl::Hidden, cl::init(true),
- cl::desc("In ThinLTO pre-link, preserve import GUIDs "
- "of functions that pre-link inlines and deletes."));
+ cl::desc(
+ "In ThinLTO, preserve the import GUIDs and profile inline decisions "
+ "of functions that pre-link inlines and deletes."));
namespace llvm {
extern cl::opt<bool> EnableExtTspBlockPlacement;
@@ -337,6 +341,9 @@ class SampleProfileLoader final : public SampleProfileLoaderBaseImpl<Function> {
findFunctionSamples(const Instruction &I) const override;
std::vector<const FunctionSamples *>
findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
+ const FunctionSamples *findOrphanedRoot(const FunctionSamples &CallerFS,
+ const LineLocation &Loc,
+ StringRef Name) const;
void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
DenseSet<GlobalValue::GUID> &InlinedGUIDs,
uint64_t Threshold);
@@ -618,15 +625,61 @@ SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
if (it.second) {
- if (FunctionSamples::ProfileIsCS)
+ if (FunctionSamples::ProfileIsCS) {
it.first->second = ContextTracker->getContextSamplesFor(DIL);
- else
+ } else {
it.first->second = Samples->findFunctionSamples(
- DIL, Reader->getRemapper(), &FuncNameToProfNameMap);
+ DIL, Reader->getRemapper(), &FuncNameToProfNameMap,
+ [this](const FunctionSamples &CallerFS, const LineLocation &Loc,
+ StringRef Name) {
+ return findOrphanedRoot(CallerFS, Loc, Name);
+ });
+ }
}
return it.first->second;
}
+/// Recover the top-level profile of \p Name for a missing inline context at
+/// \p Loc of \p CallerFS. Pre-link may have inlined and deleted a function
+/// whose profile the pre-inliner kept top-level. Require no definition in this
+/// module and check the call-site count before reusing the root. Retrieving
+/// a root for matching does not by itself justify reusing its sample counts.
+const FunctionSamples *
+SampleProfileLoader::findOrphanedRoot(const FunctionSamples &CallerFS,
+ const LineLocation &Loc,
+ StringRef Name) const {
+ if (!PreserveOrphanedInlines ||
+ LTOPhase != ThinOrFullLTOPhase::ThinLTOPostLink)
+ return nullptr;
+ StringRef Canonical = FunctionSamples::getCanonicalFnName(Name);
+ const Function *Def = SymbolMap.lookup(FunctionId(Canonical));
+ if (Def && !Def->isDeclarationForLinker())
+ return nullptr;
+ const FunctionSamples *Root = Reader->getSamplesFor(Canonical);
+ // Require this call site to account for all entries of the function, so
+ // that inlined copies at other call sites do not reuse the same samples.
+ auto Targets = CallerFS.findCallTargetMapAt(Loc);
+ if (!Targets)
+ return nullptr;
+ auto Target =
+ Targets->find(Root ? Root->getFunction() : getRepInFormat(Canonical));
+ if (Target == Targets->end())
+ return nullptr;
+ // A zero head count cannot establish that this inline site owns the root.
+ if (!Root || !Root->getHeadSamples() ||
+ Target->second < Root->getHeadSamples())
+ return nullptr;
+ // Import does not copy llvm.pseudo_probe_desc, so an imported inline frame
+ // may have no descriptor in this module. Check its hash when one is present.
+ if (FunctionSamples::ProfileIsProbeBased) {
+ const PseudoProbeDescriptor *Desc = ProbeManager->getDesc(Root->getGUID());
+ if (Desc && ProbeManager->profileIsHashMismatched(*Desc, *Root) &&
+ !Root->hasIRToProfileLocationMap())
+ return nullptr;
+ }
+ return Root;
+}
+
/// Check whether the indirect call promotion history of \p Inst allows
/// the promotion for \p Candidate.
/// If the profile count for the promotion candidate \p Candidate is
@@ -1988,8 +2041,6 @@ void SampleProfileLoader::removePseudoProbeInstsDiscriminator(Module &M) {
bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager &AM,
ProfileSummaryInfo *_PSI) {
- GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
-
PSI = _PSI;
if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
@@ -2029,6 +2080,25 @@ bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager &AM,
}
}
+ // Inline frames can outlive their standalone Function. Load their missing
+ // roots before either consumer runs; matching and annotation have different
+ // rules for using a root, but share the same selective retrieval.
+ if ((PreserveOrphanedInlines &&
+ LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink) ||
+ SalvageStaleProfile) {
+ size_t Before = Reader->getProfiles().size();
+ if (std::error_code EC =
+ Reader->readInlineFunctionProfiles(M, SalvageStaleProfile)) {
+ M.getContext().diagnose(DiagnosticInfoSampleProfile(
+ Filename, "profile reading failed: " + EC.message()));
+ return false;
+ }
+ NumOrphanedRootsLoaded += Reader->getProfiles().size() - Before;
+ }
+
+ // Created after all profiles are loaded, so that it covers them all.
+ GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
+
// Stale profile matching.
if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
SalvageStaleProfile) {
diff --git a/llvm/lib/Transforms/IPO/SampleProfileMatcher.cpp b/llvm/lib/Transforms/IPO/SampleProfileMatcher.cpp
index c5b421f64bcdc9..6460584477ce71 100644
--- a/llvm/lib/Transforms/IPO/SampleProfileMatcher.cpp
+++ b/llvm/lib/Transforms/IPO/SampleProfileMatcher.cpp
@@ -33,72 +33,50 @@ namespace llvm {
} // end namespace llvm
-void SampleProfileMatcher::findIRAnchors(const Function &F,
- AnchorMap &IRAnchors) const {
- // For inlined code, recover the original callsite and callee by finding the
- // top-level inline frame. e.g. For frame stack "main:1 @ foo:2 @ bar:3", the
- // top-level frame is "main:1", the callsite is "1" and the callee is "foo".
- auto FindTopLevelInlinedCallsite = [](const DILocation *DIL) {
- assert((DIL && DIL->getInlinedAt()) && "No inlined callsite");
- const DILocation *PrevDIL = nullptr;
- do {
- PrevDIL = DIL;
- DIL = DIL->getInlinedAt();
- } while (DIL->getInlinedAt());
-
- LineLocation Callsite = FunctionSamples::getCallSiteIdentifier(
- DIL, FunctionSamples::ProfileIsFS);
- StringRef CalleeName = PrevDIL->getSubprogramLinkageName();
- return std::make_pair(Callsite, FunctionId(CalleeName));
- };
-
- auto GetCanonicalCalleeName = [](const CallBase *CB) {
- StringRef CalleeName = UnknownIndirectCallee;
- if (Function *Callee = CB->getCalledFunction())
- CalleeName = FunctionSamples::getCanonicalFnName(Callee->getName());
- return CalleeName;
- };
-
- // Extract profile matching anchors in the IR.
- for (auto &BB : F) {
- for (auto &I : BB) {
- DILocation *DIL = I.getDebugLoc();
+void SampleProfileMatcher::findIRAnchors(
+ const Function &F, AnchorMap &IRAnchors,
+ StringMap<AnchorMap> *InlineAnchors) const {
+ DenseSet<std::pair<const DILocation *, const DISubprogram *>> Seen;
+ for (const BasicBlock &BB : F) {
+ for (const Instruction &I : BB) {
+ const DILocation *DIL = I.getDebugLoc();
if (!DIL)
continue;
-
+ std::optional<PseudoProbe> Probe;
if (FunctionSamples::ProfileIsProbeBased) {
- if (auto Probe = extractProbe(I)) {
- // Flatten inlined IR for the matching.
- if (DIL->getInlinedAt()) {
- IRAnchors.emplace(FindTopLevelInlinedCallsite(DIL));
- } else {
- // Use empty StringRef for basic block probe.
- StringRef CalleeName;
- if (const auto *CB = dyn_cast<CallBase>(&I)) {
- // Skip the probe inst whose callee name is "llvm.pseudoprobe".
- if (!isa<IntrinsicInst>(&I))
- CalleeName = GetCanonicalCalleeName(CB);
- }
- LineLocation Loc = LineLocation(Probe->Id, 0);
- IRAnchors.emplace(Loc, FunctionId(CalleeName));
- }
- }
- } else {
- // TODO: For line-number based profile(AutoFDO), currently only support
- // find callsite anchors. In future, we need to parse all the non-call
- // instructions to extract the line locations for profile matching.
- if (!isa<CallBase>(&I) || isa<IntrinsicInst>(&I))
+ Probe = extractProbe(I);
+ if (!Probe)
continue;
-
- if (DIL->getInlinedAt()) {
- IRAnchors.emplace(FindTopLevelInlinedCallsite(DIL));
- } else {
- LineLocation Callsite = FunctionSamples::getCallSiteIdentifier(
- DIL, FunctionSamples::ProfileIsFS);
- StringRef CalleeName = GetCanonicalCalleeName(dyn_cast<CallBase>(&I));
- IRAnchors.emplace(Callsite, FunctionId(CalleeName));
- }
+ } else if (!isa<CallBase>(I) || isa<IntrinsicInst>(I)) {
+ continue;
+ }
+ StringRef Callee;
+ if (const auto *CB = dyn_cast<CallBase>(&I); CB && !isa<IntrinsicInst>(I))
+ Callee =
+ CB->getCalledFunction()
+ ? FunctionSamples::getCanonicalFnName(*CB->getCalledFunction())
+ : UnknownIndirectCallee;
+ LineLocation Loc = FunctionSamples::ProfileIsProbeBased
+ ? LineLocation(Probe->Id, 0)
+ : FunctionSamples::getCallSiteIdentifier(
+ DIL, FunctionSamples::ProfileIsFS);
+ // Record anchors in each frame's own coordinates, not just the outermost
+ // caller. Shared inline-chain links need to be visited only once.
+ while (const DILocation *Callsite = DIL->getInlinedAt()) {
+ const DISubprogram *SP = DIL->getScope()->getSubprogram();
+ StringRef Name = FunctionSamples::getCanonicalFnName(
+ DIL->getSubprogramLinkageName());
+ if (InlineAnchors)
+ (*InlineAnchors)[Name].emplace(Loc, FunctionId(Callee));
+ if (!Seen.insert({Callsite, SP}).second)
+ break;
+ Callee = Name;
+ DIL = Callsite;
+ Loc = FunctionSamples::getCallSiteIdentifier(
+ DIL, FunctionSamples::ProfileIsFS);
}
+ if (!DIL->getInlinedAt())
+ IRAnchors.emplace(Loc, FunctionId(Callee));
}
}
}
@@ -316,13 +294,12 @@ void SampleProfileMatcher::getFilteredAnchorList(
// [1, 2, 3(foo), 4, 7, 8(bar), 9]
// The output mapping: [2->3, 3->4, 5->7, 6->8, 7->9].
void SampleProfileMatcher::runStaleProfileMatching(
- const Function &F, const AnchorMap &IRAnchors,
- const AnchorMap &ProfileAnchors, LocToLocMap &IRToProfileLocationMap,
- bool RunCFGMatching, bool RunCGMatching) {
+ StringRef Name, const AnchorMap &IRAnchors, const AnchorMap &ProfileAnchors,
+ LocToLocMap &IRToProfileLocationMap, bool RunCFGMatching,
+ bool RunCGMatching) {
if (!RunCFGMatching && !RunCGMatching)
return;
- LLVM_DEBUG(dbgs() << "Run stale profile matching for " << F.getName()
- << "\n");
+ LLVM_DEBUG(dbgs() << "Run stale profile matching for " << Name << "\n");
assert(IRToProfileLocationMap.empty() &&
"Run stale profile matching only once per function");
@@ -337,7 +314,7 @@ void SampleProfileMatcher::runStaleProfileMatching(
if (FilteredIRAnchorsList.size() > Opts.salvage_stale_profile_max_callsites ||
FilteredProfileAnchorList.size() >
Opts.salvage_stale_profile_max_callsites) {
- LLVM_DEBUG(dbgs() << "Skip stale profile matching for " << F.getName()
+ LLVM_DEBUG(dbgs() << "Skip stale profile matching for " << Name
<< " because the number of callsites in the IR is "
<< FilteredIRAnchorsList.size()
<< " and in the profile is "
@@ -428,7 +405,8 @@ void SampleProfileMatcher::runStaleProfileMatching(
matchNonCallsiteLocs(MatchedAnchors, IRAnchors, IRToProfileLocationMap);
}
-void SampleProfileMatcher::runOnFunction(Function &F) {
+void SampleProfileMatcher::runOnFunction(Function &F,
+ StringMap<AnchorMap> &InlineAnchors) {
// We need to use flattened function samples for matching.
// Unlike IR, which includes all callsites from the source code, the callsites
// in profile only show up when they are hit by samples, i,e. the profile
@@ -448,14 +426,15 @@ void SampleProfileMatcher::runOnFunction(Function &F) {
FSForMatching = Reader.getSamplesFor(R->second.stringRef());
}
}
- if (!FSForMatching)
+ if (!FSForMatching && !SalvageStaleProfile)
return;
- // Anchors for IR. It's a map from IR location to callee name, callee name is
- // empty for non-call instruction and use a dummy name(UnknownIndirectCallee)
- // for unknown indrect callee name.
+ // Collect inline anchors in the same scan as the function's own anchors.
+ // Even a function without a root profile can contain a profiled inlinee.
AnchorMap IRAnchors;
- findIRAnchors(F, IRAnchors);
+ findIRAnchors(F, IRAnchors, SalvageStaleProfile ? &InlineAnchors : nullptr);
+ if (!FSForMatching)
+ return;
// Anchors for profile. It's a map from callsite location to a set of callee
// name.
AnchorMap ProfileAnchors;
@@ -484,8 +463,9 @@ void SampleProfileMatcher::runOnFunction(Function &F) {
// The matching result will be saved to IRToProfileLocationMap, create a
// new map for each function.
auto &IRToProfileLocationMap = getIRToProfileLocationMap(*FSForMatching);
- runStaleProfileMatching(F, IRAnchors, ProfileAnchors, IRToProfileLocationMap,
- RunCFGMatching, RunCGMatching);
+ runStaleProfileMatching(F.getName(), IRAnchors, ProfileAnchors,
+ IRToProfileLocationMap, RunCFGMatching,
+ RunCGMatching);
// Find and update callsite match states after matching.
if (RunCFGMatching &&
(Opts.report_profile_staleness || Opts.persist_profile_staleness))
@@ -1069,6 +1049,41 @@ void SampleProfileMatcher::UpdateWithSalvagedProfiles() {
Reader.setFuncNameToProfNameMap(*FuncNameToProfNameMap);
}
+void SampleProfileMatcher::matchInlinedFunctions(
+ const StringMap<AnchorMap> &InlineAnchors) {
+ for (const auto &Entry : InlineAnchors) {
+ StringRef Name = Entry.getKey();
+ const AnchorMap &IRAnchors = Entry.getValue();
+ const auto *FS = getFlattenedSamplesFor(FunctionId(Name));
+ if (!FS || FuncMappings.contains(FS->getFuncName()))
+ continue;
+ // Prefer a surviving body's anchors. Here there is no Function whose
+ // definition can supply them, so use the collected inline copies instead.
+ if (const Function *F = M.getFunction(Name); F && !F->isDeclaration())
+ continue;
+ if (FunctionSamples::ProfileIsProbeBased) {
+ const auto *Desc = ProbeManager->getDesc(FS->getGUID());
+ if (!Desc || !ProbeManager->profileIsHashMismatched(*Desc, *FS))
+ continue;
+ }
+ AnchorMap ProfileAnchors;
+ findProfileAnchors(*FS, ProfileAnchors);
+ if (FunctionSamples::UseMD5) {
+ // Resolve known hashes once, not inside the LCS comparison loop.
+ DenseMap<uint64_t, FunctionId> Names;
+ for (const auto &[Loc, Callee] : IRAnchors)
+ if (!Callee.empty())
+ Names.try_emplace(Callee.getHashCode(), Callee);
+ for (auto &[Loc, Callee] : ProfileAnchors)
+ if (auto It = Names.find(Callee.getHashCode()); It != Names.end())
+ Callee = It->second;
+ }
+ runStaleProfileMatching(Name, IRAnchors, ProfileAnchors,
+ getIRToProfileLocationMap(*FS),
+ /*RunCFGMatching=*/true, /*RunCGMatching=*/false);
+ }
+}
+
void SampleProfileMatcher::runOnModule() {
ProfileConverter::flattenProfile(Reader.getProfiles(), FlattenedProfiles,
FunctionSamples::ProfileIsCS);
@@ -1087,17 +1102,20 @@ void SampleProfileMatcher::runOnModule() {
std::vector<Function *> TopDownFunctionList;
TopDownFunctionList.reserve(M.size());
buildTopDownFuncOrder(CG, TopDownFunctionList);
+ StringMap<AnchorMap> InlineAnchors;
for (auto *F : TopDownFunctionList) {
if (skipProfileForFunction(*F))
continue;
- runOnFunction(*F);
+ runOnFunction(*F, InlineAnchors);
}
if (SalvageUnusedProfile)
UpdateWithSalvagedProfiles();
- if (SalvageStaleProfile)
+ if (SalvageStaleProfile) {
+ matchInlinedFunctions(InlineAnchors);
distributeIRToProfileLocationMap();
+ }
computeAndReportProfileStaleness();
}
diff --git a/llvm/test/Transforms/SampleProfile/thinlto-orphaned-local-root.ll b/llvm/test/Transforms/SampleProfile/thinlto-orphaned-local-root.ll
new file mode 100644
index 00000000000000..66b410d4014ad5
--- /dev/null
+++ b/llvm/test/Transforms/SampleProfile/thinlto-orphaned-local-root.ll
@@ -0,0 +1,306 @@
+; Recover a missing inline context from an eliminated function's separate
+; profile root. Pre-link import-hint preservation is tested separately in
+; thinlto-preserve-import-hints.ll.
+
+; RUN: split-file %s %t
+; RUN: cat %t/common.ll >> %t/post.ll
+; RUN: cat %t/common.ll >> %t/post-chain.ll
+; RUN: cat %t/common.ll >> %t/post-shared.ll
+; DEFINE: %{post} = opt -passes='thinlto<O2>' -pgo-kind=pgo-sample-use-pipeline \
+; DEFINE: -pass-remarks=sample-profile-inline -o /dev/null
+; DEFINE: %{enable} = -sample-profile-preserve-orphaned-inlines
+; DEFINE: %{merge} = llvm-profdata merge --sample --extbinary
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof.txt -sample-profile-preserve-orphaned-inlines=false 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof.txt 2>&1 | FileCheck %s --check-prefix=POST-ON
+
+;; An imported optimization-only body is not a surviving emitted definition.
+; RUN: cat %t/post.ll %t/imported-root.ll > %t/post-imported.ll
+; RUN: %{post} %t/post-imported.ll -sample-profile-file=%t/prof.txt 2>&1 | FileCheck %s --check-prefix=POST-ON
+; RUN: sed 's/define available_externally i64 @R/define i64 @R/' %t/post-imported.ll > %t/post-retained.ll
+; RUN: %{post} %t/post-retained.ll -sample-profile-file=%t/prof.txt 2>&1 | FileCheck %s --check-prefix=POST-OFF --allow-empty
+
+;; Post-link recovers non-local roots by default too. Disabling recovery
+;; rejects them. Both local and non-local roots retain the call-count and
+;; checksum checks.
+; RUN: sed 's/DISPFlagLocalToUnit | //' %t/post.ll > %t/post-nonlocal.ll
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof.txt -sample-profile-preserve-orphaned-inlines=false 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: sed 's/^R:2000:1000$/R:2000:2000/' %t/prof.txt > %t/prof-multi.txt
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-multi.txt %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+;; A zero head cannot prove exclusive ownership of the root's body samples.
+; RUN: sed 's/^R:2000:1000$/R:2000:0/' %t/prof.txt > %t/prof-zero-head.txt
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-zero-head.txt 2>&1 | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{merge} %t/prof-zero-head.txt -o %t/prof-zero-head.extbinary
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-zero-head.extbinary 2>&1 | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: sed 's/^ !CFGChecksum: 2$/ !CFGChecksum: 9/' %t/prof.txt > %t/prof-stale.txt
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-stale.txt %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof.txt 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-ON
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof-multi.txt 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof-stale.txt 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+
+;; The same profiles in extbinary format. Its reader loads only the profiles of
+;; functions in the module, so post-link must load R's profile explicitly. The
+;; same gates apply.
+; RUN: %{merge} %t/prof.txt -o %t/prof.extbinary
+; RUN: %{merge} %t/prof-multi.txt -o %t/prof-multi.extbinary
+; RUN: %{merge} %t/prof-stale.txt -o %t/prof-stale.extbinary
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof.extbinary -sample-profile-preserve-orphaned-inlines=false 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-ON
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof.extbinary 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-ON
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof.extbinary -sample-profile-preserve-orphaned-inlines=false 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof-multi.extbinary 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post-nonlocal.ll -sample-profile-file=%t/prof-stale.extbinary 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-multi.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-stale.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+;; MD5 names, including the Eytzinger offset table layout.
+; RUN: %{merge} --use-md5 %t/prof.txt -o %t/prof.md5
+; RUN: %{merge} --use-md5 --md5-indexed-tables %t/prof.txt -o %t/prof.md5.eytzinger
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof.md5 %{enable} 2>&1 | FileCheck %s --check-prefix=POST-ON
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof.md5.eytzinger %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-ON
+
+;; Post-link loads a root only when a nested lookup misses and the caller
+;; records a call to it. With R's root loaded, R's frame misses S, so a second
+;; round loads S's root.
+; RUN: %{merge} %t/prof-chain.txt -o %t/prof-chain.extbinary
+; RUN: %{post} %t/post-chain.ll -sample-profile-file=%t/prof-chain.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=CHAIN
+; RUN: %if asserts %{ %{post} %t/post-chain.ll -sample-profile-file=%t/prof-chain.extbinary %{enable} -stats 2>&1 \
+; RUN: | FileCheck %s --check-prefix=LOADED2 %}
+;; R and Q, two promoted targets of one call, share the inline site in G. Both
+;; roots are loaded.
+; RUN: %{merge} %t/prof-shared.txt -o %t/prof-shared.extbinary
+; RUN: %{post} %t/post-shared.ll -sample-profile-file=%t/prof-shared.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=SHARED
+; RUN: %if asserts %{ %{post} %t/post-shared.ll -sample-profile-file=%t/prof-shared.extbinary %{enable} -stats 2>&1 \
+; RUN: | FileCheck %s --check-prefix=LOADED2 %}
+;; No root is loaded when G's profile already has R nested, when the profile
+;; has no root for R, or (with stale matching disabled) when G's call site
+;; does not record R. Matching can need the root even when callsites disagree.
+; RUN: %{merge} %t/prof-nested.txt -o %t/prof-nested.extbinary
+; RUN: sed '/^R:/,$d' %t/prof.txt | %{merge} - -o %t/prof-noroot.extbinary
+; RUN: sed 's/^ 2: 1000 R:1000$/ 2: 1000/' %t/prof.txt | %{merge} - -o %t/prof-notarget.extbinary
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-nested.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-ON
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-noroot.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post.ll -sample-profile-file=%t/prof-notarget.extbinary %{enable} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %if asserts %{ %{post} %t/post.ll -sample-profile-file=%t/prof.extbinary %{enable} -stats 2>&1 \
+; RUN: | FileCheck %s --check-prefix=LOADED1 %}
+; RUN: %if asserts %{ %{post} %t/post.ll -sample-profile-file=%t/prof-nested.extbinary %{enable} -stats 2>&1 \
+; RUN: | FileCheck %s --check-prefix=LOADED0 %}
+; RUN: %if asserts %{ %{post} %t/post.ll -sample-profile-file=%t/prof-noroot.extbinary %{enable} -stats 2>&1 \
+; RUN: | FileCheck %s --check-prefix=LOADED0 %}
+; RUN: %if asserts %{ %{post} %t/post.ll -sample-profile-file=%t/prof-notarget.extbinary %{enable} -salvage-stale-profile=false -stats 2>&1 \
+; RUN: | FileCheck %s --check-prefix=LOADED0 %}
+
+;; Reuse this fixture for a stale inline frame: R's ext call moves from
+;; probe 2 to probe 3 and R's checksum changes. Matching must recover it.
+; RUN: sed -e 's/i64 2, !"R"/i64 9, !"R"/' -e 's/!12 = !DILexicalBlockFile(scope: !9, file: !1, discriminator: 186646551)/!12 = !DILexicalBlockFile(scope: !9, file: !1, discriminator: 186646559)/' %t/post.ll > %t/post-stale.ll
+; RUN: %{post} %t/post-stale.ll -sample-profile-file=%t/prof.txt -salvage-stale-profile=false 2>&1 | FileCheck %s --check-prefix=POST-OFF --allow-empty
+; RUN: %{post} %t/post-stale.ll -sample-profile-file=%t/prof.txt -salvage-stale-profile 2>&1 | FileCheck %s --check-prefix=POST-ON
+; RUN: %{post} %t/post-stale.ll -sample-profile-file=%t/prof.extbinary -salvage-stale-profile 2>&1 | FileCheck %s --check-prefix=POST-ON
+; RUN: %{post} %t/post-stale.ll -sample-profile-file=%t/prof.md5 -salvage-stale-profile 2>&1 | FileCheck %s --check-prefix=POST-ON
+;; Matching must collect R's anchors even when G has no root profile.
+; RUN: sed -n '/^R:/,$p' %t/prof.txt | %{merge} - -o %t/inner-only.extbinary
+; RUN: %if asserts %{ %{post} %t/post-stale.ll -sample-profile-file=%t/inner-only.extbinary -salvage-stale-profile -debug-only=sample-profile-matcher 2>&1 | FileCheck %s --check-prefix=INNER %}
+; INNER: Run stale profile matching for R
+; INNER: Callsite with callee:ext is matched from 3 to 2
+
+; POST-OFF-NOT: 'ext' inlined into 'G'
+; POST-ON: remark: a.c:2:0: 'ext' inlined into 'G' to match profiling context with (cost=always): preinliner
+; CHAIN: remark: a.c:4:0: 'ext' inlined into 'G' to match profiling context with (cost=always): preinliner
+; SHARED-DAG: remark: a.c:2:0: 'ext' inlined into 'G' {{.*}}preinliner
+; SHARED-DAG: remark: a.c:5:0: 'ext2' inlined into 'G' {{.*}}preinliner
+; LOADED2: 2 sample-profile - Number of orphaned root profiles loaded on demand
+; LOADED1: 1 sample-profile - Number of orphaned root profiles loaded on demand
+; LOADED0-NOT: orphaned root profiles
+
+;--- prof.txt
+G:2000:1000
+ 1: 1000
+ 2: 1000 R:1000
+ !CFGChecksum: 1
+R:2000:1000
+ 1: 1000
+ 2: ext:1000
+ 1: 1000
+ !CFGChecksum: 3
+ !Attributes: 2
+ !CFGChecksum: 2
+
+;--- prof-nested.txt
+G:2000:1000
+ 1: 1000
+ 2: R:1000
+ 1: 1000
+ 2: ext:1000
+ 1: 1000
+ !CFGChecksum: 3
+ !Attributes: 2
+ !CFGChecksum: 2
+ !CFGChecksum: 1
+R:2000:1000
+ 1: 1000
+ !CFGChecksum: 2
+
+;--- prof-chain.txt
+G:2000:1000
+ 1: 1000
+ 2: 1000 R:1000
+ !CFGChecksum: 1
+R:2000:1000
+ 1: 1000
+ 2: 1000 S:1000
+ !CFGChecksum: 2
+S:2000:1000
+ 1: 1000
+ 2: ext:1000
+ 1: 1000
+ !CFGChecksum: 3
+ !Attributes: 2
+ !CFGChecksum: 4
+
+;--- prof-shared.txt
+G:2000:1000
+ 1: 1000
+ 2: 1000 Q:500 R:500
+ !CFGChecksum: 1
+R:1000:500
+ 1: 500
+ 2: ext:500
+ 1: 500
+ !CFGChecksum: 3
+ !Attributes: 2
+ !CFGChecksum: 2
+Q:1000:500
+ 1: 500
+ 2: ext2:500
+ 1: 500
+ !CFGChecksum: 6
+ !Attributes: 2
+ !CFGChecksum: 5
+
+;--- post.ll
+;; pre.ll after pre-link with R inlined into G, and ext imported.
+source_filename = "a.c"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i64 @G(i64 %n) #0 !dbg !5 !guid !14 {
+ call void @llvm.pseudoprobe(i64 -6455552227143004193, i64 1, i32 0, i64 -1), !dbg !6
+ call void @llvm.pseudoprobe(i64 9084449867242398177, i64 1, i32 0, i64 -1), !dbg !15
+ %r = call i64 @ext(i64 %n), !dbg !16
+ ret i64 %r
+}
+
+!llvm.pseudo_probe_desc = !{!3, !4, !17}
+
+;--- post-chain.ll
+;; G with local R and S inlined: G -> R -> S -> ext.
+source_filename = "a.c"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i64 @G(i64 %n) #0 !dbg !5 !guid !14 {
+ call void @llvm.pseudoprobe(i64 -6455552227143004193, i64 1, i32 0, i64 -1), !dbg !6
+ call void @llvm.pseudoprobe(i64 9084449867242398177, i64 1, i32 0, i64 -1), !dbg !15
+ call void @llvm.pseudoprobe(i64 551554382388837469, i64 1, i32 0, i64 -1), !dbg !22
+ %r = call i64 @ext(i64 %n), !dbg !23
+ ret i64 %r
+}
+
+!llvm.pseudo_probe_desc = !{!3, !4, !17, !24}
+
+;--- post-shared.ll
+;; G with local R and Q inlined at the same site (!7).
+source_filename = "a.c"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i64 @G(i64 %n) #0 !dbg !5 !guid !14 {
+ call void @llvm.pseudoprobe(i64 -6455552227143004193, i64 1, i32 0, i64 -1), !dbg !6
+ call void @llvm.pseudoprobe(i64 9084449867242398177, i64 1, i32 0, i64 -1), !dbg !15
+ %r = call i64 @ext(i64 %n), !dbg !16
+ call void @llvm.pseudoprobe(i64 974280323357775344, i64 1, i32 0, i64 -1), !dbg !27
+ %q = call i64 @ext2(i64 %r), !dbg !29
+ ret i64 %q
+}
+
+define available_externally i64 @ext2(i64 %n) #0 !dbg !31 !guid !32 {
+ call void @llvm.pseudoprobe(i64 3613183346563194775, i64 1, i32 0, i64 -1), !dbg !34
+ ret i64 %n
+}
+
+!llvm.pseudo_probe_desc = !{!3, !4, !17, !30, !33}
+
+;--- common.ll
+define available_externally i64 @ext(i64 %n) #0 !dbg !18 !guid !19 {
+ call void @llvm.pseudoprobe(i64 -2953423517159131221, i64 1, i32 0, i64 -1), !dbg !20
+ ret i64 %n
+}
+
+;; Shared debug metadata; each body keeps its own probe descriptor list.
+declare void @llvm.pseudoprobe(i64, i64, i32, i64)
+
+attributes #0 = { "use-sample-profile" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: LineTablesOnly)
+!1 = !DIFile(filename: "a.c", directory: "")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i64 -6455552227143004193, i64 1, !"G"}
+!4 = !{i64 9084449867242398177, i64 2, !"R"}
+!5 = distinct !DISubprogram(name: "G", file: !1, line: 1, type: !13, spFlags: DISPFlagDefinition, unit: !0)
+!6 = !DILocation(line: 1, scope: !5)
+!7 = distinct !DILocation(line: 1, scope: !8)
+;; Discriminator 186646551 encodes direct call probe 2.
+!8 = !DILexicalBlockFile(scope: !5, file: !1, discriminator: 186646551)
+!9 = distinct !DISubprogram(name: "R", file: !1, line: 2, type: !13, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition, unit: !0)
+!10 = !DILocation(line: 2, scope: !9)
+!11 = !DILocation(line: 2, scope: !12)
+!12 = !DILexicalBlockFile(scope: !9, file: !1, discriminator: 186646551)
+!13 = !DISubroutineType(types: !{})
+!14 = !{i64 -6455552227143004193}
+!15 = !DILocation(line: 2, scope: !9, inlinedAt: !7)
+!16 = distinct !DILocation(line: 2, scope: !12, inlinedAt: !7)
+!17 = !{i64 -2953423517159131221, i64 3, !"ext"}
+!18 = distinct !DISubprogram(name: "ext", file: !1, line: 3, type: !13, spFlags: DISPFlagDefinition, unit: !0)
+!19 = !{i64 -2953423517159131221}
+!20 = !DILocation(line: 3, scope: !18)
+!21 = distinct !DISubprogram(name: "S", file: !1, line: 4, type: !13, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition, unit: !0)
+!22 = !DILocation(line: 4, scope: !21, inlinedAt: !16)
+!23 = !DILocation(line: 4, scope: !25, inlinedAt: !16)
+!24 = !{i64 551554382388837469, i64 4, !"S"}
+!25 = !DILexicalBlockFile(scope: !21, file: !1, discriminator: 186646551)
+!26 = distinct !DISubprogram(name: "Q", file: !1, line: 5, type: !13, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition, unit: !0)
+!27 = !DILocation(line: 5, scope: !26, inlinedAt: !7)
+!28 = !DILexicalBlockFile(scope: !26, file: !1, discriminator: 186646551)
+!29 = !DILocation(line: 5, scope: !28, inlinedAt: !7)
+!30 = !{i64 974280323357775344, i64 5, !"Q"}
+!31 = distinct !DISubprogram(name: "ext2", file: !1, line: 6, type: !13, spFlags: DISPFlagDefinition, unit: !0)
+!32 = !{i64 3613183346563194775}
+!33 = !{i64 3613183346563194775, i64 6, !"ext2"}
+!34 = !DILocation(line: 6, scope: !31)
+
+;--- imported-root.ll
+define available_externally i64 @R(i64 %n) #0 !dbg !9 {
+ call void @llvm.pseudoprobe(i64 9084449867242398177, i64 1, i32 0, i64 -1), !dbg !10
+ %r = call i64 @ext(i64 %n), !dbg !11
+ ret i64 %r
+}
diff --git a/llvm/test/Transforms/SampleProfile/thinlto-orphaned-nonlocal-root.ll b/llvm/test/Transforms/SampleProfile/thinlto-orphaned-nonlocal-root.ll
new file mode 100644
index 00000000000000..0a688dc61a003d
--- /dev/null
+++ b/llvm/test/Transforms/SampleProfile/thinlto-orphaned-nonlocal-root.ll
@@ -0,0 +1,104 @@
+; Recover a missing inline context from an eliminated function's separate
+; profile root. Pre-link import-hint preservation is tested separately in
+; thinlto-preserve-import-hints.ll.
+
+; RUN: split-file %s %t
+
+;; Post-link: H has no top-level profile, so finding R's root needs a scan of
+;; H's body from G's nested profile. R has no probe descriptor in G's module,
+;; as import does not copy descriptors.
+; RUN: llvm-profdata merge --sample --extbinary %t/prof.txt -o %t/prof.extbinary
+; DEFINE: %{post} = opt %t/post.ll -passes='thinlto<O2>' -pgo-kind=pgo-sample-use-pipeline \
+; DEFINE: -sample-profile-file=%t/prof.extbinary \
+; DEFINE: -pass-remarks=sample-profile-inline -o /dev/null
+; RUN: %{post} -sample-profile-preserve-orphaned-inlines=false 2>&1 | FileCheck %s --check-prefix=POST-OFF
+; RUN: %{post} 2>&1 \
+; RUN: | FileCheck %s --check-prefix=POST-ON
+;; The call-site check still applies.
+; RUN: sed 's/^R:2000:1000$/R:2000:2000/' %t/prof.txt | llvm-profdata merge --sample \
+; RUN: --extbinary - -o %t/prof-multi.extbinary
+; RUN: %{post} -sample-profile-file=%t/prof-multi.extbinary 2>&1 | FileCheck %s --check-prefix=POST-OFF
+
+;; Even without a profile for G or H, H's inline frames reveal R's root.
+;; Retrieval must not depend on top-down inlining or a reachable caller profile.
+; RUN: sed -n '/^R:/,$p' %t/prof.txt | llvm-profdata merge --sample --extbinary - -o %t/inner-only.extbinary
+; RUN: %if asserts %{ %{post} -sample-profile-file=%t/inner-only.extbinary -stats 2>&1 | FileCheck %s --check-prefix=LOADED %}
+; LOADED: 1 sample-profile - Number of orphaned root profiles loaded on demand
+
+; POST-OFF: 'H' inlined into 'G'
+; POST-OFF-NOT: 'ext' inlined into 'G'
+; POST-ON: 'H' inlined into 'G'
+; POST-ON: remark: a.c:2:0: 'ext' inlined into 'G' to match profiling context with (cost=always): preinliner
+
+;--- prof.txt
+G:3000:1000
+ 1: 1000
+ 2: H:2000
+ 1: 1000
+ 2: 1000 R:1000
+ !CFGChecksum: 4
+ !Attributes: 2
+ !CFGChecksum: 1
+R:2000:1000
+ 1: 1000
+ 2: ext:1000
+ 1: 1000
+ !CFGChecksum: 3
+ !Attributes: 2
+ !CFGChecksum: 2
+
+;--- post.ll
+;; G's module after import: H is imported with R inlined into it, and ext is
+;; imported. Only G and ext have probe descriptors.
+source_filename = "a.c"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i64 @G(i64 %n) #0 !dbg !5 !guid !14 {
+ call void @llvm.pseudoprobe(i64 -6455552227143004193, i64 1, i32 0, i64 -1), !dbg !6
+ %r = call i64 @H(i64 %n), !dbg !7
+ ret i64 %r
+}
+
+define available_externally i64 @H(i64 %n) #0 !dbg !21 !guid !22 {
+ call void @llvm.pseudoprobe(i64 1898973705195084225, i64 1, i32 0, i64 -1), !dbg !23
+ call void @llvm.pseudoprobe(i64 9084449867242398177, i64 1, i32 0, i64 -1), !dbg !15
+ %r = call i64 @ext(i64 %n), !dbg !16
+ ret i64 %r
+}
+
+define available_externally i64 @ext(i64 %n) #0 !dbg !18 !guid !19 {
+ call void @llvm.pseudoprobe(i64 -2953423517159131221, i64 1, i32 0, i64 -1), !dbg !20
+ ret i64 %n
+}
+
+declare void @llvm.pseudoprobe(i64, i64, i32, i64)
+
+attributes #0 = { "use-sample-profile" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2}
+!llvm.pseudo_probe_desc = !{!3, !17}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: LineTablesOnly)
+!1 = !DIFile(filename: "a.c", directory: "")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i64 -6455552227143004193, i64 1, !"G"}
+!5 = distinct !DISubprogram(name: "G", file: !1, line: 1, type: !13, spFlags: DISPFlagDefinition, unit: !0)
+!6 = !DILocation(line: 1, scope: !5)
+!7 = !DILocation(line: 1, scope: !8)
+!8 = !DILexicalBlockFile(scope: !5, file: !1, discriminator: 186646551)
+!9 = distinct !DISubprogram(name: "R", file: !1, line: 2, type: !13, spFlags: DISPFlagDefinition, unit: !0)
+!12 = !DILexicalBlockFile(scope: !9, file: !1, discriminator: 186646551)
+!13 = !DISubroutineType(types: !{})
+!14 = !{i64 -6455552227143004193}
+!15 = !DILocation(line: 2, scope: !9, inlinedAt: !24)
+!16 = !DILocation(line: 2, scope: !12, inlinedAt: !24)
+!17 = !{i64 -2953423517159131221, i64 3, !"ext"}
+!18 = distinct !DISubprogram(name: "ext", file: !1, line: 3, type: !13, spFlags: DISPFlagDefinition, unit: !0)
+!19 = !{i64 -2953423517159131221}
+!20 = !DILocation(line: 3, scope: !18)
+!21 = distinct !DISubprogram(name: "H", file: !1, line: 4, type: !13, spFlags: DISPFlagDefinition, unit: !0)
+!22 = !{i64 1898973705195084225}
+!23 = !DILocation(line: 4, scope: !21)
+!24 = distinct !DILocation(line: 4, scope: !25)
+!25 = !DILexicalBlockFile(scope: !21, file: !1, discriminator: 186646551)
More information about the llvm-branch-commits
mailing list