26#define DEBUG_TYPE "sample-profile-matcher"
29 "Number of functions matched by demangled basename");
35 cl::desc(
"Consider a profile matches a function if the similarity of their "
36 "callee sequences is above the specified percentile."));
40 cl::desc(
"The minimum number of basic blocks required for a function to "
41 "run stale profile call graph matching."));
45 cl::desc(
"The minimum number of call anchors required for a function to "
46 "run stale profile call graph matching."));
51 "Load top-level profiles that the sample reader initially skipped for "
52 "the call-graph matching (only meaningful for extended binary "
62 cl::desc(
"The maximum number of functions in a module, above which salvage "
63 "unused profile will be skipped."));
67 cl::desc(
"The maximum number of callsites in a function, above which stale "
68 "profile matching will be skipped."));
72void SampleProfileMatcher::findIRAnchors(
const Function &
F,
77 auto FindTopLevelInlinedCallsite = [](
const DILocation *DIL) {
78 assert((DIL && DIL->getInlinedAt()) &&
"No inlined callsite");
82 DIL = DIL->getInlinedAt();
83 }
while (DIL->getInlinedAt());
87 StringRef CalleeName = PrevDIL->getSubprogramLinkageName();
88 return std::make_pair(Callsite, FunctionId(CalleeName));
91 auto GetCanonicalCalleeName = [](
const CallBase *CB) {
92 StringRef CalleeName = UnknownIndirectCallee;
93 if (
Function *Callee = CB->getCalledFunction())
101 DILocation *DIL =
I.getDebugLoc();
108 if (DIL->getInlinedAt()) {
109 IRAnchors.emplace(FindTopLevelInlinedCallsite(DIL));
112 StringRef CalleeName;
116 CalleeName = GetCanonicalCalleeName(CB);
118 LineLocation Loc = LineLocation(Probe->Id, 0);
119 IRAnchors.emplace(Loc, FunctionId(CalleeName));
129 if (DIL->getInlinedAt()) {
130 IRAnchors.emplace(FindTopLevelInlinedCallsite(DIL));
135 IRAnchors.emplace(Callsite, FunctionId(CalleeName));
142void SampleProfileMatcher::findProfileAnchors(
const FunctionSamples &FS,
144 auto isInvalidLineOffset = [](uint32_t LineOffset) {
145 return LineOffset & 0x8000;
148 auto InsertAnchor = [](
const LineLocation &Loc,
const FunctionId &CalleeName,
150 auto Ret = ProfileAnchors.try_emplace(Loc, CalleeName);
154 Ret.first->second = FunctionId(UnknownIndirectCallee);
158 for (
const auto &
I :
FS.getBodySamples()) {
159 const LineLocation &Loc =
I.first;
163 const auto &CallTargets =
I.second.getCallTargets();
164 const bool HasSampledTarget =
165 llvm::any_of(CallTargets, [](
const auto &
C) {
return C.second != 0; });
166 for (
const auto &
C : CallTargets) {
170 if (HasSampledTarget &&
C.second == 0)
172 InsertAnchor(Loc,
C.first, ProfileAnchors);
176 for (
const auto &
I :
FS.getCallsiteSamples()) {
177 const LineLocation &Loc =
I.first;
181 const auto &Callees =
I.second;
183 Callees, [](
const auto &
C) {
return C.second.getTotalSamples() != 0; });
184 for (
const auto &
C : Callees) {
187 if (HasSampledCallee &&
C.second.getTotalSamples() == 0)
189 InsertAnchor(Loc,
C.first, ProfileAnchors);
194bool SampleProfileMatcher::anchorsMatch(
const FunctionId &IRAnchor,
202 return IRAnchor == ProfileAnchor ||
203 IRAnchor == FunctionId(UnknownIndirectCallee);
206bool SampleProfileMatcher::functionHasProfile(
const FunctionId &IRFuncName,
208 FuncWithoutProfile =
nullptr;
209 auto R = FunctionsWithoutProfile.find(IRFuncName);
210 if (R != FunctionsWithoutProfile.end())
211 FuncWithoutProfile =
R->second;
212 return !FuncWithoutProfile;
215bool SampleProfileMatcher::isProfileUnused(
const FunctionId &ProfileFuncName) {
218 return (SymbolMap->find(ProfileFuncName) == SymbolMap->end()) &&
222 (ProbeManager->getDesc(ProfileFuncName.
stringRef()) ==
nullptr));
225bool SampleProfileMatcher::functionMatchesProfile(
227 bool FindMatchedProfileOnly) {
228 if (IRFuncName == ProfileFuncName)
236 if (functionHasProfile(IRFuncName, IRFunc) ||
237 !isProfileUnused(ProfileFuncName))
241 "IR function should be different from profile function to match");
242 return functionMatchesProfile(*IRFunc, ProfileFuncName,
243 FindMatchedProfileOnly);
247SampleProfileMatcher::longestCommonSequence(
const AnchorList &AnchorList1,
249 bool MatchUnusedFunction) {
252 AnchorList1, AnchorList2,
253 [&](
const FunctionId &
A,
const FunctionId &
B) {
254 return functionMatchesProfile(
259 [&](LineLocation
A, LineLocation
B) {
262 return MatchedAnchors;
265void SampleProfileMatcher::matchNonCallsiteLocs(
268 auto UpdateMatching = [&](
const LineLocation &From,
const LineLocation &To) {
273 IRToProfileLocationMap.
erase(From);
277 int32_t LocationDelta = 0;
279 for (
const auto &
IR : IRAnchors) {
280 const auto &Loc =
IR.first;
281 bool IsMatchedAnchor =
false;
283 auto R = MatchedAnchors.
find(Loc);
284 if (R != MatchedAnchors.
end()) {
285 const auto &Candidate =
R->second;
286 UpdateMatching(Loc, Candidate);
288 <<
" is matched from " << Loc <<
" to " << Candidate
290 LocationDelta = Candidate.LineOffset - Loc.
LineOffset;
296 for (
size_t I = (LastMatchedNonAnchors.
size() + 1) / 2;
297 I < LastMatchedNonAnchors.
size();
I++) {
298 const auto &
L = LastMatchedNonAnchors[
I];
299 uint32_t CandidateLineOffset =
L.LineOffset + LocationDelta;
300 LineLocation Candidate(CandidateLineOffset,
L.Discriminator);
301 UpdateMatching(L, Candidate);
303 <<
" to " << Candidate <<
"\n");
306 IsMatchedAnchor =
true;
307 LastMatchedNonAnchors.
clear();
311 if (!IsMatchedAnchor) {
312 uint32_t CandidateLineOffset = Loc.
LineOffset + LocationDelta;
313 LineLocation Candidate(CandidateLineOffset, Loc.
Discriminator);
314 UpdateMatching(Loc, Candidate);
316 << Candidate <<
"\n");
324void SampleProfileMatcher::getFilteredAnchorList(
327 for (
const auto &
I : IRAnchors) {
328 if (
I.second.stringRef().empty())
330 FilteredIRAnchorsList.emplace_back(
I);
333 for (
const auto &
I : ProfileAnchors)
334 FilteredProfileAnchorList.emplace_back(
I);
354void SampleProfileMatcher::runStaleProfileMatching(
357 bool RunCFGMatching,
bool RunCGMatching) {
358 if (!RunCFGMatching && !RunCGMatching)
363 "Run stale profile matching only once per function");
367 getFilteredAnchorList(IRAnchors, ProfileAnchors, FilteredIRAnchorsList,
368 FilteredProfileAnchorList);
370 if (FilteredIRAnchorsList.empty() || FilteredProfileAnchorList.empty())
376 <<
" because the number of callsites in the IR is "
377 << FilteredIRAnchorsList.size()
378 <<
" and in the profile is "
379 << FilteredProfileAnchorList.size() <<
"\n");
394 longestCommonSequence(FilteredIRAnchorsList, FilteredProfileAnchorList,
401 for (
const auto &
IR : IRAnchors) {
402 bool ProfileConflicted =
false;
403 const auto &Loc =
IR.first;
407 FunctionId ProfAnchor;
408 auto AnchorLoc = MatchedAnchors.
find(Loc);
409 if (AnchorLoc == MatchedAnchors.
end()) {
412 auto PreMatched = FuncToProfileNameMap.find(Callee);
413 if (PreMatched == FuncToProfileNameMap.end())
415 ProfAnchor = PreMatched->second;
417 const auto &Prof = ProfileAnchors.find(AnchorLoc->second);
418 if (Prof == ProfileAnchors.end())
420 ProfAnchor = Prof->second;
424 auto Cached = MatchedAnchorCache.find(ProfAnchor);
425 if (Cached == MatchedAnchorCache.end())
426 MatchedAnchorCache[ProfAnchor] =
Callee;
427 else if (Cached->second != Callee)
428 ProfileConflicted =
true;
430 if (ProfileConflicted) {
433 const auto *FSForMatching = getFlattenedSamplesFor(ProfAnchor);
435 FSForMatching = Reader.getSamplesFor(ProfAnchor.
stringRef());
439 FunctionId NewAnchor(
441 auto R = FuncProfileMatchCache.find({
Callee, NewAnchor});
442 if (R != FuncProfileMatchCache.end() &&
R->second)
444 FunctionSamples &NewFS = FlattenedProfiles.create(NewAnchor);
445 NewFS.
merge(*FSForMatching);
446 FuncToProfileNameMap[
Callee] = NewAnchor;
447 FuncProfileMatchCache[{
Callee, NewAnchor}] =
true;
450 SampleProfileMap &Profiles = Reader.getProfiles();
451 SampleContext FContext(NewAnchor);
452 auto Res = Profiles.
try_emplace(FContext.getHashCode(), FContext, NewFS);
453 FunctionSamples &FProfile = Res.first->second;
463 matchNonCallsiteLocs(MatchedAnchors, IRAnchors, IRToProfileLocationMap);
466void SampleProfileMatcher::runOnFunction(
Function &
F) {
473 const auto *FSForMatching = getFlattenedSamplesFor(
F);
476 auto R = FuncToProfileNameMap.find(&
F);
477 if (R != FuncToProfileNameMap.end()) {
478 FSForMatching = getFlattenedSamplesFor(
R->second);
483 FSForMatching = Reader.getSamplesFor(
R->second.stringRef());
493 findIRAnchors(
F, IRAnchors);
497 findProfileAnchors(*FSForMatching, ProfileAnchors);
501 recordCallsiteMatchStates(
F, IRAnchors, ProfileAnchors,
nullptr);
508 !ProbeManager->profileIsValid(
F, *FSForMatching);
509 bool RunCFGMatching =
517 F.addFnAttr(
"profile-checksum-mismatch");
521 auto &IRToProfileLocationMap = getIRToProfileLocationMap(*FSForMatching);
522 runStaleProfileMatching(
F, IRAnchors, ProfileAnchors, IRToProfileLocationMap,
523 RunCFGMatching, RunCGMatching);
526 recordCallsiteMatchStates(
F, IRAnchors, ProfileAnchors,
527 &IRToProfileLocationMap);
530void SampleProfileMatcher::recordCallsiteMatchStates(
534 bool IsPostMatch = IRToProfileLocationMap !=
nullptr;
535 auto &CallsiteMatchStates =
538 auto MapIRLocToProfileLoc = [&](
const LineLocation &IRLoc) {
540 if (!IRToProfileLocationMap)
542 const auto &ProfileLoc = IRToProfileLocationMap->
find(IRLoc);
543 if (ProfileLoc != IRToProfileLocationMap->
end())
544 return ProfileLoc->second;
549 for (
const auto &
I : IRAnchors) {
552 const auto &ProfileLoc = MapIRLocToProfileLoc(
I.first);
553 const auto &IRCalleeId =
I.second;
554 const auto &It = ProfileAnchors.find(ProfileLoc);
555 if (It == ProfileAnchors.end())
557 const auto &ProfCalleeId = It->second;
558 if (anchorsMatch(IRCalleeId, ProfCalleeId)) {
559 auto It = CallsiteMatchStates.find(ProfileLoc);
560 if (It == CallsiteMatchStates.end())
561 CallsiteMatchStates.try_emplace(ProfileLoc, MatchState::InitialMatch);
562 else if (IsPostMatch) {
563 if (It->second == MatchState::InitialMatch)
564 It->second = MatchState::UnchangedMatch;
565 else if (It->second == MatchState::InitialMismatch)
566 It->second = MatchState::RecoveredMismatch;
573 for (
const auto &
I : ProfileAnchors) {
574 const auto &Loc =
I.first;
575 assert(!
I.second.stringRef().empty() &&
"Callees should not be empty");
576 auto It = CallsiteMatchStates.find(Loc);
577 if (It == CallsiteMatchStates.end())
578 CallsiteMatchStates.try_emplace(Loc, MatchState::InitialMismatch);
579 else if (IsPostMatch) {
582 if (It->second == MatchState::InitialMismatch)
583 It->second = MatchState::UnchangedMismatch;
584 else if (It->second == MatchState::InitialMatch)
585 It->second = MatchState::RemovedMatch;
590void SampleProfileMatcher::countMismatchedFuncSamples(
const FunctionSamples &FS,
592 const auto *FuncDesc = ProbeManager->getDesc(
FS.getGUID());
597 if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS)) {
599 NumStaleProfileFunc++;
604 MismatchedFunctionSamples +=
FS.getTotalSamples();
613 for (
const auto &
I :
FS.getCallsiteSamples())
614 for (
const auto &CS :
I.second)
615 countMismatchedFuncSamples(CS.second,
false);
618void SampleProfileMatcher::countMismatchedCallsiteSamples(
620 auto It = FuncCallsiteMatchStates.find(
FS.getFuncName());
622 if (It == FuncCallsiteMatchStates.end() || It->second.empty())
624 const auto &CallsiteMatchStates = It->second;
626 auto findMatchState = [&](
const LineLocation &Loc) {
627 auto It = CallsiteMatchStates.find(Loc);
628 if (It == CallsiteMatchStates.end())
629 return MatchState::Unknown;
633 auto AttributeMismatchedSamples = [&](
const enum MatchState &State,
635 if (isMismatchState(State))
636 MismatchedCallsiteSamples += Samples;
637 else if (State == MatchState::RecoveredMismatch)
638 RecoveredCallsiteSamples += Samples;
643 for (
const auto &
I :
FS.getBodySamples())
644 AttributeMismatchedSamples(findMatchState(
I.first),
I.second.getSamples());
647 for (
const auto &
I :
FS.getCallsiteSamples()) {
648 auto State = findMatchState(
I.first);
650 for (
const auto &CS :
I.second)
651 CallsiteSamples += CS.second.getTotalSamples();
652 AttributeMismatchedSamples(State, CallsiteSamples);
654 if (isMismatchState(State))
660 for (
const auto &CS :
I.second)
661 countMismatchedCallsiteSamples(CS.second);
665void SampleProfileMatcher::countMismatchCallsites(
const FunctionSamples &FS) {
666 auto It = FuncCallsiteMatchStates.find(
FS.getFuncName());
668 if (It == FuncCallsiteMatchStates.end() || It->second.empty())
670 const auto &MatchStates = It->second;
671 [[maybe_unused]]
bool OnInitialState =
672 isInitialState(MatchStates.begin()->second);
673 for (
const auto &
I : MatchStates) {
674 TotalProfiledCallsites++;
676 (OnInitialState ? isInitialState(
I.second) : isFinalState(
I.second)) &&
677 "Profile matching state is inconsistent");
679 if (isMismatchState(
I.second))
680 NumMismatchedCallsites++;
681 else if (
I.second == MatchState::RecoveredMismatch)
682 NumRecoveredCallsites++;
686void SampleProfileMatcher::countCallGraphRecoveredSamples(
689 if (CallGraphRecoveredProfiles.
count(
FS.getFunction())) {
690 NumCallGraphRecoveredFuncSamples +=
FS.getTotalSamples();
694 for (
const auto &CM :
FS.getCallsiteSamples()) {
695 for (
const auto &CS : CM.second) {
696 countCallGraphRecoveredSamples(CS.second, CallGraphRecoveredProfiles);
701void SampleProfileMatcher::computeAndReportProfileStaleness() {
705 DenseSet<FunctionId> CallGraphRecoveredProfiles;
707 for (
const auto &
I : FuncToProfileNameMap) {
708 CallGraphRecoveredProfiles.
insert(
I.second);
711 NumCallGraphRecoveredProfiledFunc++;
716 for (
const auto &
F : M) {
723 const auto *
FS = Reader.getSamplesFor(
F);
727 TotalFunctionSamples +=
FS->getTotalSamples();
730 countCallGraphRecoveredSamples(*FS, CallGraphRecoveredProfiles);
734 countMismatchedFuncSamples(*FS,
true);
737 countMismatchCallsites(*FS);
738 countMismatchedCallsiteSamples(*FS);
743 errs() <<
"(" << NumStaleProfileFunc <<
"/" << TotalProfiledFunc
744 <<
") of functions' profile are invalid and ("
745 << MismatchedFunctionSamples <<
"/" << TotalFunctionSamples
746 <<
") of samples are discarded due to function hash mismatch.\n";
749 errs() <<
"(" << NumCallGraphRecoveredProfiledFunc <<
"/"
750 << TotalProfiledFunc <<
") of functions' profile are matched and ("
751 << NumCallGraphRecoveredFuncSamples <<
"/" << TotalFunctionSamples
752 <<
") of samples are reused by call graph matching.\n";
755 errs() <<
"(" << (NumMismatchedCallsites + NumRecoveredCallsites) <<
"/"
756 << TotalProfiledCallsites
757 <<
") of callsites' profile are invalid and ("
758 << (MismatchedCallsiteSamples + RecoveredCallsiteSamples) <<
"/"
759 << TotalFunctionSamples
760 <<
") of samples are discarded due to callsite location mismatch.\n";
761 errs() <<
"(" << NumRecoveredCallsites <<
"/"
762 << (NumRecoveredCallsites + NumMismatchedCallsites)
763 <<
") of callsites and (" << RecoveredCallsiteSamples <<
"/"
764 << (RecoveredCallsiteSamples + MismatchedCallsiteSamples)
765 <<
") of samples are recovered by stale profile matching.\n";
769 LLVMContext &Ctx = M.getContext();
774 ProfStatsVec.
emplace_back(
"NumStaleProfileFunc", NumStaleProfileFunc);
775 ProfStatsVec.
emplace_back(
"TotalProfiledFunc", TotalProfiledFunc);
777 MismatchedFunctionSamples);
778 ProfStatsVec.
emplace_back(
"TotalFunctionSamples", TotalFunctionSamples);
782 ProfStatsVec.
emplace_back(
"NumCallGraphRecoveredProfiledFunc",
783 NumCallGraphRecoveredProfiledFunc);
784 ProfStatsVec.
emplace_back(
"NumCallGraphRecoveredFuncSamples",
785 NumCallGraphRecoveredFuncSamples);
788 ProfStatsVec.
emplace_back(
"NumMismatchedCallsites", NumMismatchedCallsites);
789 ProfStatsVec.
emplace_back(
"NumRecoveredCallsites", NumRecoveredCallsites);
790 ProfStatsVec.
emplace_back(
"TotalProfiledCallsites", TotalProfiledCallsites);
792 MismatchedCallsiteSamples);
794 RecoveredCallsiteSamples);
796 auto *MD = MDB.createLLVMStats(ProfStatsVec);
797 auto *NMD = M.getOrInsertNamedMetadata(
"llvm.stats");
802void SampleProfileMatcher::findFunctionsWithoutProfile() {
810 if (
F.isDeclaration())
814 const auto *
FS = getFlattenedSamplesFor(
F);
821 if (Reader.contains(CanonFName))
826 if (PSL && PSL->contains(CanonFName))
830 <<
" is not in profile or profile symbol list.\n");
831 FunctionsWithoutProfile[FunctionId(CanonFName)] = &
F;
839 auto FunctionName = FName.
str();
840 if (Demangler.partialDemangle(FunctionName.c_str()))
841 return std::string();
842 size_t BaseNameSize = 0;
846 char *BaseNamePtr = Demangler.getFunctionBaseName(
nullptr, &BaseNameSize);
847 std::string Result = (BaseNamePtr && BaseNameSize)
848 ? std::string(BaseNamePtr, BaseNameSize)
853 while (!Result.empty() && (Result.back() ==
' ' || Result.back() ==
'\0'))
858void SampleProfileMatcher::matchFunctionsWithoutProfileByBasename() {
861 auto NameTable = Reader.getNameTable();
862 if (NameTable.empty())
870 StringMap<Function *> OrphansByBaseName;
871 StringSet<> AmbiguousBaseNames;
872 for (
auto &[FuncId, Func] : FunctionsWithoutProfile) {
874 if (BaseName.empty() || AmbiguousBaseNames.
count(BaseName))
879 OrphansByBaseName.
erase(It);
880 AmbiguousBaseNames.
insert(BaseName);
883 if (OrphansByBaseName.
empty())
888 StringMap<FunctionId> CandidateByBaseName;
889 for (FunctionId ProfileFuncId : NameTable) {
890 StringRef ProfName = ProfileFuncId.stringRef();
891 if (ProfName.
empty())
895 if (ProfBaseName.empty())
898 if (OrphansByBaseName.
count(ProfBaseName)) {
899 if (AmbiguousBaseNames.
count(ProfBaseName))
903 CandidateByBaseName.
try_emplace(ProfBaseName, ProfileFuncId);
906 CandidateByBaseName.
erase(It);
907 AmbiguousBaseNames.
insert(ProfBaseName);
912 if (CandidateByBaseName.
empty())
916 DenseSet<StringRef> ToLoad;
917 for (
auto &[BaseName, ProfId] : CandidateByBaseName)
918 ToLoad.
insert(ProfId.stringRef());
921 unsigned MatchCount = 0;
922 SampleProfileMap NewlyLoadedProfiles;
923 for (
auto &[BaseName, ProfId] : CandidateByBaseName) {
924 if (!isProfileUnused(ProfId))
930 FuncToProfileNameMap[OrphanFunc] = ProfId;
931 MatchedAnchorCache[ProfId] = OrphanFunc;
932 if (
const auto *FS = Reader.getSamplesFor(ProfId.stringRef()))
936 <<
" (IR) -> " << ProfId <<
" (Profile)"
937 <<
" [basename: " << BaseName <<
"]\n");
942 if (!NewlyLoadedProfiles.empty())
946 NumDirectProfileMatch += MatchCount;
947 LLVM_DEBUG(
dbgs() <<
"Direct basename matching found " << MatchCount
951bool SampleProfileMatcher::functionMatchesProfileHelper(
955 float Similarity = 0.0;
962 if (!IRBaseName.empty() && IRBaseName == ProfBaseName) {
964 << ProfFunc <<
"(Profile) share the same base name: "
965 << IRBaseName <<
".\n");
969 const auto *FSForMatching = getFlattenedSamplesFor(ProfFunc);
976 DenseSet<StringRef> TopLevelFunc({ProfFunc.
stringRef()});
977 if (std::error_code EC = Reader.read(TopLevelFunc))
979 FSForMatching = Reader.getSamplesFor(ProfFunc.
stringRef());
984 SampleProfileMap TempProfiles;
985 TempProfiles.
create(FSForMatching->getFunction()).
merge(*FSForMatching);
988 FSForMatching = getFlattenedSamplesFor(ProfFunc);
992 dbgs() <<
"Read top-level function " << ProfFunc
993 <<
" for call-graph matching\n";
1008 const auto *FuncDesc = ProbeManager->getDesc(IRFunc);
1010 !ProbeManager->profileIsHashMismatched(*FuncDesc, *FSForMatching)) {
1012 <<
"(IR) and " << ProfFunc <<
"(Profile) match.\n");
1019 findIRAnchors(IRFunc, IRAnchors);
1021 findProfileAnchors(*FSForMatching, ProfileAnchors);
1025 getFilteredAnchorList(IRAnchors, ProfileAnchors, FilteredIRAnchorsList,
1026 FilteredProfileAnchorList);
1039 longestCommonSequence(FilteredIRAnchorsList, FilteredProfileAnchorList,
1042 Similarity =
static_cast<float>(MatchedAnchors.
size()) /
1043 FilteredProfileAnchorList.size();
1046 <<
"(IR) and " << ProfFunc <<
"(profile) is "
1047 <<
format(
"%.2f", Similarity) <<
"\n");
1048 assert((Similarity >= 0 && Similarity <= 1.0) &&
1049 "Similarity value should be in [0, 1]");
1055bool SampleProfileMatcher::functionMatchesProfile(
Function &IRFunc,
1057 bool FindMatchedProfileOnly) {
1058 auto R = FuncProfileMatchCache.find({&IRFunc, ProfFunc});
1059 if (R != FuncProfileMatchCache.end())
1062 if (FindMatchedProfileOnly)
1065 bool Matched = functionMatchesProfileHelper(IRFunc, ProfFunc);
1066 FuncProfileMatchCache[{&IRFunc, ProfFunc}] = Matched;
1068 FuncToProfileNameMap[&IRFunc] = ProfFunc;
1070 <<
" matches profile:" << ProfFunc <<
"\n");
1076void SampleProfileMatcher::UpdateWithSalvagedProfiles() {
1077 DenseSet<StringRef> ProfileSalvagedFuncs;
1079 for (
auto &
I : FuncToProfileNameMap) {
1080 assert(
I.first &&
"New function is null");
1081 FunctionId FuncName(
I.first->getName());
1082 ProfileSalvagedFuncs.
insert(
I.second.stringRef());
1083 FuncNameToProfNameMap->emplace(FuncName,
I.second);
1087 SymbolMap->erase(FuncName);
1088 [[maybe_unused]]
auto Ret = SymbolMap->emplace(
I.second,
I.first);
1091 dbgs() <<
"Profile Function " <<
I.second
1092 <<
" has already been matched to another IR function.\n";
1100 Reader.read(ProfileSalvagedFuncs);
1101 Reader.setFuncNameToProfNameMap(*FuncNameToProfNameMap);
1113 findFunctionsWithoutProfile();
1114 matchFunctionsWithoutProfileByBasename();
1119 std::vector<Function *> TopDownFunctionList;
1120 TopDownFunctionList.reserve(M.size());
1122 for (
auto *
F : TopDownFunctionList) {
1129 UpdateWithSalvagedProfiles();
1132 distributeIRToProfileLocationMap();
1134 computeAndReportProfileStaleness();
1137void SampleProfileMatcher::distributeIRToProfileLocationMap(
1139 const auto ProfileMappings = FuncMappings.find(FS.getFuncName());
1140 if (ProfileMappings != FuncMappings.end()) {
1141 FS.setIRToProfileLocationMap(&(ProfileMappings->second));
1144 for (
auto &Callees :
1146 for (
auto &FS : Callees.second) {
1147 distributeIRToProfileLocationMap(FS.second);
1154void SampleProfileMatcher::distributeIRToProfileLocationMap() {
1155 for (
auto &
I : Reader.getProfiles()) {
1156 distributeIRToProfileLocationMap(
I.second);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
itanium_demangle::ManglingParser< DefaultAllocator > Demangler
Legalize the Machine IR a function s Machine IR
static std::string getDemangledBaseName(ItaniumPartialDemangler &Demangler, StringRef FName)
This file provides the interface for SampleProfileMatcher.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert_or_assign(const KeyT &Key, V &&Val)
Implements a dense probed hash-table based set.
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
LLVM_ABI void runOnModule()
reference emplace_back(ArgTypes &&... Args)
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
constexpr bool empty() const
Check if the string is empty.
std::pair< typename Base::iterator, bool > insert(StringRef key)
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
This class represents a function that is read from a sample profile.
StringRef stringRef() const
Convert to StringRef.
bool isStringRef() const
Check if this object represents a StringRef, or a hash code.
Representation of the samples collected for a function.
static LLVM_ABI std::atomic< bool > ProfileIsFS
If this profile uses flow sensitive discriminators.
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
void setContext(const SampleContext &FContext)
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.
std::pair< iterator, bool > try_emplace(const key_type &Hash, const original_key_type &Key, Ts &&...Args)
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
mapped_type & create(const SampleContext &Ctx)
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
DenseMap< LineLocation, LineLocation > LocToLocMap
This is an optimization pass for GlobalISel generic memory operations.
cl::opt< bool > ReportProfileStaleness("report-profile-staleness", cl::Hidden, cl::init(false), cl::desc("Compute and report stale profile statistical metrics."))
cl::opt< bool > PersistProfileStaleness("persist-profile-staleness", cl::Hidden, cl::init(false), cl::desc("Compute stale profile statistical metrics and write it into the " "native object file(.llvm_stats section)."))
std::map< LineLocation, FunctionId > AnchorMap
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
static cl::opt< bool > LoadFuncProfileforCGMatching("load-func-profile-for-cg-matching", cl::Hidden, cl::init(true), cl::desc("Load top-level profiles that the sample reader initially skipped for " "the call-graph matching (only meaningful for extended binary " "format)"))
static cl::opt< unsigned > SalvageUnusedProfileMaxFunctions("salvage-unused-profile-max-functions", cl::Hidden, cl::init(UINT_MAX), cl::desc("The maximum number of functions in a module, above which salvage " "unused profile will be skipped."))
static void buildTopDownFuncOrder(LazyCallGraph &CG, std::vector< Function * > &FunctionOrderList)
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
static cl::opt< unsigned > MinCallCountForCGMatching("min-call-count-for-cg-matching", cl::Hidden, cl::init(3), cl::desc("The minimum number of call anchors required for a function to " "run stale profile call graph matching."))
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.
static cl::opt< unsigned > MinFuncCountForCGMatching("min-func-count-for-cg-matching", cl::Hidden, cl::init(5), cl::desc("The minimum number of basic blocks required for a function to " "run stale profile call graph matching."))
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
cl::opt< bool > SalvageStaleProfile("salvage-stale-profile", cl::Hidden, cl::init(false), cl::desc("Salvage stale profile by fuzzy matching and use the remapped " "location for sample profile query."))
void longestCommonSequence(AnchorList AnchorList1, AnchorList AnchorList2, llvm::function_ref< bool(const Function &, const Function &)> FunctionMatchesProfile, llvm::function_ref< void(Loc, Loc)> InsertMatching)
std::vector< std::pair< LineLocation, FunctionId > > AnchorList
static bool skipProfileForFunction(const Function &F)
cl::opt< bool > SalvageUnusedProfile("salvage-unused-profile", cl::Hidden, cl::init(false), cl::desc("Salvage unused profile by matching with new " "functions on call graph."))
static cl::opt< unsigned > SalvageStaleProfileMaxCallsites("salvage-stale-profile-max-callsites", cl::Hidden, cl::init(UINT_MAX), cl::desc("The maximum number of callsites in a function, above which stale " "profile matching will be skipped."))
static cl::opt< unsigned > FuncProfileSimilarityThreshold("func-profile-similarity-threshold", cl::Hidden, cl::init(80), cl::desc("Consider a profile matches a function if the similarity of their " "callee sequences is above the specified percentile."))