129#include <unordered_map>
136#define DEBUG_TYPE "pgo-instrumentation"
138STATISTIC(NumOfPGOInstrument,
"Number of edges instrumented.");
139STATISTIC(NumOfPGOSelectInsts,
"Number of select instruction instrumented.");
140STATISTIC(NumOfPGOMemIntrinsics,
"Number of mem intrinsics instrumented.");
143STATISTIC(NumOfPGOSplit,
"Number of critical edge splits.");
144STATISTIC(NumOfPGOFunc,
"Number of functions having valid profile counts.");
145STATISTIC(NumOfPGOMismatch,
"Number of functions having mismatch profile.");
146STATISTIC(NumOfPGOMissing,
"Number of functions without profile.");
147STATISTIC(NumOfPGOICall,
"Number of indirect call value instrumentations.");
148STATISTIC(NumOfCSPGOInstrument,
"Number of edges instrumented in CSPGO.");
150 "Number of select instruction instrumented in CSPGO.");
152 "Number of mem intrinsics instrumented in CSPGO.");
154STATISTIC(NumOfCSPGOBB,
"Number of basic-blocks in CSPGO.");
155STATISTIC(NumOfCSPGOSplit,
"Number of critical edge splits in CSPGO.");
157 "Number of functions having valid profile counts in CSPGO.");
159 "Number of functions having mismatch profile in CSPGO.");
160STATISTIC(NumOfCSPGOMissing,
"Number of functions without profile in CSPGO.");
161STATISTIC(NumCoveredBlocks,
"Number of basic blocks that were executed");
169 cl::desc(
"Use this option to turn off/on "
170 "warnings about profile cfg mismatch."));
180 return LibraryOptions.
get<InstrumentationOptions>()
181 .pgo_instrument_cold_function_only;
185class FunctionInstrumenter final {
186 const InstrumentationOptions &Opts;
190 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
201 bool isValueProfilingDisabled()
const {
208 return Opts.disable_vp ||
213 bool shouldInstrumentEntryBB()
const {
214 return valueOr(Opts.pgo_instrument_entry,
false) ||
215 InstrumentationType == PGOInstrumentationType::CTXPROF;
218 bool shouldInstrumentLoopEntries()
const {
219 return valueOr(Opts.pgo_instrument_loop_entries,
false);
223 FunctionInstrumenter(
225 TargetLibraryInfo &TLI,
226 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
227 BranchProbabilityInfo *BPI =
nullptr, BlockFrequencyInfo *BFI =
nullptr,
228 LoopInfo *LI =
nullptr,
230 : Opts(Opts), M(M), F(F), TLI(TLI), ComdatMembers(ComdatMembers),
231 BPI(BPI), BFI(BFI), LI(LI), InstrumentationType(InstrumentationType) {}
242 return std::string();
247 return std::string();
259 else if (CV->
isOne())
270#define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
284 if (
valueOr(Opts.pgo_instrument_entry,
false) ||
287 if (
valueOr(Opts.pgo_instrument_loop_entries,
false))
291 if (Opts.pgo_function_entry_coverage)
294 if (Opts.pgo_block_coverage)
296 if (Opts.pgo_temporal_instrumentation)
301 Triple TT(M.getTargetTriple());
302 IRLevelVersionVariable->setVisibility(TT.isGPU()
305 if (TT.supportsCOMDAT()) {
307 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
309 return IRLevelVersionVariable;
319enum VisitMode { VM_counting, VM_instrument, VM_annotate };
323struct SelectInstVisitor :
public InstVisitor<SelectInstVisitor> {
324 const InstrumentationOptions &Opts;
327 VisitMode Mode = VM_counting;
328 unsigned *CurCtrIdx =
nullptr;
329 unsigned TotalNumCtrs = 0;
330 GlobalValue *FuncNameVar =
nullptr;
332 PGOUseFunc *UseFunc =
nullptr;
333 bool HasSingleByteCoverage;
335 SelectInstVisitor(
const InstrumentationOptions &Opts,
Function &Func,
336 bool HasSingleByteCoverage)
337 : Opts(Opts), F(
Func), HasSingleByteCoverage(HasSingleByteCoverage) {}
339 void countSelects() {
349 void instrumentSelects(
unsigned *Ind,
unsigned TotalNC, GlobalValue *FNV,
351 Mode = VM_instrument;
353 TotalNumCtrs = TotalNC;
360 void annotateSelects(PGOUseFunc *UF,
unsigned *Ind) {
367 void instrumentOneSelectInst(SelectInst &SI);
368 void annotateOneSelectInst(SelectInst &SI);
371 void visitSelectInst(SelectInst &SI);
375 unsigned getNumOfSelectInsts()
const {
return NSIs; }
387 bool Removed =
false;
388 bool IsCritical =
false;
390 PGOEdge(BasicBlock *Src, BasicBlock *Dest,
uint64_t W = 1)
391 : SrcBB(Src), DestBB(Dest), Weight(
W) {}
394 std::string infoString()
const {
395 return (Twine(Removed ?
"-" :
" ") + (InMST ?
" " :
"*") +
396 (IsCritical ?
"c" :
" ") +
" W=" + Twine(Weight))
407 PGOBBInfo(
unsigned IX) : Group(this), Index(IX) {}
410 std::string infoString()
const {
411 return (Twine(
"Index=") + Twine(Index)).str();
416template <
class Edge,
class BBInfo>
class FuncPGOInstrumentation {
418 const InstrumentationOptions &Opts;
425 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
427 ValueProfileCollector VPC;
429 void computeCFGHash();
430 void renameComdatFunction();
433 std::vector<std::vector<VPCandidateInfo>> ValueSites;
434 SelectInstVisitor SIVisitor;
435 std::string FuncName;
436 std::string DeprecatedFuncName;
437 GlobalVariable *FuncNameVar;
443 CFGMST<Edge, BBInfo> MST;
445 const std::optional<BlockCoverageInference> BCI;
447 static std::optional<BlockCoverageInference>
448 constructBCI(
Function &Func,
bool HasSingleByteCoverage,
449 bool InstrumentFuncEntry) {
450 if (HasSingleByteCoverage)
451 return BlockCoverageInference(Func, InstrumentFuncEntry);
457 void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
464 BBInfo &getBBInfo(
const BasicBlock *BB)
const {
return MST.getBBInfo(BB); }
467 BBInfo *findBBInfo(
const BasicBlock *BB)
const {
return MST.findBBInfo(BB); }
470 void dumpInfo(StringRef Str =
"")
const {
471 MST.dumpEdges(
dbgs(), Twine(
"Dump Function ") + FuncName +
472 " Hash: " + Twine(FunctionHash) +
"\t" + Str);
475 FuncPGOInstrumentation(
476 const InstrumentationOptions &Opts,
Function &Func,
477 TargetLibraryInfo &
TLI,
478 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
479 bool CreateGlobalVar =
false, BranchProbabilityInfo *BPI =
nullptr,
480 BlockFrequencyInfo *BFI =
nullptr, LoopInfo *LI =
nullptr,
481 bool IsCS =
false,
bool InstrumentFuncEntry =
true,
482 bool InstrumentLoopEntries =
false,
bool HasSingleByteCoverage =
false)
483 : Opts(Opts), F(
Func), IsCS(IsCS), ComdatMembers(ComdatMembers),
484 VPC(
Func,
TLI), ValueSites(IPVK_Last + 1),
485 SIVisitor(Opts,
Func, HasSingleByteCoverage),
486 MST(F, InstrumentFuncEntry, InstrumentLoopEntries, BPI, BFI, LI),
487 BCI(constructBCI(
Func, HasSingleByteCoverage, InstrumentFuncEntry)) {
488 if (BCI && Opts.pgo_view_block_coverage_graph)
489 BCI->viewBlockCoverageGraph();
491 SIVisitor.countSelects();
492 ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize);
494 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
495 NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
496 NumOfPGOBB += MST.bbInfoSize();
497 ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget);
499 ValueSites[IPVK_VTableTarget] = VPC.get(IPVK_VTableTarget);
501 NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
502 NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
503 NumOfCSPGOBB += MST.bbInfoSize();
509 if (!ComdatMembers.empty())
510 renameComdatFunction();
513 for (
const auto &
E : MST.allEdges()) {
516 IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
518 IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
531template <
class Edge,
class BBInfo>
532void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
533 std::vector<uint8_t> Indexes;
537 auto BI = findBBInfo(Succ);
541 for (
int J = 0; J < 4; J++)
542 Indexes.push_back((
uint8_t)(Index >> (J * 8)));
549 auto updateJCH = [&JCH](
uint64_t Num) {
554 updateJCH((
uint64_t)SIVisitor.getNumOfSelectInsts());
555 updateJCH((
uint64_t)ValueSites[IPVK_IndirectCallTarget].
size());
558 updateJCH(BCI->getInstrumentedBlocksHash());
571 LLVM_DEBUG(
dbgs() <<
"Function Hash Computation for " <<
F.getName() <<
":\n"
572 <<
" CRC = " << JC.
getCRC()
573 <<
", Selects = " << SIVisitor.getNumOfSelectInsts()
574 <<
", Edges = " << MST.
numEdges() <<
", ICSites = "
575 << ValueSites[IPVK_IndirectCallTarget].size()
576 <<
", Memops = " << ValueSites[IPVK_MemOPSize].size()
577 <<
", High32 CRC = " << JCH.
getCRC()
578 <<
", Hash = " << FunctionHash <<
"\n";);
580 if (Opts.pgo_trace_func_hash !=
"-" &&
581 F.getName().contains(Opts.pgo_trace_func_hash))
582 dbgs() <<
"Funcname=" <<
F.getName() <<
", Hash=" << FunctionHash
583 <<
" in building " <<
F.getParent()->getSourceFileName() <<
"\n";
588 const InstrumentationOptions &Opts,
Function &
F,
589 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
601 for (
auto &&CM :
make_range(ComdatMembers.equal_range(
C))) {
611template <
class Edge,
class BBInfo>
612void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
615 std::string OrigName =
F.getName().str();
616 std::string NewFuncName =
618 F.setName(
Twine(NewFuncName));
620 FuncName =
Twine(FuncName +
"." +
Twine(FunctionHash)).
str();
626 if (!
F.hasComdat()) {
628 NewComdat = M->getOrInsertComdat(
StringRef(NewFuncName));
630 F.setComdat(NewComdat);
635 Comdat *OrigComdat =
F.getComdat();
636 std::string NewComdatName =
638 NewComdat = M->getOrInsertComdat(
StringRef(NewComdatName));
641 for (
auto &&CM :
make_range(ComdatMembers.equal_range(OrigComdat))) {
649template <
class Edge,
class BBInfo>
650void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
651 std::vector<BasicBlock *> &InstrumentBBs) {
654 if (BCI->shouldInstrumentBlock(BB))
655 InstrumentBBs.push_back(&BB);
660 std::vector<Edge *> EdgeList;
663 EdgeList.push_back(
E.get());
665 for (
auto &
E : EdgeList) {
668 InstrumentBBs.push_back(InstrBB);
674template <
class Edge,
class BBInfo>
675BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *
E) {
676 if (
E->InMST ||
E->Removed)
682 if (SrcBB ==
nullptr)
684 if (DestBB ==
nullptr)
699 return canInstrument(SrcBB);
701 return canInstrument(DestBB);
710 dbgs() <<
"Fail to split critical edge: not instrument this edge.\n");
715 IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
716 LLVM_DEBUG(
dbgs() <<
"Split critical edge: " << getBBInfo(SrcBB).Index
717 <<
" --> " << getBBInfo(DestBB).Index <<
"\n");
719 MST.
addEdge(SrcBB, InstrBB, 0);
721 Edge &NewEdge1 = MST.
addEdge(InstrBB, DestBB, 0);
722 NewEdge1.InMST =
true;
725 return canInstrument(InstrBB);
744 std::optional<OperandBundleUse> ParentFunclet =
752 if (!BlockColors.
empty()) {
753 const ColorVector &CV = BlockColors.
find(OrigCall->getParent())->second;
754 assert(CV.
size() == 1 &&
"non-unique color for block!");
756 if (EHPadIt->isEHPad())
764void FunctionInstrumenter::instrument() {
765 if (!Opts.pgo_block_coverage) {
771 const bool IsCtxProf = InstrumentationType == PGOInstrumentationType::CTXPROF;
772 FuncPGOInstrumentation<PGOEdge, PGOBBInfo> FuncInfo(
773 Opts,
F,
TLI, ComdatMembers, !IsCtxProf, BPI, BFI, LI,
774 InstrumentationType == PGOInstrumentationType::CSFDO,
775 shouldInstrumentEntryBB(), shouldInstrumentLoopEntries(),
776 Opts.pgo_block_coverage);
779 auto *
const CFGHash =
780 ConstantInt::get(Type::getInt64Ty(
M.getContext()), FuncInfo.FunctionHash);
784 Name, PointerType::get(
M.getContext(), 0));
785 if (Opts.pgo_function_entry_coverage) {
786 auto &EntryBB =
F.getEntryBlock();
787 IRBuilder<> Builder(EntryBB.getFirstNonPHIOrAlloca());
790 Builder.CreateIntrinsic(
791 Intrinsic::instrprof_cover,
792 {NormalizedNamePtr, CFGHash, Builder.getInt32(1), Builder.getInt32(0)});
796 std::vector<BasicBlock *> InstrumentBBs;
797 FuncInfo.getInstrumentBBs(InstrumentBBs);
798 unsigned NumCounters =
799 InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
803 Opts.ctx_prof_skip_callsite_instr);
815 auto Visit = [&](llvm::function_ref<void(CallBase * CB)> Visitor) {
817 for (
auto &Instr : BB)
821 if (CS->getCalledFunction() &&
822 SkipCSInstr.contains(CS->getCalledFunction()->getName()))
828 uint32_t TotalNumCallsites = 0;
829 Visit([&TotalNumCallsites](
auto *) { ++TotalNumCallsites; });
833 Visit([&](
auto *CB) {
835 Builder.CreateCall(CSIntrinsic,
836 {
Name, CFGHash, Builder.getInt32(TotalNumCallsites),
838 CB->getCalledOperand()});
843 if (Opts.pgo_temporal_instrumentation) {
844 NumCounters += Opts.pgo_block_coverage ? 8 : 1;
845 auto &EntryBB =
F.getEntryBlock();
846 IRBuilder<> Builder(EntryBB.getFirstNonPHIOrAlloca());
849 Builder.CreateIntrinsic(Intrinsic::instrprof_timestamp,
850 {NormalizedNamePtr, CFGHash,
851 Builder.getInt32(NumCounters),
852 Builder.getInt32(
I)});
853 I += Opts.pgo_block_coverage ? 8 : 1;
856 for (
auto *InstrBB : InstrumentBBs) {
858 assert(Builder.GetInsertPoint() != InstrBB->
end() &&
859 "Cannot get the Instrumentation point");
862 Builder.CreateIntrinsic(
863 Opts.pgo_block_coverage ? Intrinsic::instrprof_cover
864 : Intrinsic::instrprof_increment,
865 {NormalizedNamePtr, CFGHash, Builder.getInt32(NumCounters),
866 Builder.getInt32(I++)});
870 FuncInfo.SIVisitor.instrumentSelects(&
I, NumCounters, Name,
871 FuncInfo.FunctionHash);
874 if (isValueProfilingDisabled())
877 NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size();
883 DenseMap<BasicBlock *, ColorVector> BlockColors;
884 if (
F.hasPersonalityFn() &&
889 for (uint32_t Kind = IPVK_First;
Kind <= IPVK_Last; ++
Kind) {
890 unsigned SiteIndex = 0;
891 if (Kind == IPVK_MemOPSize && !Opts.pgo_instr_memop)
896 <<
" site: CallSite Index = " << SiteIndex <<
"\n");
899 assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() &&
900 "Cannot get the Instrumentation point");
902 Value *ToProfile =
nullptr;
903 if (Cand.V->getType()->isIntegerTy())
904 ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty());
905 else if (Cand.V->getType()->isPointerTy())
906 ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty());
907 assert(ToProfile &&
"value profiling Value is of unexpected type");
910 Name, PointerType::get(
M.getContext(), 0));
916 Intrinsic::instrprof_value_profile),
917 {NormalizedNamePtr, Builder.getInt64(FuncInfo.FunctionHash),
918 ToProfile, Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)},
927struct PGOUseEdge :
public PGOEdge {
928 using PGOEdge::PGOEdge;
930 std::optional<uint64_t>
Count;
936 std::string infoString()
const {
938 return PGOEdge::infoString();
939 return (Twine(PGOEdge::infoString()) +
" Count=" + Twine(*
Count)).str();
946struct PGOUseBBInfo :
public PGOBBInfo {
947 std::optional<uint64_t>
Count;
948 int32_t UnknownCountInEdge = 0;
949 int32_t UnknownCountOutEdge = 0;
951 DirectEdges OutEdges;
953 PGOUseBBInfo(
unsigned IX) : PGOBBInfo(IX) {}
959 std::string infoString()
const {
961 return PGOBBInfo::infoString();
962 return (Twine(PGOBBInfo::infoString()) +
" Count=" + Twine(*
Count)).str();
966 void addOutEdge(PGOUseEdge *
E) {
967 OutEdges.push_back(
E);
968 UnknownCountOutEdge++;
972 void addInEdge(PGOUseEdge *
E) {
973 InEdges.push_back(
E);
974 UnknownCountInEdge++;
983 for (
const auto &
E : Edges) {
996 PGOUseFunc(
const InstrumentationOptions &Opts,
Function &Func,
Module *Modu,
997 TargetLibraryInfo &
TLI,
998 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
999 BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin,
1000 LoopInfo *LI, ProfileSummaryInfo *PSI,
bool IsCS,
1001 bool InstrumentFuncEntry,
bool InstrumentLoopEntries,
1002 bool HasSingleByteCoverage)
1003 : Opts(Opts),
F(
Func),
M(Modu), BFI(BFIin), PSI(PSI),
1004 FuncInfo(Opts,
Func,
TLI, ComdatMembers,
false, BPI, BFIin, LI, IsCS,
1005 InstrumentFuncEntry, InstrumentLoopEntries,
1006 HasSingleByteCoverage),
1007 FreqAttr(FFA_Normal), IsCS(IsCS), VPC(
Func,
TLI) {}
1009 void handleInstrProfError(
Error Err,
uint64_t MismatchedFuncSum);
1014 bool getRecord(IndexedInstrProfReader *PGOReader);
1017 bool readCounters(
bool &AllZeros,
1021 void populateCounters();
1024 void populateCoverage();
1030 void annotateValueSites();
1033 void annotateValueSites(uint32_t Kind);
1036 void annotateIrrLoopHeaderWeights();
1039 void setBlockUniformityAttribute();
1042 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
1045 FuncFreqAttr getFuncFreqAttr()
const {
return FreqAttr; }
1051 NamedInstrProfRecord &getProfileRecord() {
return ProfileRecord; }
1054 PGOUseBBInfo &getBBInfo(
const BasicBlock *BB)
const {
1055 return FuncInfo.getBBInfo(BB);
1059 PGOUseBBInfo *findBBInfo(
const BasicBlock *BB)
const {
1060 return FuncInfo.findBBInfo(BB);
1065 void dumpInfo(StringRef Str =
"")
const { FuncInfo.dumpInfo(Str); }
1067 uint64_t getProgramMaxCount()
const {
return ProgramMaxCount; }
1070 const InstrumentationOptions &Opts;
1073 BlockFrequencyInfo *BFI;
1074 ProfileSummaryInfo *PSI;
1077 FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> FuncInfo;
1084 uint32_t CountPosition = 0;
1087 uint32_t ProfileCountSize = 0;
1090 NamedInstrProfRecord ProfileRecord;
1093 FuncFreqAttr FreqAttr;
1098 ValueProfileCollector VPC;
1101 bool setInstrumentedCounts(
const std::vector<uint64_t> &CountFromProfile);
1114 FreqAttr = FFA_Cold;
1122 const FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> &FuncInfo) {
1126 for (
const auto &
E : FuncInfo.MST.allEdges()) {
1131 PGOUseBBInfo &SrcInfo = FuncInfo.getBBInfo(SrcBB);
1132 PGOUseBBInfo &DestInfo = FuncInfo.getBBInfo(DestBB);
1133 SrcInfo.addOutEdge(
E.get());
1134 DestInfo.addInEdge(
E.get());
1140bool PGOUseFunc::setInstrumentedCounts(
1141 const std::vector<uint64_t> &CountFromProfile) {
1143 std::vector<BasicBlock *> InstrumentBBs;
1144 FuncInfo.getInstrumentBBs(InstrumentBBs);
1148 unsigned NumInstrumentedBBs = InstrumentBBs.size();
1149 unsigned NumSelects = FuncInfo.SIVisitor.getNumOfSelectInsts();
1150 unsigned NumCounters = NumInstrumentedBBs + NumSelects;
1153 if (NumCounters != CountFromProfile.size()) {
1155 dbgs() <<
"PGO COUNTER MISMATCH for function " <<
F.getName() <<
":\n";
1156 dbgs() <<
" Expected counters: " << NumCounters <<
"\n";
1157 dbgs() <<
" - From instrumented edges: " << NumInstrumentedBBs <<
"\n";
1158 for (
size_t i = 0; i < InstrumentBBs.size(); ++i) {
1159 dbgs() <<
" " << i <<
": ";
1160 InstrumentBBs[i]->printAsOperand(
dbgs(),
false);
1163 dbgs() <<
" - From select instructions: " << NumSelects <<
"\n";
1164 dbgs() <<
" Actual counters from profile: " << CountFromProfile.size()
1169 auto *FuncEntry = &*
F.begin();
1173 for (BasicBlock *InstrBB : InstrumentBBs) {
1174 uint64_t CountValue = CountFromProfile[
I++];
1175 PGOUseBBInfo &
Info = getBBInfo(InstrBB);
1179 if (InstrBB == FuncEntry && CountValue == 0)
1181 Info.setBBInfoCount(CountValue);
1183 ProfileCountSize = CountFromProfile.size();
1187 auto setEdgeCount = [
this](PGOUseEdge *
E,
uint64_t Value) ->
void {
1189 this->getBBInfo(
E->SrcBB).UnknownCountOutEdge--;
1190 this->getBBInfo(
E->DestBB).UnknownCountInEdge--;
1196 for (
const auto &
E : FuncInfo.MST.allEdges()) {
1197 if (
E->Removed ||
E->InMST)
1200 PGOUseBBInfo &SrcInfo = getBBInfo(SrcBB);
1204 if (SrcInfo.Count && SrcInfo.OutEdges.size() == 1)
1205 setEdgeCount(
E.get(), *SrcInfo.Count);
1208 PGOUseBBInfo &DestInfo = getBBInfo(DestBB);
1211 if (DestInfo.Count && DestInfo.InEdges.size() == 1)
1212 setEdgeCount(
E.get(), *DestInfo.Count);
1218 setEdgeCount(
E.get(), 0);
1225void PGOUseFunc::setEdgeCount(DirectEdges &Edges,
uint64_t Value) {
1226 for (
auto &
E : Edges) {
1231 getBBInfo(
E->SrcBB).UnknownCountOutEdge--;
1232 getBBInfo(
E->DestBB).UnknownCountInEdge--;
1240 const char MetadataName[] =
"instr_prof_hash_mismatch";
1243 auto *Existing =
F.getMetadata(LLVMContext::MD_annotation);
1246 for (
const auto &
N : Tuple->operands()) {
1247 if (
N.equalsStr(MetadataName))
1256 F.setMetadata(LLVMContext::MD_annotation, MD);
1259void PGOUseFunc::handleInstrProfError(
Error Err,
uint64_t MismatchedFuncSum) {
1261 auto &Ctx =
M->getContext();
1262 auto Err = IPE.
get();
1263 bool SkipWarning =
false;
1265 << FuncInfo.FuncName <<
": ");
1266 if (Err == instrprof_error::unknown_function) {
1267 IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
1268 SkipWarning = !Opts.pgo_warn_missing_function;
1270 }
else if (Err == instrprof_error::hash_mismatch ||
1271 Err == instrprof_error::malformed) {
1272 IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
1275 (Opts.no_pgo_warn_mismatch_comdat_weak &&
1278 LLVM_DEBUG(
dbgs() <<
"hash mismatch (hash= " << FuncInfo.FunctionHash
1279 <<
" skip=" << SkipWarning <<
")");
1289 IPE.
message() + std::string(
" ") +
F.getName().str() +
1290 std::string(
" Hash = ") + std::to_string(FuncInfo.FunctionHash) +
1291 std::string(
" up to ") + std::to_string(MismatchedFuncSum) +
1292 std::string(
" count discarded");
1299bool PGOUseFunc::getRecord(IndexedInstrProfReader *PGOReader) {
1302 FuncInfo.FuncName, FuncInfo.FunctionHash, FuncInfo.DeprecatedFuncName,
1303 &MismatchedFuncSum);
1305 handleInstrProfError(std::move(
E), MismatchedFuncSum);
1308 ProfileRecord = std::move(
Result.get());
1316bool PGOUseFunc::readCounters(
bool &AllZeros,
1318 auto &Ctx =
M->getContext();
1323 std::vector<uint64_t> &CountFromProfile = ProfileRecord.
Counts;
1325 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1329 for (
unsigned I = 0, S = CountFromProfile.size();
I < S;
I++) {
1331 ValueSum += CountFromProfile[
I];
1333 AllZeros = (ValueSum == 0);
1337 getBBInfo(
nullptr).UnknownCountOutEdge = 2;
1338 getBBInfo(
nullptr).UnknownCountInEdge = 2;
1340 if (!setInstrumentedCounts(CountFromProfile)) {
1342 dbgs() <<
"Inconsistent number of counts, skipping this function");
1343 Ctx.diagnose(DiagnosticInfoPGOProfile(
1344 M->getName().data(),
1345 Twine(
"Inconsistent number of counts in ") +
F.getName().str() +
1346 Twine(
": the profile may be stale or there is a function name "
1354void PGOUseFunc::populateCoverage() {
1355 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1357 ArrayRef<uint64_t> CountsFromProfile = ProfileRecord.
Counts;
1358 DenseMap<const BasicBlock *, bool>
Coverage;
1361 if (FuncInfo.BCI->shouldInstrumentBlock(BB))
1366 DenseMap<const BasicBlock *, DenseSet<const BasicBlock *>>
1367 InverseDependencies;
1368 for (
auto &BB :
F) {
1369 for (
auto *Dep : FuncInfo.BCI->getDependencies(BB)) {
1371 InverseDependencies[Dep].
insert(&BB);
1376 std::stack<const BasicBlock *> CoveredBlocksToProcess;
1377 for (
auto &[BB, IsCovered] : Coverage)
1379 CoveredBlocksToProcess.push(BB);
1381 while (!CoveredBlocksToProcess.empty()) {
1382 auto *CoveredBlock = CoveredBlocksToProcess.top();
1383 assert(Coverage[CoveredBlock]);
1384 CoveredBlocksToProcess.pop();
1385 for (
auto *BB : InverseDependencies[CoveredBlock]) {
1391 CoveredBlocksToProcess.push(BB);
1396 MDBuilder MDB(
F.getContext());
1399 F.setEntryCount(Coverage[&
F.getEntryBlock()] ? 10000 : 0);
1400 for (
auto &BB :
F) {
1407 SmallVector<uint32_t, 4> Weights;
1409 Weights.
push_back((Coverage[Succ] || !Coverage[&BB]) ? 1 : 0);
1410 if (Weights.
size() >= 2)
1415 unsigned NumCorruptCoverage = 0;
1418 BranchProbabilityInfo BPI(
F, CI);
1419 BlockFrequencyInfo BFI(
F, BPI, CI);
1420 auto IsBlockDead = [&](
const BasicBlock &BB) -> std::optional<bool> {
1425 LLVM_DEBUG(
dbgs() <<
"Block Coverage: (Instrumented=*, Covered=X)\n");
1426 for (
auto &BB :
F) {
1427 LLVM_DEBUG(
dbgs() << (FuncInfo.BCI->shouldInstrumentBlock(BB) ?
"* " :
" ")
1428 << (Coverage[&BB] ?
"X " :
" ") <<
" " << BB.getName()
1435 if (Cov == IsBlockDead(BB).value_or(
false)) {
1437 dbgs() <<
"Found inconsistent block covearge for " << BB.getName()
1438 <<
": BCI=" << (Cov ?
"Covered" :
"Dead") <<
" BFI="
1439 << (IsBlockDead(BB).value() ?
"Dead" :
"Covered") <<
"\n");
1440 ++NumCorruptCoverage;
1445 if (Opts.pgo_verify_bfi && NumCorruptCoverage) {
1446 auto &Ctx =
M->getContext();
1447 Ctx.diagnose(DiagnosticInfoPGOProfile(
1448 M->getName().data(),
1449 Twine(
"Found inconsistent block coverage for function ") +
F.getName() +
1450 " in " + Twine(NumCorruptCoverage) +
" blocks.",
1453 if (Opts.pgo_view_block_coverage_graph)
1454 FuncInfo.BCI->viewBlockCoverageGraph(&Coverage);
1459void PGOUseFunc::populateCounters() {
1460 bool Changes =
true;
1461 unsigned NumPasses = 0;
1469 PGOUseBBInfo *UseBBInfo = findBBInfo(&BB);
1470 if (UseBBInfo ==
nullptr)
1472 if (!UseBBInfo->Count) {
1473 if (UseBBInfo->UnknownCountOutEdge == 0) {
1476 }
else if (UseBBInfo->UnknownCountInEdge == 0) {
1481 if (UseBBInfo->Count) {
1482 if (UseBBInfo->UnknownCountOutEdge == 1) {
1488 if (*UseBBInfo->Count > OutSum)
1489 Total = *UseBBInfo->Count - OutSum;
1490 setEdgeCount(UseBBInfo->OutEdges,
Total);
1493 if (UseBBInfo->UnknownCountInEdge == 1) {
1496 if (*UseBBInfo->Count > InSum)
1497 Total = *UseBBInfo->Count - InSum;
1498 setEdgeCount(UseBBInfo->InEdges,
Total);
1505 LLVM_DEBUG(
dbgs() <<
"Populate counts in " << NumPasses <<
" passes.\n");
1509 for (
auto &BB :
F) {
1510 auto BI = findBBInfo(&BB);
1513 assert(BI->Count &&
"BB count is not valid");
1517 FuncInfo.SIVisitor.annotateSelects(
this, &CountPosition);
1518 assert(CountPosition == ProfileCountSize);
1522 for (
auto &BB :
F) {
1523 auto BI = findBBInfo(&BB);
1526 FuncMaxCount = std::max(FuncMaxCount, *BI->Count);
1535 LLVM_DEBUG(FuncInfo.dumpInfo(
"after reading profile."));
1539void PGOUseFunc::setBranchWeights() {
1541 LLVM_DEBUG(
dbgs() <<
"\nSetting branch weights for func " <<
F.getName()
1542 <<
" IsCS=" << IsCS <<
"\n");
1543 for (
auto &BB :
F) {
1552 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1553 if (!*BBCountInfo.Count)
1560 unsigned OutEdgesCount = BBCountInfo.OutEdges.size();
1561 unsigned SuccessorCount = BB.getTerminator()->getNumSuccessors();
1562 assert(OutEdgesCount <= SuccessorCount);
1566 for (
unsigned It = 0; It < OutEdgesCount; It++) {
1567 const PGOUseEdge *
E = BBCountInfo.OutEdges[It];
1570 if (DestBB ==
nullptr)
1574 if (EdgeCount > MaxCount)
1575 MaxCount = EdgeCount;
1576 EdgeCounts[SuccNum] = EdgeCount;
1585 auto &Ctx =
M->getContext();
1586 Ctx.diagnose(DiagnosticInfoPGOProfile(
1587 M->getName().data(),
1588 Twine(
"Profile in ") +
F.getName().str() +
1589 Twine(
" partially ignored") +
1590 Twine(
", possibly due to the lack of a return path."),
1604void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1605 LLVM_DEBUG(
dbgs() <<
"\nAnnotating irreducible loop header weights.\n");
1607 for (
auto &BB :
F) {
1613 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1619void PGOUseFunc::setBlockUniformityAttribute() {
1630 std::vector<BasicBlock *> InstrumentBBs;
1631 FuncInfo.getInstrumentBBs(InstrumentBBs);
1633 LLVMContext &Ctx =
F.getContext();
1634 Type *Int1Ty = Type::getInt1Ty(Ctx);
1636 for (
size_t I = 0,
E = InstrumentBBs.size();
I <
E; ++
I) {
1648 dbgs() <<
"PGO: Set block uniformity profile for " <<
F.getName() <<
": ";
1649 for (
size_t I = 0,
E = InstrumentBBs.size();
I <
E; ++
I)
1655void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1658 Type *Int64Ty = Builder.getInt64Ty();
1664 auto *Step = Builder.CreateZExt(
Cond, Int64Ty);
1665 auto *NormalizedFuncNameVarPtr =
1667 FuncNameVar, PointerType::get(
M->getContext(), 0));
1668 Builder.CreateIntrinsic(Intrinsic::instrprof_increment_step,
1669 {NormalizedFuncNameVarPtr, Builder.getInt64(
FuncHash),
1670 Builder.getInt32(TotalNumCtrs),
1671 Builder.getInt32(*CurCtrIdx), Step});
1675void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1676 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1677 assert(*CurCtrIdx < CountFromProfile.size() &&
1678 "Out of bound access of counters");
1680 SCounts[0] = CountFromProfile[*CurCtrIdx];
1683 auto BI = UseFunc->findBBInfo(
SI.getParent());
1684 if (BI !=
nullptr) {
1685 TotalCount = *BI->Count;
1688 if (TotalCount < SCounts[0])
1689 BI->Count = SCounts[0];
1692 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1693 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1698void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1699 if (!Opts.pgo_instr_select || Opts.pgo_function_entry_coverage ||
1700 HasSingleByteCoverage)
1703 if (
SI.getCondition()->getType()->isVectorTy())
1711 instrumentOneSelectInst(SI);
1714 annotateOneSelectInst(SI);
1724 if (ValueProfKind == IPVK_MemOPSize)
1725 return Opts.memop_max_annotations;
1726 if (ValueProfKind == llvm::IPVK_VTableTarget)
1728 return Opts.icp_max_annotations;
1732void PGOUseFunc::annotateValueSites() {
1733 if (Opts.disable_vp)
1736 for (uint32_t Kind = IPVK_First;
Kind <= IPVK_Last; ++
Kind)
1737 annotateValueSites(Kind);
1741void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1742 assert(Kind <= IPVK_Last);
1743 unsigned ValueSiteIndex = 0;
1757 NumValueSites != FuncInfo.ValueSites[IPVK_VTableTarget].size() &&
1759 FuncInfo.ValueSites[IPVK_VTableTarget] = VPC.
get(IPVK_VTableTarget);
1760 auto &ValueSites = FuncInfo.ValueSites[
Kind];
1762 auto &Ctx =
M->getContext();
1763 Ctx.
diagnose(DiagnosticInfoPGOProfile(
1764 M->getName().data(),
1765 Twine(
"Inconsistent number of value sites for ") +
1768 Twine(
"\", possibly due to the use of a stale profile."),
1774 LLVM_DEBUG(
dbgs() <<
"Read one value site profile (kind = " << Kind
1775 <<
"): Index = " << ValueSiteIndex <<
" out of "
1778 *M, *
I.AnnotatedInst, ProfileRecord,
1789 const InstrumentationOptions &Opts,
Module &M,
1790 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1791 if (!Opts.do_comdat_renaming)
1795 ComdatMembers.insert(std::make_pair(
C, &
F));
1797 if (
Comdat *
C = GV.getComdat())
1798 ComdatMembers.insert(std::make_pair(
C, &GV));
1800 if (
Comdat *
C = GA.getComdat())
1801 ComdatMembers.insert(std::make_pair(
C, &GA));
1806 if (
F.isDeclaration())
1811 unsigned NumCriticalEdges = 0;
1812 for (
auto &BB :
F) {
1819 if (NumCriticalEdges > Opts.pgo_critical_edge_threshold) {
1821 <<
", NumCriticalEdges=" << NumCriticalEdges
1822 <<
" exceed the threshold. Skip PGO.\n");
1832 if (
F.hasFnAttribute(llvm::Attribute::Naked))
1834 if (
F.hasFnAttribute(llvm::Attribute::NoProfile))
1836 if (
F.hasFnAttribute(llvm::Attribute::SkipProfile))
1838 if (
F.getInstructionCount() < Opts.pgo_function_size_threshold)
1840 if (Opts.pgo_instrument_cold_function_only) {
1841 if (
auto EntryCount =
F.getEntryCount())
1842 return *EntryCount > Opts.pgo_cold_instrument_entry_threshold;
1843 return !Opts.pgo_treat_unknown_as_cold;
1849 const InstrumentationOptions &Opts,
Module &M,
1860 Triple TT(M.getTargetTriple());
1865 Twine(
"VTable value profiling is presently not "
1866 "supported for non-ELF object formats"),
1868 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1878 FunctionInstrumenter FI(Opts, M,
F,
TLI, ComdatMembers, BPI, BFI, LI,
1879 InstrumentationType);
1893 if (ProfileSampling)
1919 LookupLI, InstrumentationType))
1932 auto BFIEntryCount =
F.getEntryCount();
1933 assert(BFIEntryCount && (*BFIEntryCount > 0) &&
"Invalid BFI Entrycount");
1937 for (
auto &BBI :
F) {
1940 if (!Func.findBBInfo(&BBI))
1943 CountValue = *Func.getBBInfo(&BBI).Count;
1944 BFICountValue = *BFICount;
1948 if (SumCount.isZero())
1952 "Incorrect sum of BFI counts");
1955 double Scale = (SumCount / SumBFICount).convertToDouble();
1956 if (Scale < 1.001 && Scale > 0.999)
1961 if (NewEntryCount == 0)
1964 F.setEntryCount(NewEntryCount);
1967 << NewEntryCount <<
"\n");
1980 bool HotBBOnly = Opts.pgo_verify_hot_bfi;
1984 unsigned BBNum = 0, BBMisMatchNum = 0, NonZeroBBNum = 0;
1985 for (
auto &BBI :
F) {
1986 PGOUseBBInfo *BBInfo = Func.findBBInfo(&BBI);
1990 uint64_t CountValue = BBInfo->Count.value_or(CountValue);
1998 BFICountValue = *BFICount;
2001 bool rawIsHot = CountValue >= HotCountThreshold;
2002 bool BFIIsHot = BFICountValue >= HotCountThreshold;
2004 bool ShowCount =
false;
2005 if (rawIsHot && !BFIIsHot) {
2006 Msg =
"raw-Hot to BFI-nonHot";
2008 }
else if (rawIsCold && BFIIsHot) {
2009 Msg =
"raw-Cold to BFI-Hot";
2015 if ((CountValue < Opts.pgo_verify_bfi_cutoff) &&
2016 (BFICountValue < Opts.pgo_verify_bfi_cutoff))
2018 uint64_t Diff = (BFICountValue >= CountValue)
2019 ? BFICountValue - CountValue
2020 : CountValue - BFICountValue;
2021 if (Diff <= CountValue / 100 * Opts.pgo_verify_bfi_ratio)
2028 F.getSubprogram(), &BBI);
2030 <<
" Count=" <<
ore::NV(
"Count", CountValue)
2031 <<
" BFI_Count=" <<
ore::NV(
"Count", BFICountValue);
2040 F.getSubprogram(), &
F.getEntryBlock())
2041 <<
"In Func " <<
ore::NV(
"Function",
F.getName())
2042 <<
": Num_of_BB=" <<
ore::NV(
"Count", BBNum)
2043 <<
", Num_of_non_zerovalue_BB=" <<
ore::NV(
"Count", NonZeroBBNum)
2044 <<
", Num_of_mis_matching_BB=" <<
ore::NV(
"Count", BBMisMatchNum);
2049 const InstrumentationOptions &Opts,
Module &M,
StringRef ProfileFileName,
2057 auto &Ctx = M.getContext();
2060 ProfileRemappingFileName);
2061 if (
Error E = ReaderOrErr.takeError()) {
2069 std::unique_ptr<IndexedInstrProfReader> PGOReader =
2070 std::move(ReaderOrErr.get());
2076 if (!PGOReader->hasCSIRLevelProfile() && IsCS)
2080 if (!PGOReader->isIRLevelProfile()) {
2082 ProfileFileName.
data(),
"Not an IR level instrumentation profile"));
2085 if (PGOReader->functionEntryOnly()) {
2087 ProfileFileName.
data(),
2088 "Function entry profiles are not yet supported for optimization"));
2095 M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
2100 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
2102 std::vector<Function *> HotFunctions;
2103 std::vector<Function *> ColdFunctions;
2107 bool InstrumentFuncEntry =
2108 valueOr(Opts.pgo_instrument_entry, PGOReader->instrEntryBBEnabled());
2109 bool InstrumentLoopEntries =
valueOr(Opts.pgo_instrument_loop_entries,
2110 PGOReader->instrLoopEntriesEnabled());
2112 bool HasSingleByteCoverage = PGOReader->hasSingleByteCoverage();
2120 if (!HasSingleByteCoverage) {
2126 PGOUseFunc Func(Opts,
F, &M,
TLI, ComdatMembers, BPI, BFI, LI, PSI, IsCS,
2127 InstrumentFuncEntry, InstrumentLoopEntries,
2128 HasSingleByteCoverage);
2129 if (!Func.getRecord(PGOReader.get()))
2131 if (HasSingleByteCoverage) {
2132 Func.populateCoverage();
2140 bool AllZeros =
false;
2141 if (!Func.readCounters(AllZeros, PseudoKind))
2145 if (Func.getProgramMaxCount() != 0)
2146 ColdFunctions.push_back(&
F);
2151 if (
F.hasFnAttribute(Attribute::Cold))
2152 F.removeFnAttr(Attribute::Cold);
2155 F.addFnAttr(Attribute::Hot);
2158 Func.populateCounters();
2159 Func.setBranchWeights();
2160 Func.annotateValueSites();
2161 Func.annotateIrrLoopHeaderWeights();
2162 Func.setBlockUniformityAttribute();
2163 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
2164 if (FreqAttr == PGOUseFunc::FFA_Cold)
2165 ColdFunctions.push_back(&
F);
2166 else if (FreqAttr == PGOUseFunc::FFA_Hot)
2167 HotFunctions.push_back(&
F);
2171 (ViewFuncName.
empty() ||
F.getName() == ViewFuncName)) {
2174 std::unique_ptr<BranchProbabilityInfo> NewBPI =
2175 std::make_unique<BranchProbabilityInfo>(
F, CI);
2176 std::unique_ptr<BlockFrequencyInfo> NewBFI =
2177 std::make_unique<BlockFrequencyInfo>(
F, *NewBPI, CI);
2181 dbgs() <<
"pgo-view-counts: " << Func.getFunc().getName() <<
"\n";
2182 NewBFI->print(
dbgs());
2186 (ViewFuncName.
empty() ||
F.getName() == ViewFuncName)) {
2188 if (ViewFuncName.
empty())
2191 ViewGraph(&Func,
Twine(
"PGORawCounts_") + Func.getFunc().getName());
2193 dbgs() <<
"pgo-view-raw-counts: " << Func.getFunc().getName() <<
"\n";
2198 if (Opts.pgo_verify_bfi || Opts.pgo_verify_hot_bfi ||
2199 Opts.pgo_fix_entry_count) {
2205 if (Opts.pgo_fix_entry_count)
2210 if (Opts.pgo_verify_hot_bfi) {
2223 for (
auto &
F : HotFunctions) {
2224 F->addFnAttr(Attribute::InlineHint);
2225 LLVM_DEBUG(
dbgs() <<
"Set inline attribute to function: " <<
F->getName()
2228 for (
auto &
F : ColdFunctions) {
2231 if (
F->hasFnAttribute(Attribute::Hot)) {
2232 auto &Ctx = M.getContext();
2233 std::string
Msg = std::string(
"Function ") +
F->getName().str() +
2234 std::string(
" is annotated as a hot function but"
2235 " the profile is cold");
2240 F->addFnAttr(Attribute::Cold);
2241 LLVM_DEBUG(
dbgs() <<
"Set cold attribute to function: " <<
F->getName()
2248 std::string
Filename, std::string RemappingFilename,
bool IsCS,
2251 ProfileRemappingFileName(
std::
move(RemappingFilename)), IsCS(IsCS),
2276 StringRef ProfileFile = ProfileFileName;
2277 if (!Opts.pgo_test_profile_file.empty())
2278 ProfileFile = Opts.pgo_test_profile_file;
2279 StringRef RemappingFile = ProfileRemappingFileName;
2280 if (!Opts.pgo_test_profile_remapping_file.empty())
2281 RemappingFile = Opts.pgo_test_profile_remapping_file;
2283 LookupBPI, LookupBFI, LookupLI, PSI, IsCS))
2290 if (!
Node->getName().empty())
2291 return Node->getName().str();
2293 std::string SimpleNodeName;
2296 return SimpleNodeName;
2300 uint64_t MaxCount) {
2303 LLVM_DEBUG(
dbgs() <<
"Weight is: ";
for (
const auto &W : Weights) {
2311 const InstrumentationOptions &Opts =
2313 if (Opts.pgo_emit_branch_prob) {
2315 if (BrCondStr.empty())
2319 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
2320 [](uint64_t w1, uint64_t w2) { return w1 + w2; });
2321 uint64_t TotalCount =
2322 std::accumulate(EdgeCounts.
begin(), EdgeCounts.
end(), (uint64_t)0,
2323 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
2327 std::string BranchProbStr;
2330 OS <<
" (total count : " << TotalCount <<
")";
2335 << BrCondStr <<
" is true with probability : " << BranchProbStr;
2354 return &
G->getFunc().front();
2377 return std::string(
G->getFunc().getName());
2385 PGOUseBBInfo *BI =
Graph->findBBInfo(
Node);
2387 if (BI && BI->Count)
2388 OS << *BI->Count <<
"\\l";
2392 const InstrumentationOptions &Opts =
2394 if (!Opts.pgo_instr_select)
2401 OS <<
"SELECT : { T = ";
2405 OS <<
"Unknown, F = Unknown }\\l";
2407 OS << TC <<
", F = " << FC <<
" }\\l";
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
Function Alias Analysis false
This file contains the simple types necessary to represent the attributes associated with functions a...
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
This file finds the minimum set of blocks on a CFG that must be instrumented to infer execution cover...
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 contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
post inline ee instrument
static BasicBlock * getInstrBB(CFGMST< Edge, BBInfo > &MST, Edge &E, const DenseSet< const BasicBlock * > &ExecBlocks)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define INSTR_PROF_QUOTE(x)
#define VARIANT_MASK_CSIR_PROF
#define VARIANT_MASK_DBG_CORRELATE
#define INSTR_PROF_RAW_VERSION
#define INSTR_PROF_RAW_VERSION_VAR
#define VARIANT_MASK_TEMPORAL_PROF
#define VARIANT_MASK_IR_PROF
#define VARIANT_MASK_BYTE_COVERAGE
#define VARIANT_MASK_INSTR_ENTRY
#define VARIANT_MASK_FUNCTION_ENTRY_ONLY
#define VARIANT_MASK_INSTR_LOOP_ENTRIES
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
Machine Check Debug Module
static constexpr StringLiteral Filename
static void annotateFunctionWithHashMismatch(Function &F, LLVMContext &ctx)
static bool instrumentAllFunctions(const InstrumentationOptions &Opts, Module &M, function_ref< TargetLibraryInfo &(Function &)> LookupTLI, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, function_ref< LoopInfo *(Function &)> LookupLI, PGOInstrumentationType InstrumentationType)
static bool skipPGOGen(const InstrumentationOptions &Opts, const Function &F)
static void fixFuncEntryCount(PGOUseFunc &Func, CycleInfo &CI, BranchProbabilityInfo &NBPI)
static void populateEHOperandBundle(VPCandidateInfo &Cand, DenseMap< BasicBlock *, ColorVector > &BlockColors, SmallVectorImpl< OperandBundleDef > &OpBundles)
static void collectComdatMembers(const InstrumentationOptions &Opts, Module &M, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
static void setupBBInfoEdges(const FuncPGOInstrumentation< PGOUseEdge, PGOUseBBInfo > &FuncInfo)
Set up InEdges/OutEdges for all BBs in the MST.
ValueProfileCollector::CandidateInfo VPCandidateInfo
static bool skipPGOUse(const InstrumentationOptions &Opts, const Function &F)
static uint64_t sumEdgeCount(const ArrayRef< PGOUseEdge * > Edges)
static std::string getSimpleNodeName(const BasicBlock *Node)
static bool isIndirectBrTarget(BasicBlock *BB)
static bool annotateAllFunctions(const InstrumentationOptions &Opts, Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName, vfs::FileSystem &FS, function_ref< TargetLibraryInfo &(Function &)> LookupTLI, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, function_ref< LoopInfo *(Function &)> LookupLI, ProfileSummaryInfo *PSI, bool IsCS)
static GlobalVariable * createIRLevelProfileFlagVar(const InstrumentationOptions &Opts, Module &M, PGOInstrumentationType InstrumentationType)
static void verifyFuncBFI(const InstrumentationOptions &Opts, PGOUseFunc &Func, CycleInfo &CI, BranchProbabilityInfo &NBPI, uint64_t HotCountThreshold, uint64_t ColdCountThreshold)
static bool canRenameComdat(const InstrumentationOptions &Opts, Function &F, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
static std::string getBranchCondString(Instruction *TI)
static uint32_t getMaxNumAnnotations(const InstrumentationOptions &Opts, const LLVMContext &C, InstrProfValueKind ValueProfKind)
static const char * ValueProfKindDescr[]
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains the declarations for profiling metadata utility functions.
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
std::pair< BasicBlock *, BasicBlock * > Edge
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)
StringSet - A set-like wrapper for the StringMap.
Defines the virtual file system interface vfs::FileSystem.
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
static constexpr roundingMode rmNearestTiesToEven
static constexpr const fltSemantics & IEEEdouble()
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Class for arbitrary precision integers.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
LLVM Basic Block Representation.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI bool isIrrLoopHeader(const BasicBlock *BB)
Returns true if BB is an irreducible loop header block.
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
Edge & addEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W)
const std::vector< std::unique_ptr< Edge > > & allEdges() const
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_ABI StringRef getName() const
void setSelectionKind(SelectionKind Val)
SelectionKind getSelectionKind() const
Conditional Branch instruction.
Value * getCondition() const
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This is the shared class of boolean and integer constants.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Diagnostic information for the PGO profiler.
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
Lightweight error class with error context and mandatory checking.
void compute(FunctionT &F)
Compute the cycle info for a function.
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
This instruction compares its operands according to the predicate given to the constructor.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
uint64_t getMaximumFunctionCount(bool UseCS)
Return the maximum of all known function counts.
Expected< NamedInstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName="", uint64_t *MismatchedFuncSum=nullptr)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
Base class for instruction visitors.
static bool canInstrumentCallsite(const CallBase &CB)
instrprof_error get() const
std::string message() const override
Return the error message as a string.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
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...
LLVM_ABI void update(ArrayRef< uint8_t > Data)
This is an important class for using LLVM in a threaded context.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Analysis pass that exposes the LoopInfo for a function.
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
LLVM_ABI MDNode * createIrrLoopHeaderWeight(uint64_t Weight)
Return metadata containing an irreducible loop header weight.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
A Module instance is used to store all the information related to an LLVM module.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI PGOInstrumentationUse(std::string Filename="", std::string RemappingFilename="", bool IsCS=false, IntrusiveRefCntPtr< vfs::FileSystem > FS=nullptr)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
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.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI uint64_t getOrCompColdCountThreshold() const
Returns ColdCountThreshold if set.
LLVM_ABI bool isColdCount(uint64_t C) const
Returns true if count C is considered cold.
LLVM_ABI void refresh(std::unique_ptr< ProfileSummary > &&Other=nullptr)
If a summary is provided as argument, use that.
LLVM_ABI bool isHotCount(uint64_t C) const
Returns true if count C is considered hot.
LLVM_ABI uint64_t getOrCompHotCountThreshold() const
Returns HotCountThreshold if set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
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.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Value * getOperand(unsigned i) const
std::vector< CandidateInfo > get(InstrProfValueKind Kind) const
returns a list of value profiling candidates of the given kind
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
A raw_ostream that writes to an std::string.
The virtual file system interface.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
initializer< Ty > init(const Ty &Val)
uint64_t getFuncHash(const FuncRecordTy *Record)
Return the structural hash associated with the function.
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
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
void write64le(void *P, uint64_t V)
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.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
LLVM_ABI void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count)
LLVM_ABI void setProfMetadata(Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOObjectName for LLVM IR instrumentation.
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
auto successors(const MachineBasicBlock *BB)
LLVM_ABI void createProfileSamplingVar(Module &M)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
cl::opt< bool > EnableVTableProfileUse("enable-vtable-profile-use", cl::init(false), cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable " "profiles will be used by ICP pass for more efficient indirect " "call sequence. If false, type profiles won't be used."))
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
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...
LLVM_ABI GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI PGOViewCountsType getPGOViewCounts(const LLVMContext &C)
Return -pgo-view-counts.
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
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...
cl::opt< bool > NoPGOWarnMismatch
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
OperandBundleDefT< Value * > OperandBundleDef
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
Instruction::const_succ_iterator const_succ_iterator
uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
constexpr bool valueOr(BoolOrDefault X, bool Default)
LLVM_ABI unsigned getMaxNumVTableAnnotations(const LLVMContext &C)
Return -icp-max-num-vtables.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI StringRef getViewBlockFreqFuncName(const LLVMContext &C)
Return -view-bfi-func-name.
uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
LLVM_ABI SmallVector< uint32_t > downscaleWeights(ArrayRef< uint64_t > Weights, std::optional< uint64_t > KnownMaxCount=std::nullopt)
downscale the given weights preserving the ratio.
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
LLVM_ABI bool isPGOInstrumentColdFunctionOnly(const cl::LibraryOptionsContext &LibraryOptions)
Return the value of -pgo-instrument-cold-function-only in LibraryOptions.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Implement std::hash so that hash_code can be used in STL containers.
DOTGraphTraits(bool isSimple=false)
static std::string getGraphName(const PGOUseFunc *G)
std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph)
DefaultDOTGraphTraits(bool simple=false)
static ChildIteratorType child_end(const NodeRef N)
static NodeRef getEntryNode(const PGOUseFunc *G)
static ChildIteratorType child_begin(const NodeRef N)
static nodes_iterator nodes_end(const PGOUseFunc *G)
const BasicBlock * NodeRef
static nodes_iterator nodes_begin(const PGOUseFunc *G)
pointer_iterator< Function::const_iterator > nodes_iterator
const_succ_iterator ChildIteratorType
bool isBlockUniform(unsigned BlockIdx) const
Check if a basic block is entered via a wave-uniform branch.
std::vector< uint64_t > Counts
CountPseudoKind getCountPseudoKind() const
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
std::vector< uint8_t > UniformityBits
For AMDGPU offload profiling: 1 bit per basic block indicating whether the block is usually entered w...
static void setCSFlagInHash(uint64_t &FuncHash)
static constexpr uint64_t FUNC_HASH_MASK
Instruction * AnnotatedInst