90#include <system_error>
97#define DEBUG_TYPE "sample-profile"
98#define CSINLINE_DEBUG DEBUG_TYPE "-inline"
101 "Number of functions inlined with context sensitive profile");
103 "Number of functions not inlined with context sensitive profile");
105 "Number of functions with CFG mismatched profile");
106STATISTIC(NumMatchedProfile,
"Number of functions with CFG matched profile");
108 "Number of inlined callsites with a partial distribution factor");
111 "Number of functions with FDO inline stopped due to min size limit");
113 "Number of functions with FDO inline stopped due to max size limit");
115 NumCSInlinedHitGrowthLimit,
116 "Number of functions with FDO inline stopped due to growth size limit");
126using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
130class GUIDToFuncNameMapper {
135 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
139 for (
const auto &
F : CurrentModule) {
141 CurrentGUIDToFuncNameMap.insert(
152 if (CanonName != OrigName)
153 CurrentGUIDToFuncNameMap.insert(
158 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
161 ~GUIDToFuncNameMapper() {
165 CurrentGUIDToFuncNameMap.clear();
169 SetGUIDToFuncNameMapForAll(
nullptr);
174 std::queue<FunctionSamples *> FSToUpdate;
176 FSToUpdate.push(&IFS.second);
179 while (!FSToUpdate.empty()) {
182 FS->GUIDToFuncNameMap = Map;
183 for (
const auto &ICS : FS->getCallsiteSamples()) {
185 for (
const auto &IFS : FSMap) {
187 FSToUpdate.push(&FS);
199struct InlineCandidate {
201 const FunctionSamples *CalleeSamples;
209 float CallsiteDistribution;
213struct CandidateComparer {
214 bool operator()(
const InlineCandidate &
LHS,
const InlineCandidate &
RHS) {
215 if (
LHS.CallsiteCount !=
RHS.CallsiteCount)
216 return LHS.CallsiteCount <
RHS.CallsiteCount;
218 const FunctionSamples *LCS =
LHS.CalleeSamples;
219 const FunctionSamples *RCS =
RHS.CalleeSamples;
234using CandidateQueue =
246 const IPOOptions &Opts, StringRef Name, StringRef RemapName,
248 std::function<AssumptionCache &(
Function &)> GetAssumptionCache,
249 std::function<TargetTransformInfo &(
Function &)> GetTargetTransformInfo,
250 std::function<
const TargetLibraryInfo &(
Function &)> GetTLI,
251 LazyCallGraph &CG,
bool DisableSampleProfileInlining,
252 bool UseFlattenedProfile)
255 Opts(Opts), ProfileMergeInlinee(Opts.sample_profile_merge_inlinee),
256 ProfileSizeInline(
valueOr(Opts.sample_profile_inline_size,
false)),
257 CallsitePrioritizedInline(
258 valueOr(Opts.sample_profile_prioritized_inline,
false)),
259 AllowRecursiveInline(
261 UsePreInlinerDecision(
263 SalvageStaleProfile(
valueOr(Opts.salvage_stale_profile,
false)),
264 SalvageUnusedProfile(
valueOr(Opts.salvage_unused_profile,
false)),
265 GetAC(std::
move(GetAssumptionCache)),
266 GetTTI(std::
move(GetTargetTransformInfo)), GetTLI(std::
move(GetTLI)),
267 CG(CG), LTOPhase(LTOPhase),
268 AnnotatedPassName(Opts.annotate_sample_profile_inline_phase
272 DisableSampleProfileInlining(DisableSampleProfileInlining),
273 UseFlattenedProfile(UseFlattenedProfile) {}
277 ProfileSummaryInfo *_PSI);
280 const IPOOptions &Opts;
282 bool ProfileMergeInlinee;
283 bool ProfileSizeInline;
284 bool CallsitePrioritizedInline;
285 bool AllowRecursiveInline;
286 bool UsePreInlinerDecision;
287 bool SalvageStaleProfile;
288 bool SalvageUnusedProfile;
289 SampleProfileInlineOptions InlineOpts;
293 ErrorOr<uint64_t> getInstWeight(
const Instruction &
I)
override;
294 const FunctionSamples *findCalleeFunctionSamples(
const CallBase &
I)
const;
295 const FunctionSamples *
296 findFunctionSamples(
const Instruction &
I)
const override;
297 std::vector<const FunctionSamples *>
298 findIndirectCallFunctionSamples(
const Instruction &
I,
uint64_t &Sum)
const;
299 void findExternalInlineCandidate(CallBase *CB,
const FunctionSamples *Samples,
300 DenseSet<GlobalValue::GUID> &InlinedGUIDs,
303 bool tryPromoteAndInlineCandidate(
308 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
309 std::optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
310 bool getExternalInlineAdvisorShouldInline(CallBase &CB);
311 InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
312 bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
314 tryInlineCandidate(InlineCandidate &Candidate,
317 inlineHotFunctionsWithPriority(
Function &
F,
318 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
320 bool shouldInlineColdCallee(CallBase &CallInst);
321 void emitOptimizationRemarksForInlineCandidates(
322 const SmallVectorImpl<CallBase *> &Candidates,
const Function &
F,
324 void promoteMergeNotInlinedContextSamples(
325 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
327 std::vector<Function *> buildFunctionOrder(
Module &M, LazyCallGraph &CG);
328 std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(
Module &M);
329 void generateMDProfMetadata(
Function &
F);
330 bool rejectHighStalenessProfile(
Module &M, ProfileSummaryInfo *PSI,
331 const SampleProfileMap &Profiles);
332 void removePseudoProbeInstsDiscriminator(
Module &M);
338 HashKeyMap<DenseMap, FunctionId, Function *> SymbolMap;
342 HashKeyMap<DenseMap, FunctionId, FunctionId> FuncNameToProfNameMap;
344 std::function<AssumptionCache &(
Function &)> GetAC;
345 std::function<TargetTransformInfo &(
Function &)> GetTTI;
346 std::function<
const TargetLibraryInfo &(
Function &)> GetTLI;
350 std::unique_ptr<SampleContextTracker> ContextTracker;
358 const std::string AnnotatedPassName;
362 std::shared_ptr<ProfileSymbolList> PSL;
367 struct NotInlinedProfileInfo {
370 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
374 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
381 bool ProfAccForSymsInList;
383 bool DisableSampleProfileInlining;
385 bool UseFlattenedProfile;
388 std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
391 std::unique_ptr<SampleProfileMatcher> MatchingManager;
394 const char *getAnnotatedRemarkPassName()
const {
395 return AnnotatedPassName.c_str();
402inline bool SampleProfileInference<Function>::isExit(
const BasicBlock *BB) {
407inline void SampleProfileInference<Function>::findUnlikelyJumps(
408 const std::vector<const BasicBlockT *> &BasicBlocks,
410 for (
auto &Jump :
Func.Jumps) {
411 const auto *BB = BasicBlocks[Jump.Source];
412 const auto *Succ = BasicBlocks[Jump.Target];
416 const auto &Succs = Successors[BB];
417 if (Succs.size() == 2 && Succs.back() == Succ) {
419 Jump.IsUnlikely =
true;
426 Jump.IsUnlikely =
true;
447 return getProbeWeight(Inst);
451 return std::error_code();
457 return std::error_code();
467 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
470 return getInstWeightImpl(Inst);
485const FunctionSamples *
486SampleProfileLoader::findCalleeFunctionSamples(
const CallBase &Inst)
const {
492 StringRef CalleeName;
494 CalleeName =
Callee->getName();
497 return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
499 const FunctionSamples *
FS = findFunctionSamples(Inst);
504 CalleeName, Reader->getRemapper(),
505 &FuncNameToProfNameMap);
511std::vector<const FunctionSamples *>
512SampleProfileLoader::findIndirectCallFunctionSamples(
513 const Instruction &Inst,
uint64_t &Sum)
const {
515 std::vector<const FunctionSamples *>
R;
521 auto FSCompare = [](
const FunctionSamples *
L,
const FunctionSamples *
R) {
522 assert(L && R &&
"Expect non-null FunctionSamples");
523 if (
L->getHeadSamplesEstimate() !=
R->getHeadSamplesEstimate())
524 return L->getHeadSamplesEstimate() >
R->getHeadSamplesEstimate();
525 return L->getGUID() <
R->getGUID();
530 ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
531 if (CalleeSamples.empty())
537 for (
const auto *
const FS : CalleeSamples) {
538 Sum +=
FS->getHeadSamplesEstimate();
545 const FunctionSamples *
FS = findFunctionSamples(Inst);
551 if (
auto T =
FS->findCallTargetMapAt(CallSite))
552 for (
const auto &T_C : *
T)
557 for (
const auto &NameFS : *M) {
558 Sum += NameFS.second.getHeadSamplesEstimate();
559 R.push_back(&NameFS.second);
566const FunctionSamples *
567SampleProfileLoader::findFunctionSamples(
const Instruction &Inst)
const {
578 auto it = DILocation2SampleMap.try_emplace(DIL,
nullptr);
581 it.first->second = ContextTracker->getContextSamplesFor(DIL);
583 it.first->second = Samples->findFunctionSamples(
584 DIL, Reader->getRemapper(), &FuncNameToProfNameMap);
586 return it.first->second;
600 Opts.sample_profile_icp_max_prom,
604 if (ValueData.empty())
607 unsigned NumPromoted = 0;
608 for (
const auto &
V : ValueData) {
619 if (NumPromoted == Opts.sample_profile_icp_max_prom)
639 if (Opts.sample_profile_icp_max_prom == 0)
645 Opts.sample_profile_icp_max_prom, OldSum,
true);
651 "If sum is 0, assume only one element in CallTargets "
652 "with count being NOMORE_ICP_MAGICNUM");
654 for (
const auto &
V : ValueData)
655 ValueCountMap[
V.Value] =
V.Count;
661 OldSum -= Pair.first->second;
668 for (
const auto &
V : ValueData) {
670 ValueCountMap[
V.Value] =
V.Count;
673 for (
const auto &
Data : CallTargets) {
680 assert(Sum >=
Data.Count &&
"Sum should never be less than Data.Count");
686 for (
const auto &ValueCount : ValueCountMap) {
688 InstrProfValueData{ValueCount.first, ValueCount.second});
692 [](
const InstrProfValueData &L,
const InstrProfValueData &R) {
693 return std::tie(L.Count, L.Value) > std::tie(R.Count, R.Value);
697 std::min(NewCallTargets.
size(),
698 static_cast<size_t>(Opts.sample_profile_icp_max_prom));
700 NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
713bool SampleProfileLoader::tryPromoteAndInlineCandidate(
717 if (DisableSampleProfileInlining)
722 if (Opts.sample_profile_icp_max_prom == 0)
724 auto CalleeFunctionName = Candidate.CalleeSamples->
getFunction();
725 auto R = SymbolMap.find(CalleeFunctionName);
726 if (R == SymbolMap.end() || !
R->second)
729 auto &CI = *Candidate.CallInstr;
733 const char *Reason =
"Callee function not available";
740 if (!
R->second->isDeclaration() &&
R->second->getSubprogram() &&
741 R->second->hasFnAttribute(
"use-sample-profile") &&
746 Function::getGUIDAssumingExternalLinkage(
R->second->getName()),
751 CI,
R->second, Candidate.CallsiteCount, Sum,
false, ORE);
753 Sum -= Candidate.CallsiteCount;
766 Candidate.CallInstr = DI;
768 bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
773 *DI,
static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
781 Candidate.CallInstr->
getName())<<
" because "
787bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
788 if (!ProfileSizeInline)
796 GetTTI(*CallInst.
getCaller()), GetAC, GetTLI);
807void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
808 const SmallVectorImpl<CallBase *> &Candidates,
const Function &
F,
810 for (
auto *
I : Candidates) {
811 Function *CalledFunction =
I->getCalledFunction();
812 if (CalledFunction) {
813 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
814 "InlineAttempt",
I->getDebugLoc(),
816 <<
"previous inlining reattempted for "
817 << (
Hot ?
"hotness: '" :
"size: '")
818 <<
ore::NV(
"Callee", CalledFunction) <<
"' into '"
824void SampleProfileLoader::findExternalInlineCandidate(
825 CallBase *CB,
const FunctionSamples *Samples,
826 DenseSet<GlobalValue::GUID> &InlinedGUIDs,
uint64_t Threshold) {
831 bool IncludeLocalTargets = Opts.sample_profile_preserve_deferred_inlines &&
836 if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
840 InlinedGUIDs.
insert(Function::getGUIDAssumingExternalLinkage(
860 if (UsePreInlinerDecision)
863 IncludeLocalTargets);
867 ContextTrieNode *
Caller = ContextTracker->getContextNodeForProfile(Samples);
868 std::queue<ContextTrieNode *> CalleeList;
869 CalleeList.push(Caller);
870 while (!CalleeList.empty()) {
871 ContextTrieNode *
Node = CalleeList.front();
873 FunctionSamples *CalleeSample =
Node->getFunctionSamples();
882 UsePreInlinerDecision &&
890 InlinedGUIDs, SymbolMap, CalleeSample->
getFunction(),
896 for (
const auto &TS : BS.second.getCallTargets())
897 if (TS.second > Threshold)
899 IncludeLocalTargets);
905 for (
auto &Child :
Node->getAllChildContext()) {
906 ContextTrieNode *CalleeNode = &Child.second;
907 CalleeList.push(CalleeNode);
934bool SampleProfileLoader::inlineHotFunctions(
935 Function &
F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
938 assert((!ProfAccForSymsInList ||
939 (!Opts.profile_sample_accurate &&
940 !
F.hasFnAttribute(
"profile-sample-accurate"))) &&
941 "ProfAccForSymsInList should be false when profile-sample-accurate "
944 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
946 bool LocalChanged =
true;
947 while (LocalChanged) {
948 LocalChanged =
false;
955 const FunctionSamples *
FS =
nullptr;
958 if ((FS = findCalleeFunctionSamples(*CB))) {
960 "GUIDToFuncNameMap has to be populated");
962 if (
FS->getHeadSamplesEstimate() > 0 ||
964 LocalNotInlinedCallSites.
insert({CB,
FS});
967 else if (shouldInlineColdCallee(*CB))
969 }
else if (getExternalInlineAdvisorShouldInline(*CB)) {
975 if (
Hot || ExternalInlineAdvisor) {
977 emitOptimizationRemarksForInlineCandidates(AllCandidates,
F,
true);
980 emitOptimizationRemarksForInlineCandidates(ColdCandidates,
F,
false);
983 for (CallBase *
I : CIS) {
984 Function *CalledFunction =
I->getCalledFunction();
985 InlineCandidate Candidate = {
I, LocalNotInlinedCallSites.
lookup(
I),
989 if (CalledFunction == &
F)
991 if (
I->isIndirectCall()) {
993 for (
const auto *FS : findIndirectCallFunctionSamples(*
I, Sum)) {
995 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
996 findExternalInlineCandidate(
I, FS, InlinedGUIDs,
997 PSI->getOrCompHotCountThreshold());
1003 Candidate = {
I,
FS,
FS->getHeadSamplesEstimate(), 1.0};
1004 if (tryPromoteAndInlineCandidate(
F, Candidate, SumOrigin, Sum)) {
1005 LocalNotInlinedCallSites.
erase(
I);
1006 LocalChanged =
true;
1009 }
else if (CalledFunction && CalledFunction->
getSubprogram() &&
1011 if (tryInlineCandidate(Candidate)) {
1012 LocalNotInlinedCallSites.
erase(
I);
1013 LocalChanged =
true;
1015 }
else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1016 findExternalInlineCandidate(
I, findCalleeFunctionSamples(*
I),
1018 PSI->getOrCompHotCountThreshold());
1027 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites,
F);
1031bool SampleProfileLoader::tryInlineCandidate(
1035 if (DisableSampleProfileInlining)
1038 CallBase &CB = *Candidate.CallInstr;
1040 assert(CalledFunction &&
"Expect a callee with definition");
1044 InlineCost
Cost = shouldInlineCandidate(Candidate);
1045 if (
Cost.isNever()) {
1046 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1047 "InlineFail", DLoc, BB)
1048 <<
"incompatible inlining");
1055 InlineFunctionInfo IFI(GetAC);
1056 IFI.UpdateProfile =
false;
1059 if (!
IR.isSuccess())
1064 Cost,
true, getAnnotatedRemarkPassName());
1067 if (InlinedCallSites) {
1068 InlinedCallSites->
clear();
1073 ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1083 if (Candidate.CallsiteDistribution < 1) {
1084 for (
auto &
I : IFI.InlinedCallSites) {
1087 Candidate.CallsiteDistribution);
1089 NumDuplicatedInlinesite++;
1095bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1097 assert(CB &&
"Expect non-null call instruction");
1103 const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1106 if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
1110 if (std::optional<PseudoProbe> Probe =
extractProbe(*CB))
1111 Factor = Probe->Factor;
1115 *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1119std::optional<InlineCost>
1120SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
1121 std::unique_ptr<InlineAdvice> Advice =
nullptr;
1122 if (ExternalInlineAdvisor) {
1123 Advice = ExternalInlineAdvisor->getAdvice(CB);
1125 if (!Advice->isInliningRecommended()) {
1126 Advice->recordUnattemptedInlining();
1129 Advice->recordInlining();
1137bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
1138 std::optional<InlineCost>
Cost = getExternalInlineAdvisorCost(CB);
1143SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1144 if (std::optional<InlineCost> ReplayCost =
1145 getExternalInlineAdvisorCost(*Candidate.CallInstr))
1150 if (CallsitePrioritizedInline) {
1151 if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1153 else if (!ProfileSizeInline)
1159 assert(Callee &&
"Expect a definition for inline candidate of direct call");
1172 GetTTI(*Caller), GetAC, GetTLI);
1175 if (
Cost.isNever() ||
Cost.isAlways())
1187 if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1200 if (!CallsitePrioritizedInline) {
1209bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1210 Function &
F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1213 assert((!ProfAccForSymsInList ||
1214 (!Opts.profile_sample_accurate &&
1215 !
F.hasFnAttribute(
"profile-sample-accurate"))) &&
1216 "ProfAccForSymsInList should be false when profile-sample-accurate "
1221 CandidateQueue CQueue;
1222 InlineCandidate NewCandidate;
1223 for (
auto &BB :
F) {
1225 if (getInlineCandidate(&NewCandidate, &CB))
1226 CQueue.push(NewCandidate);
1235 "Max inline size limit should not be smaller than min inline size "
1240 if (ExternalInlineAdvisor)
1241 SizeLimit = std::numeric_limits<unsigned>::max();
1243 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1247 while (!CQueue.empty() &&
F.getInstructionCount() <
SizeLimit) {
1248 InlineCandidate Candidate = CQueue.top();
1250 CallBase *
I = Candidate.CallInstr;
1251 Function *CalledFunction =
I->getCalledFunction();
1253 if (CalledFunction == &
F)
1255 if (
I->isIndirectCall()) {
1257 auto CalleeSamples = findIndirectCallFunctionSamples(*
I, Sum);
1259 Sum *= Candidate.CallsiteDistribution;
1260 unsigned ICPCount = 0;
1261 for (
const auto *FS : CalleeSamples) {
1263 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1264 findExternalInlineCandidate(
I, FS, InlinedGUIDs,
1265 PSI->getOrCompHotCountThreshold());
1269 FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
1274 if (ICPCount >= Opts.sample_profile_icp_relative_hotness_skip &&
1275 EntryCountDistributed * 100 <
1276 SumOrigin * Opts.sample_profile_icp_relative_hotness)
1285 if (!PSI->isHotCount(EntryCountDistributed))
1290 Candidate = {
I,
FS, EntryCountDistributed,
1291 Candidate.CallsiteDistribution};
1292 if (tryPromoteAndInlineCandidate(
F, Candidate, SumOrigin, Sum,
1293 &InlinedCallSites)) {
1294 for (
auto *CB : InlinedCallSites) {
1295 if (getInlineCandidate(&NewCandidate, CB))
1296 CQueue.emplace(NewCandidate);
1300 }
else if (!ContextTracker) {
1301 LocalNotInlinedCallSites.
insert({
I,
FS});
1304 }
else if (CalledFunction && CalledFunction->
getSubprogram() &&
1307 if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1308 for (
auto *CB : InlinedCallSites) {
1309 if (getInlineCandidate(&NewCandidate, CB))
1310 CQueue.emplace(NewCandidate);
1313 }
else if (!ContextTracker) {
1314 LocalNotInlinedCallSites.
insert({
I, Candidate.CalleeSamples});
1316 }
else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1317 findExternalInlineCandidate(
I, findCalleeFunctionSamples(*
I),
1319 PSI->getOrCompHotCountThreshold());
1323 if (!CQueue.empty()) {
1325 ++NumCSInlinedHitMaxLimit;
1327 ++NumCSInlinedHitMinLimit;
1329 ++NumCSInlinedHitGrowthLimit;
1335 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites,
F);
1339void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1340 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
1343 for (
const auto &Pair : NonInlinedCallSites) {
1344 CallBase *
I = Pair.first;
1346 if (!Callee ||
Callee->isDeclaration())
1350 OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
"NotInline",
1351 I->getDebugLoc(),
I->getParent())
1352 <<
"previous inlining not repeated: '" <<
ore::NV(
"Callee", Callee)
1353 <<
"' into '" <<
ore::NV(
"Caller", &
F) <<
"'");
1356 const FunctionSamples *
FS = Pair.second;
1357 if (
FS->getTotalSamples() == 0 &&
FS->getHeadSamplesEstimate() == 0) {
1365 if (ProfileMergeInlinee) {
1371 if (
FS->getHeadSamples() == 0) {
1374 const_cast<FunctionSamples *
>(
FS)->addHeadSamples(
1375 FS->getHeadSamplesEstimate());
1380 FunctionSamples *OutlineFS = Reader->getSamplesFor(*Callee);
1384 OutlineFS = &OutlineFunctionSamples[
1386 OutlineFS->
merge(*FS, 1);
1392 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1393 pair.first->second.entryCount +=
FS->getHeadSamplesEstimate();
1404 InstrProfValueData{
I.first.getHashCode(),
I.second});
1411void SampleProfileLoader::generateMDProfMetadata(
Function &
F) {
1414 LLVM_DEBUG(
dbgs() <<
"\nPropagation complete. Setting branch weights\n");
1415 LLVMContext &Ctx =
F.getContext();
1417 for (
auto &BI :
F) {
1420 if (BlockWeights[BB]) {
1421 for (
auto &
I : *BB) {
1428 const DILocation *DIL = DLoc;
1429 const FunctionSamples *
FS = findFunctionSamples(
I);
1433 ErrorOr<SampleRecord::CallTargetMap>
T =
1434 FS->findCallTargetMapAt(CallSite);
1435 if (!
T ||
T.get().empty())
1442 if (Probe->Factor < 1)
1449 for (
const auto &
C :
T.get())
1456 FS->findFunctionSamplesMapAt(CallSite)) {
1457 for (
const auto &NameFS : *M)
1458 Sum += NameFS.second.getHeadSamplesEstimate();
1463 else if (Opts.overwrite_existing_weights)
1464 I.setMetadata(LLVMContext::MD_prof,
nullptr);
1467 I, ArrayRef<uint32_t>{
static_cast<uint32_t
>(BlockWeights[BB])},
1471 }
else if (Opts.overwrite_existing_weights ||
1472 Opts.profile_sample_block_accurate) {
1475 for (
auto &
I : *BB) {
1478 I.setMetadata(LLVMContext::MD_prof,
nullptr);
1496 << ((BranchLoc) ? Twine(BranchLoc.
getLine())
1497 : Twine(
"<UNKNOWN LOCATION>"))
1499 SmallVector<uint32_t, 4> Weights;
1500 uint32_t MaxWeight = 0;
1505 DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
1506 std::vector<uint64_t> EdgeIndex;
1511 EdgeIndex[
I] = EdgeMultiplicity[Succ];
1512 EdgeMultiplicity[Succ]++;
1517 Edge E = std::make_pair(BB, Succ);
1523 if (Weight > std::numeric_limits<uint32_t>::max()) {
1525 Weight = std::numeric_limits<uint32_t>::max();
1530 Weights.
push_back(
static_cast<uint32_t
>(
1531 Weight == std::numeric_limits<uint32_t>::max() ? Weight
1536 uint64_t W = Weight / EdgeMultiplicity[Succ];
1538 if (EdgeIndex[
I] < Weight % EdgeMultiplicity[Succ])
1540 Weights.
push_back(
static_cast<uint32_t
>(W));
1543 if (Weight > MaxWeight) {
1545 MaxDestInst = &*Succ->getFirstNonPHIOrLifetime();
1562 Opts.overwrite_existing_weights)) {
1566 return OptimizationRemark(
DEBUG_TYPE,
"PopularDest", MaxDestInst)
1567 <<
"most popular destination for conditional branches at "
1568 <<
ore::NV(
"CondBranchesLoc", BranchLoc);
1571 if (Opts.overwrite_existing_weights) {
1587bool SampleProfileLoader::emitAnnotations(
Function &
F) {
1592 if (!ProbeManager->getDesc(
F))
1593 dbgs() <<
"Probe descriptor missing for Function " <<
F.getName()
1597 if (ProbeManager->profileIsValid(
F, *Samples)) {
1598 ++NumMatchedProfile;
1600 ++NumMismatchedProfile;
1602 dbgs() <<
"Profile is invalid due to CFG mismatch for Function "
1603 <<
F.getName() <<
"\n");
1604 if (!SalvageStaleProfile)
1608 if (getFunctionLoc(
F) == 0)
1612 <<
F.getName() <<
": " << getFunctionLoc(
F) <<
"\n");
1615 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1616 if (CallsitePrioritizedInline)
1617 Changed |= inlineHotFunctionsWithPriority(
F, InlinedGUIDs);
1619 Changed |= inlineHotFunctions(
F, InlinedGUIDs);
1621 Changed |= computeAndPropagateWeights(
F, InlinedGUIDs);
1624 generateMDProfMetadata(
F);
1626 emitCoverageRemarks(
F);
1630std::unique_ptr<ProfiledCallGraph>
1631SampleProfileLoader::buildProfiledCallGraph(
Module &M) {
1632 std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1634 ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1636 ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1644 ProfiledCG->addProfiledFunction(
1651std::vector<Function *>
1652SampleProfileLoader::buildFunctionOrder(
Module &M, LazyCallGraph &CG) {
1653 std::vector<Function *> FunctionOrderList;
1654 FunctionOrderList.reserve(
M.size());
1656 if (!Opts.sample_profile_top_down_load && Opts.use_profiled_call_graph)
1657 errs() <<
"WARNING: -use-profiled-call-graph ignored, should be used "
1658 "together with -sample-profile-top-down-load.\n";
1660 if (!Opts.sample_profile_top_down_load) {
1661 if (ProfileMergeInlinee) {
1667 ProfileMergeInlinee =
false;
1672 FunctionOrderList.push_back(&
F);
1673 return FunctionOrderList;
1676 if (Opts.use_profiled_call_graph) {
1725 std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(M);
1726 scc_iterator<ProfiledCallGraph *> CGI =
scc_begin(ProfiledCG.get());
1731 scc_member_iterator<ProfiledCallGraph *>
SI(*CGI);
1734 for (
auto *Node :
Range) {
1737 FunctionOrderList.push_back(
F);
1741 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1746 dbgs() <<
"Function processing order:\n";
1747 for (
auto F : FunctionOrderList) {
1748 dbgs() <<
F->getName() <<
"\n";
1752 return FunctionOrderList;
1755bool SampleProfileLoader::doInitialization(
Module &M,
1757 auto &Ctx =
M.getContext();
1762 Filename, Ctx, *FS, FSDiscriminatorPass::Base, RemappingFilename);
1763 if (std::error_code EC = ReaderOrErr.getError()) {
1764 std::string
Msg =
"Could not open profile: " +
EC.message();
1768 Reader = std::move(ReaderOrErr.get());
1769 Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1772 Reader->setModule(&M);
1773 if (std::error_code EC = Reader->read()) {
1774 std::string
Msg =
"profile reading failed: " +
EC.message();
1779 PSL = Reader->getProfileSymbolList();
1781 DisableSampleProfileInlining =
1782 !
valueOr(Opts.sample_loader_inlining, !DisableSampleProfileInlining);
1784 if (UseFlattenedProfile)
1786 Reader->profileIsCS());
1789 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL &&
1790 !Opts.profile_sample_accurate;
1791 if (ProfAccForSymsInList)
1792 CoverageTracker.setProfAccForSymsInList(
true);
1794 if (
FAM && !Opts.sample_profile_inline_replay.
empty()) {
1796 M, *
FAM, Ctx,
nullptr,
1797 ReplayInlinerSettings{Opts.sample_profile_inline_replay,
1798 Opts.sample_profile_inline_replay_scope,
1799 Opts.sample_profile_inline_replay_fallback,
1800 {Opts.sample_profile_inline_replay_format}},
1802 InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
1806 if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
1807 Reader->profileIsProbeBased()) {
1815 ProfileSizeInline =
valueOr(Opts.sample_profile_inline_size,
true);
1816 CallsitePrioritizedInline =
1817 valueOr(Opts.sample_profile_prioritized_inline,
true);
1819 AllowRecursiveInline =
valueOr(Opts.sample_profile_recursive_inline,
true);
1821 if (Reader->profileIsPreInlined())
1822 UsePreInlinerDecision =
valueOr(Opts.sample_profile_use_preinliner,
true);
1829 if (Reader->profileIsProbeBased()) {
1830 SalvageStaleProfile =
valueOr(Opts.salvage_stale_profile,
true);
1831 SalvageUnusedProfile =
valueOr(Opts.salvage_unused_profile,
true);
1834 if (!Reader->profileIsCS()) {
1839 InlineOpts.
LimitMin = Opts.sample_profile_inline_limit_min.value_or(
1840 std::numeric_limits<unsigned>::max());
1842 std::max(Opts.sample_profile_inline_limit_max.value_or(
1843 std::numeric_limits<unsigned>::max()),
1848 if (Reader->profileIsCS()) {
1850 ContextTracker = std::make_unique<SampleContextTracker>(
1851 Reader->getProfiles(), &GUIDToFuncNameMap);
1855 if (Reader->profileIsProbeBased()) {
1856 ProbeManager = std::make_unique<PseudoProbeManager>(M);
1857 if (!ProbeManager->moduleIsProbed(M)) {
1859 "Pseudo-probe-based profile requires SampleProfileProbePass";
1860 Ctx.
diagnose(DiagnosticInfoSampleProfile(
M.getModuleIdentifier(),
Msg,
1866 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
1867 SalvageStaleProfile) {
1868 MatchingManager = std::make_unique<SampleProfileMatcher>(
1869 Opts, M, *Reader, CG, ProbeManager.get(), LTOPhase, SymbolMap, PSL,
1870 FuncNameToProfNameMap, SalvageStaleProfile, SalvageUnusedProfile);
1886bool SampleProfileLoader::rejectHighStalenessProfile(
1887 Module &M, ProfileSummaryInfo *PSI,
const SampleProfileMap &Profiles) {
1889 "Only support for probe-based profile");
1892 for (
const auto &
I : Profiles) {
1893 const auto &
FS =
I.second;
1894 const auto *FuncDesc = ProbeManager->getDesc(
FS.getGUID());
1900 FS.getTotalSamples()))
1904 if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS) &&
1905 !ProbeManager->probeFromWeakSymbol(
FS.getGUID()))
1906 NumMismatchedFunc++;
1910 if (TotalHotFunc < Opts.min_functions_for_staleness_error)
1914 if (NumMismatchedFunc * 100 >=
1915 TotalHotFunc * Opts.percent_mismatch_for_staleness_error) {
1916 auto &Ctx =
M.getContext();
1918 "The input profile significantly mismatches current source code. "
1919 "Please recollect profile to avoid performance regression.";
1920 Ctx.
diagnose(DiagnosticInfoSampleProfile(
M.getModuleIdentifier(),
Msg));
1926void SampleProfileLoader::removePseudoProbeInstsDiscriminator(
Module &M) {
1928 std::vector<Instruction *> InstsToDel;
1929 for (
auto &BB :
F) {
1930 for (
auto &
I : BB) {
1932 InstsToDel.push_back(&
I);
1934 if (
const DILocation *DIL =
I.getDebugLoc().get()) {
1938 std::optional<uint32_t> DwarfDiscriminator =
1947 for (
auto *
I : InstsToDel)
1948 I->eraseFromParent();
1953 ProfileSummaryInfo *_PSI) {
1954 GUIDToFuncNameMapper
Mapper(M, *Reader, GUIDToFuncNameMap);
1957 if (
M.getProfileSummary(
false) ==
nullptr) {
1958 M.setProfileSummary(Reader->getSummary().getMD(
M.getContext()),
1964 rejectHighStalenessProfile(M, PSI, Reader->getProfiles()))
1967 auto Remapper = Reader->getRemapper();
1969 for (
const auto &N_F :
M.getValueSymbolTable()) {
1970 StringRef OrigName = N_F.getKey();
1972 if (
F ==
nullptr || OrigName.
empty())
1974 SymbolMap[FunctionId(OrigName)] =
F;
1976 if (OrigName != NewName && !NewName.
empty()) {
1977 auto r = SymbolMap.emplace(FunctionId(NewName),
F);
1983 r.first->second =
nullptr;
1988 if (
auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
1989 if (*MapName != OrigName && !MapName->empty())
1990 SymbolMap.emplace(FunctionId(*MapName),
F);
1996 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
1997 SalvageStaleProfile) {
1998 MatchingManager->runOnModule();
1999 MatchingManager->clearMatchingData();
2001 assert(SymbolMap.count(FunctionId()) == 0 &&
2002 "No empty StringRef should be added in SymbolMap");
2003 assert((SalvageUnusedProfile || FuncNameToProfNameMap.empty()) &&
2004 "FuncNameToProfNameMap is not empty when --salvage-unused-profile is "
2007 bool retval =
false;
2008 for (
auto *
F : buildFunctionOrder(M, CG)) {
2010 clearFunctionData();
2016 for (
const auto &[Fn, Info] : notInlinedCallInfo)
2019 if (Opts.sample_profile_remove_probe &&
2021 removePseudoProbeInstsDiscriminator(M);
2023 M.eraseNamedMetadata(FuncInfo);
2029bool SampleProfileLoader::runOnFunction(
Function &
F,
2031 LLVM_DEBUG(
dbgs() <<
"\n\nProcessing Function " <<
F.getName() <<
"\n");
2032 DILocation2SampleMap.clear();
2039 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL;
2040 if (Opts.profile_sample_accurate ||
2041 F.hasFnAttribute(
"profile-sample-accurate")) {
2044 initialEntryCount = 0;
2047 ProfAccForSymsInList =
false;
2049 CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
2055 if (ProfAccForSymsInList) {
2057 if (PSL->contains(
F.getName()))
2058 initialEntryCount = 0;
2073 Function::getGUIDAssumingExternalLinkage(CanonName))
2074 : Reader->contains(CanonName))
2075 initialEntryCount = -1;
2080 if (!
F.getEntryCount())
2081 F.setEntryCount(initialEntryCount);
2087 Samples = ContextTracker->getBaseSamplesFor(
F);
2089 Samples = Reader->getSamplesFor(
F);
2094 auto It = OutlineFunctionSamples.find(FunctionId(CanonName));
2095 if (It != OutlineFunctionSamples.end()) {
2096 Samples = &It->second;
2097 }
else if (
auto Remapper = Reader->getRemapper()) {
2098 if (
auto RemppedName = Remapper->lookUpNameInProfile(CanonName)) {
2099 It = OutlineFunctionSamples.find(FunctionId(*RemppedName));
2100 if (It != OutlineFunctionSamples.end())
2101 Samples = &It->second;
2107 if (Samples && !Samples->
empty())
2108 return emitAnnotations(
F);
2118 const auto &Opts =
C.get<IPOOptions>();
2120 Opts.sample_profile_hot_inline_threshold.value_or(
2123 Opts.sample_profile_cold_inline_threshold.value_or(
2126 Opts.sample_profile_inline_growth_limit.value_or(Defaults.
GrowthLimit);
2128 Opts.sample_profile_inline_limit_min.value_or(Defaults.
LimitMin);
2130 Opts.sample_profile_inline_limit_max.value_or(Defaults.
LimitMax);
2139 bool UseFlattenedProfile)
2140 : ProfileFileName(File), ProfileRemappingFileName(RemappingFile),
2141 LTOPhase(LTOPhase), FS(
std::
move(FS)),
2142 DisableSampleProfileInlining(DisableSampleProfileInlining),
2143 UseFlattenedProfile(UseFlattenedProfile) {}
2165 SampleProfileLoader SampleLoader(
2167 ProfileFileName.empty() ? Opts.sample_profile_file
2169 ProfileRemappingFileName.
empty() ? Opts.sample_profile_remapping_file
2171 LTOPhase, FS, GetAssumptionCache, GetTTI, GetTLI, CG,
2172 DisableSampleProfileInlining, UseFlattenedProfile);
2173 if (!SampleLoader.doInitialization(M, &
FAM))
2177 if (!SampleLoader.runOnModule(M, AM, PSI))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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.
static cl::opt< unsigned > SizeLimit("eif-limit", cl::init(6), cl::Hidden, cl::desc("Size limit in Hexagon early if-conversion"))
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static LVReader * CurrentReader
Implements a lazy call graph analysis and related passes for the new pass manager.
Legalize the Machine IR a function s Machine IR
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static const Function * getCalledFunction(const Value *V)
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 ...
std::pair< BasicBlock *, BasicBlock * > Edge
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.
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)
Defines the virtual file system interface vfs::FileSystem.
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.
const Function * getParent() const
Return the enclosing method, or null if none.
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.
LLVM_ABI unsigned getLine() const
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Represents either an error or a value T.
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.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
static InlineCost getNever(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
static InlineCost getAlways(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
static InlineCost get(int Cost, int Threshold, int StaticBonus=0)
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.
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
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
A Module instance is used to store all the information related to an LLVM module.
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.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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)
PostDominatorTreePtrT PDT
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.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LLVM Value Representation.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
const ParentTy * getParent() const
Representation of the samples collected for a function.
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.
void setContextSynthetic()
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)
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.
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
SortedVectorMap< FunctionId, uint64_t, 0 > CallTargetMap
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
@ BasicBlock
Various leaf nodes.
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
NodeAddr< FuncNode * > Func
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
@ ContextDuplicatedIntoBase
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
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.
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)
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.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
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.
LLVM_ABI std::string AnnotateInlinePassName(InlineContext IC)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
LLVM_ABI cl::opt< bool > SampleProfileUseProfi
const IPOOptions & getIPOOptions(const LLVMContext &C)
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...
void sort(IteratorTy Start, IteratorTy End)
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.
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...
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
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
constexpr const char * PseudoProbeDescMetadataName
Implement std::hash so that hash_code can be used in STL containers.
A wrapper of binary function with basic blocks and jumps.
std::optional< bool > AllowRecursiveCall
Indicate whether we allow inlining for recursive call.
std::optional< bool > ComputeFullInlineCost
Compute inline cost even when the cost has exceeded the threshold.
static std::optional< uint32_t > extractDwarfBaseDiscriminator(uint32_t Value)
The thresholds of the priority-based sample profile loader inliner.
int ColdCallSiteThreshold