84 #include <unordered_map>
90 #define DEBUG_TYPE "pgo-instrumentation"
92 STATISTIC(NumOfPGOInstrument,
"Number of edges instrumented.");
93 STATISTIC(NumOfPGOSelectInsts,
"Number of select instruction instrumented.");
94 STATISTIC(NumOfPGOMemIntrinsics,
"Number of mem intrinsics instrumented.");
95 STATISTIC(NumOfPGOEdge,
"Number of edges.");
96 STATISTIC(NumOfPGOBB,
"Number of basic-blocks.");
97 STATISTIC(NumOfPGOSplit,
"Number of critical edge splits.");
98 STATISTIC(NumOfPGOFunc,
"Number of functions having valid profile counts.");
99 STATISTIC(NumOfPGOMismatch,
"Number of functions having mismatch profile.");
100 STATISTIC(NumOfPGOMissing,
"Number of functions without profile.");
101 STATISTIC(NumOfPGOICall,
"Number of indirect call value instrumentations.");
108 cl::desc(
"Specify the path of profile data file. This is"
109 "mainly for test purpose."));
115 cl::desc(
"Disable Value Profiling"));
121 cl::desc(
"Max number of annotations for a single indirect "
128 cl::desc(
"Max number of preicise value annotations for a single memop"
135 cl::desc(
"Append function hash to the name of COMDAT function to avoid "
136 "function hash mismatch due to the preinliner"));
142 cl::desc(
"Use this option to turn on/off "
143 "warnings about missing profile data for "
150 cl::desc(
"Use this option to turn off/on "
151 "warnings about profile cfg mismatch."));
159 cl::desc(
"The option is used to turn on/off "
160 "warnings about hash mismatch for comdat "
166 cl::desc(
"Use this option to turn on/off SELECT "
167 "instruction instrumentation. "));
172 cl::desc(
"A boolean option to show CFG dag "
173 "with raw profile counts from "
174 "profile data. See also option "
175 "-pgo-view-counts. To limit graph "
176 "display to only one function, use "
177 "filtering option -view-bfi-func-name."));
182 cl::desc(
"Use this option to turn on/off "
183 "memory intrinsic size profiling."));
188 cl::desc(
"When this option is on, the annotated "
189 "branch probability will be emitted as "
190 " optimization remarks: -Rpass-analysis="
208 return std::string();
213 return std::string();
225 else if (CV->
isOne())
241 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
245 struct SelectInstVisitor :
public InstVisitor<SelectInstVisitor> {
249 unsigned *CurCtrIdx =
nullptr;
250 unsigned TotalNumCtrs = 0;
252 uint64_t FuncHash = 0;
253 PGOUseFunc *UseFunc =
nullptr;
255 SelectInstVisitor(
Function &Func) :
F(Func) {}
266 void instrumentSelects(
Function &Func,
unsigned *Ind,
unsigned TotalNC,
268 Mode = VM_instrument;
270 TotalNumCtrs = TotalNC;
277 void annotateSelects(
Function &Func, PGOUseFunc *UF,
unsigned *Ind) {
290 unsigned getNumOfSelectInsts()
const {
return NSIs; }
294 struct MemIntrinsicVisitor :
public InstVisitor<MemIntrinsicVisitor> {
298 unsigned CurCtrId = 0;
299 unsigned TotalNumCtrs = 0;
301 uint64_t FuncHash = 0;
302 PGOUseFunc *UseFunc =
nullptr;
303 std::vector<Instruction *> Candidates;
305 MemIntrinsicVisitor(
Function &Func) :
F(Func) {}
307 void countMemIntrinsics(
Function &Func) {
313 void instrumentMemIntrinsics(
Function &Func,
unsigned TotalNC,
315 Mode = VM_instrument;
316 TotalNumCtrs = TotalNC;
322 std::vector<Instruction *> findMemIntrinsics(
Function &Func) {
333 unsigned getNumOfMemIntrinsics()
const {
return NMemIs; }
336 class PGOInstrumentationGenLegacyPass :
public ModulePass {
345 StringRef getPassName()
const override {
return "PGOInstrumentationGenPass"; }
348 bool runOnModule(
Module &M)
override;
355 class PGOInstrumentationUseLegacyPass :
public ModulePass {
360 PGOInstrumentationUseLegacyPass(std::string Filename =
"")
361 :
ModulePass(
ID), ProfileFileName(std::move(Filename)) {
368 StringRef getPassName()
const override {
return "PGOInstrumentationUsePass"; }
371 std::string ProfileFileName;
373 bool runOnModule(
Module &M)
override;
383 "PGO instrumentation.",
false,
false)
390 return new PGOInstrumentationGenLegacyPass();
395 "Read PGO instrumentation profile.",
false,
false)
402 return new PGOInstrumentationUseLegacyPass(Filename.str());
420 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(
false), Removed(
false),
423 const std::string infoString()
const {
424 return (
Twine(Removed ?
"-" :
" ") + (InMST ?
" " :
"*") +
425 (IsCritical ?
"c" :
" ") +
" W=" +
Twine(Weight)).str();
435 BBInfo(
unsigned IX) : Group(this), Index(IX), Rank(0) {}
438 const std::string infoString()
const {
439 return (
Twine(
"Index=") +
Twine(Index)).str();
444 template <
class Edge,
class BBInfo>
class FuncPGOInstrumentation {
447 void computeCFGHash();
448 void renameComdatFunction();
450 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
453 std::vector<std::vector<Instruction *>> ValueSites;
454 SelectInstVisitor SIVisitor;
455 MemIntrinsicVisitor MIVisitor;
456 std::string FuncName;
459 uint64_t FunctionHash;
469 BBInfo &getBBInfo(
const BasicBlock *BB)
const {
return MST.getBBInfo(BB); }
472 BBInfo *findBBInfo(
const BasicBlock *BB)
const {
return MST.findBBInfo(BB); }
475 void dumpInfo(std::string Str =
"")
const {
476 MST.dumpEdges(
dbgs(),
Twine(
"Dump Function ") + FuncName +
" Hash: " +
477 Twine(FunctionHash) +
"\t" + Str);
480 FuncPGOInstrumentation(
482 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
485 :
F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
486 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(
F, BPI,
BFI) {
489 SIVisitor.countSelects(Func);
490 MIVisitor.countMemIntrinsics(Func);
491 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
492 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
494 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
498 if (ComdatMembers.size())
499 renameComdatFunction();
500 DEBUG(dumpInfo(
"after CFGMST"));
502 NumOfPGOBB += MST.BBInfos.size();
503 for (
auto &
E : MST.AllEdges) {
508 NumOfPGOInstrument++;
516 unsigned getNumCounters() {
517 unsigned NumCounters = 0;
518 for (
auto &
E : this->MST.AllEdges) {
519 if (!
E->InMST && !
E->Removed)
522 return NumCounters + SIVisitor.getNumOfSelectInsts();
528 template <
class Edge,
class BBInfo>
529 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
530 std::vector<char> Indexes;
536 auto BI = findBBInfo(Succ);
540 for (
int J = 0; J < 4; J++)
541 Indexes.push_back((
char)(Index >> (J * 8)));
545 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
546 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
547 (uint64_t)MST.AllEdges.size() << 32 | JC.
getCRC();
551 static bool canRenameComdat(
553 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
565 for (
auto &&CM :
make_range(ComdatMembers.equal_range(C))) {
566 if (dyn_cast<GlobalAlias>(CM.second))
576 template <
class Edge,
class BBInfo>
577 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
578 if (!canRenameComdat(F, ComdatMembers))
581 std::string NewFuncName =
585 FuncName =
Twine(FuncName +
"." +
Twine(FunctionHash)).
str();
601 std::string NewComdatName =
606 for (
auto &&CM :
make_range(ComdatMembers.equal_range(OrigComdat))) {
607 if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
609 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
610 std::string OrigGAName = GA->getName().str();
611 GA->setName(
Twine(GA->getName() +
"." +
Twine(FunctionHash)));
624 template <
class Edge,
class BBInfo>
625 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *
E) {
626 if (E->InMST || E->Removed)
632 if (SrcBB ==
nullptr)
634 if (DestBB ==
nullptr)
648 DEBUG(
dbgs() <<
"Split critical edge: " << getBBInfo(SrcBB).Index <<
" --> "
649 << getBBInfo(DestBB).Index <<
"\n");
652 assert(InstrBB &&
"Critical edge is not split");
660 static void instrumentOneFunc(
662 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
663 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers,
true, BPI,
665 unsigned NumCounters = FuncInfo.getNumCounters();
669 for (
auto &E : FuncInfo.MST.AllEdges) {
670 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
675 assert(Builder.GetInsertPoint() != InstrBB->
end() &&
676 "Cannot get the Instrumentation point");
680 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
681 Builder.getInt32(I++)});
685 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
686 FuncInfo.FunctionHash);
692 unsigned NumIndirectCallSites = 0;
693 for (
auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
695 Value *Callee =
CS.getCalledValue();
696 DEBUG(
dbgs() <<
"Instrument one indirect call: CallSite Index = "
697 << NumIndirectCallSites <<
"\n");
699 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
700 "Cannot get the Instrumentation point");
704 Builder.getInt64(FuncInfo.FunctionHash),
705 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
706 Builder.getInt32(IPVK_IndirectCallTarget),
707 Builder.getInt32(NumIndirectCallSites++)});
709 NumOfPGOICall += NumIndirectCallSites;
712 FuncInfo.MIVisitor.instrumentMemIntrinsics(
713 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
717 struct PGOUseEdge :
public PGOEdge {
721 : PGOEdge(Src, Dest, W), CountValid(
false), CountValue(0) {}
724 void setEdgeCount(uint64_t
Value) {
730 const std::string infoString()
const {
732 return PGOEdge::infoString();
733 return (
Twine(PGOEdge::infoString()) +
" Count=" +
Twine(CountValue))
741 struct UseBBInfo :
public BBInfo {
744 int32_t UnknownCountInEdge;
745 int32_t UnknownCountOutEdge;
747 DirectEdges OutEdges;
748 UseBBInfo(
unsigned IX)
749 : BBInfo(IX), CountValue(0), CountValid(
false), UnknownCountInEdge(0),
750 UnknownCountOutEdge(0) {}
751 UseBBInfo(
unsigned IX, uint64_t C)
752 : BBInfo(IX), CountValue(C), CountValid(
true), UnknownCountInEdge(0),
753 UnknownCountOutEdge(0) {}
756 void setBBInfoCount(uint64_t
Value) {
762 const std::string infoString()
const {
764 return BBInfo::infoString();
765 return (
Twine(BBInfo::infoString()) +
" Count=" +
Twine(CountValue)).str();
772 for (
auto &E : Edges) {
775 Total += E->CountValue;
783 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
786 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers,
false, BPI, BFI),
787 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
793 void populateCounters();
796 void setBranchWeights();
799 void annotateValueSites();
805 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
808 FuncFreqAttr getFuncFreqAttr()
const {
return FreqAttr; }
811 uint64_t getFuncHash()
const {
return FuncInfo.FunctionHash; }
816 UseBBInfo &getBBInfo(
const BasicBlock *BB)
const {
817 return FuncInfo.getBBInfo(BB);
821 UseBBInfo *findBBInfo(
const BasicBlock *BB)
const {
822 return FuncInfo.findBBInfo(BB);
831 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
835 uint64_t ProgramMaxCount;
847 FuncFreqAttr FreqAttr;
850 void setInstrumentedCounts(
const std::vector<uint64_t> &CountFromProfile);
854 void setEdgeCount(DirectEdges &Edges, uint64_t
Value);
857 const std::string getFuncName()
const {
return FuncInfo.FuncName; }
862 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
863 if (ProgramMaxCount == 0)
869 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
871 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
878 void PGOUseFunc::setInstrumentedCounts(
879 const std::vector<uint64_t> &CountFromProfile) {
881 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
883 std::vector<PGOUseEdge *> WorkList;
884 for (
auto &E : FuncInfo.MST.AllEdges)
885 WorkList.push_back(E.get());
888 for (
auto &E : WorkList) {
892 uint64_t CountValue = CountFromProfile[I++];
894 getBBInfo(InstrBB).setBBInfoCount(CountValue);
895 E->setEdgeCount(CountValue);
903 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
904 NewEdge.setEdgeCount(CountValue);
906 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
907 NewEdge1.setEdgeCount(CountValue);
908 NewEdge1.InMST =
true;
909 getBBInfo(InstrBB).setBBInfoCount(CountValue);
911 ProfileCountSize = CountFromProfile.size();
917 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t
Value) {
918 for (
auto &E : Edges) {
921 E->setEdgeCount(Value);
923 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
924 getBBInfo(E->DestBB).UnknownCountInEdge--;
939 auto Err = IPE.
get();
940 bool SkipWarning =
false;
963 ProfileRecord = std::move(Result.
get());
964 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
967 DEBUG(
dbgs() << CountFromProfile.size() <<
" counts\n");
968 uint64_t ValueSum = 0;
969 for (
unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
970 DEBUG(
dbgs() <<
" " << I <<
": " << CountFromProfile[I] <<
"\n");
971 ValueSum += CountFromProfile[
I];
974 DEBUG(
dbgs() <<
"SUM = " << ValueSum <<
"\n");
976 getBBInfo(
nullptr).UnknownCountOutEdge = 2;
977 getBBInfo(
nullptr).UnknownCountInEdge = 2;
979 setInstrumentedCounts(CountFromProfile);
986 void PGOUseFunc::populateCounters() {
988 for (
auto &E : FuncInfo.MST.AllEdges) {
994 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
995 UseBBInfo &DestInfo = getBBInfo(DestBB);
996 SrcInfo.OutEdges.push_back(E.get());
997 DestInfo.InEdges.push_back(E.get());
998 SrcInfo.UnknownCountOutEdge++;
999 DestInfo.UnknownCountInEdge++;
1003 DestInfo.UnknownCountInEdge--;
1004 SrcInfo.UnknownCountOutEdge--;
1007 bool Changes =
true;
1008 unsigned NumPasses = 0;
1016 UseBBInfo *Count = findBBInfo(&BB);
1017 if (Count ==
nullptr)
1019 if (!Count->CountValid) {
1020 if (Count->UnknownCountOutEdge == 0) {
1021 Count->CountValue = sumEdgeCount(Count->OutEdges);
1022 Count->CountValid =
true;
1024 }
else if (Count->UnknownCountInEdge == 0) {
1025 Count->CountValue = sumEdgeCount(Count->InEdges);
1026 Count->CountValid =
true;
1030 if (Count->CountValid) {
1031 if (Count->UnknownCountOutEdge == 1) {
1033 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1037 if (Count->CountValue > OutSum)
1038 Total = Count->CountValue - OutSum;
1039 setEdgeCount(Count->OutEdges, Total);
1042 if (Count->UnknownCountInEdge == 1) {
1044 uint64_t InSum = sumEdgeCount(Count->InEdges);
1045 if (Count->CountValue > InSum)
1046 Total = Count->CountValue - InSum;
1047 setEdgeCount(Count->InEdges, Total);
1054 DEBUG(
dbgs() <<
"Populate counts in " << NumPasses <<
" passes.\n");
1057 for (
auto &BB : F) {
1058 auto BI = findBBInfo(&BB);
1061 assert(BI->CountValid &&
"BB count is not valid");
1064 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1065 F.setEntryCount(FuncEntryCount);
1066 uint64_t FuncMaxCount = FuncEntryCount;
1067 for (
auto &BB : F) {
1068 auto BI = findBBInfo(&BB);
1071 FuncMaxCount =
std::max(FuncMaxCount, BI->CountValue);
1073 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1076 FuncInfo.SIVisitor.annotateSelects(F,
this, &CountPosition);
1077 assert(CountPosition == ProfileCountSize);
1079 DEBUG(FuncInfo.dumpInfo(
"after reading profile."));
1083 void PGOUseFunc::setBranchWeights() {
1085 DEBUG(
dbgs() <<
"\nSetting branch weights.\n");
1086 for (
auto &BB : F) {
1090 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1092 if (getBBInfo(&BB).CountValue == 0)
1096 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1097 unsigned Size = BBCountInfo.OutEdges.size();
1099 uint64_t MaxCount = 0;
1100 for (
unsigned s = 0; s <
Size; s++) {
1101 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1104 if (DestBB ==
nullptr)
1107 uint64_t EdgeCount = E->CountValue;
1108 if (EdgeCount > MaxCount)
1109 MaxCount = EdgeCount;
1110 EdgeCounts[SuccNum] = EdgeCount;
1116 void SelectInstVisitor::instrumentOneSelectInst(
SelectInst &SI) {
1117 Module *M = F.getParent();
1121 auto *Step = Builder.CreateZExt(SI.
getCondition(), Int64Ty);
1125 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1126 Builder.getInt32(*CurCtrIdx), Step});
1130 void SelectInstVisitor::annotateOneSelectInst(
SelectInst &SI) {
1131 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1132 assert(*CurCtrIdx < CountFromProfile.size() &&
1133 "Out of bound access of counters");
1134 uint64_t SCounts[2];
1135 SCounts[0] = CountFromProfile[*CurCtrIdx];
1137 uint64_t TotalCount = 0;
1138 auto BI = UseFunc->findBBInfo(SI.
getParent());
1140 TotalCount = BI->CountValue;
1142 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1143 uint64_t MaxCount =
std::max(SCounts[0], SCounts[1]);
1148 void SelectInstVisitor::visitSelectInst(
SelectInst &SI) {
1160 instrumentOneSelectInst(SI);
1163 annotateOneSelectInst(SI);
1170 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(
MemIntrinsic &
MI) {
1171 Module *M = F.getParent();
1176 assert(!dyn_cast<ConstantInt>(Length));
1180 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
1181 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1185 void MemIntrinsicVisitor::visitMemIntrinsic(
MemIntrinsic &MI) {
1190 if (dyn_cast<ConstantInt>(Length))
1198 instrumentOneMemIntrinsic(MI);
1201 Candidates.push_back(&MI);
1208 void PGOUseFunc::annotateValueSites() {
1216 annotateValueSites(
Kind);
1221 unsigned ValueSiteIndex = 0;
1222 auto &ValueSites = FuncInfo.ValueSites[
Kind];
1223 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1224 if (NumValueSites != ValueSites.size()) {
1228 Twine(
"Inconsistent number of value sites for kind = ") +
Twine(Kind) +
1229 " in " + F.getName().
str(),
1234 for (
auto &I : ValueSites) {
1235 DEBUG(
dbgs() <<
"Read one value site profile (kind = " << Kind
1236 <<
"): Index = " << ValueSiteIndex <<
" out of "
1237 << NumValueSites <<
"\n");
1239 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1251 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1255 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1258 if (!TT.supportsCOMDAT())
1262 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
1269 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1273 if (
Comdat *C = F.getComdat())
1274 ComdatMembers.insert(std::make_pair(C, &F));
1276 if (
Comdat *C = GV.getComdat())
1277 ComdatMembers.insert(std::make_pair(C, &GV));
1279 if (
Comdat *C = GA.getComdat())
1280 ComdatMembers.insert(std::make_pair(C, &GA));
1287 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1291 if (F.isDeclaration())
1293 auto *BPI = LookupBPI(F);
1294 auto *BFI = LookupBFI(F);
1295 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
1300 bool PGOInstrumentationGenLegacyPass::runOnModule(
Module &M) {
1305 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(
F).getBPI();
1308 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
1335 DEBUG(
dbgs() <<
"Read in profile counters: ");
1339 if (
Error E = ReaderOrErr.takeError()) {
1347 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1348 std::move(ReaderOrErr.get());
1355 if (!PGOReader->isIRLevelProfile()) {
1357 ProfileFileName.
data(),
"Not an IR level instrumentation profile"));
1361 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1363 std::vector<Function *> HotFunctions;
1364 std::vector<Function *> ColdFunctions;
1366 if (F.isDeclaration())
1368 auto *BPI = LookupBPI(F);
1369 auto *BFI = LookupBFI(F);
1370 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
1371 if (!Func.readCounters(PGOReader.get()))
1373 Func.populateCounters();
1374 Func.setBranchWeights();
1375 Func.annotateValueSites();
1376 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1377 if (FreqAttr == PGOUseFunc::FFA_Cold)
1378 ColdFunctions.push_back(&F);
1379 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1380 HotFunctions.push_back(&F);
1384 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1385 llvm::make_unique<BranchProbabilityInfo>(
F, LI);
1386 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1387 llvm::make_unique<BlockFrequencyInfo>(
F, *NewBPI, LI);
1396 ViewGraph(&Func,
Twine(
"PGORawCounts_") + Func.getFunc().getName());
1399 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
1404 for (
auto &F : HotFunctions) {
1405 F->addFnAttr(llvm::Attribute::InlineHint);
1406 DEBUG(
dbgs() <<
"Set inline attribute to function: " << F->getName()
1409 for (
auto &F : ColdFunctions) {
1411 DEBUG(
dbgs() <<
"Set cold attribute to function: " << F->getName() <<
"\n");
1417 : ProfileFileName(std::move(Filename)) {
1440 bool PGOInstrumentationUseLegacyPass::runOnModule(
Module &M) {
1445 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(
F).getBPI();
1448 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
1456 uint64_t MaxCount) {
1458 assert(MaxCount > 0 &&
"Bad max count");
1461 for (
const auto &ECI : EdgeCounts)
1465 for (
const auto &W : Weights) {
dbgs() << W <<
" "; }
1469 std::string BrCondStr = getBranchCondString(TI);
1470 if (BrCondStr.empty())
1474 std::accumulate(Weights.begin(), Weights.end(), 0,
1475 [](
unsigned w1,
unsigned w2) {
return w1 + w2; });
1476 uint64_t TotalCount =
1477 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1478 [](uint64_t c1, uint64_t c2) {
return c1 + c2; });
1480 std::string BranchProbStr;
1483 OS <<
" (total count : " << TotalCount <<
")";
1489 " is true with probability : " +
Twine(BranchProbStr));
1499 return &G->getFunc().front();
1506 return nodes_iterator(G->getFunc().begin());
1509 return nodes_iterator(G->getFunc().end());
1517 std::string SimpleNodeName;
1528 return G->getFunc().getName();
1536 UseBBInfo *BI = Graph->findBBInfo(Node);
1538 if (BI && BI->CountValid)
1539 OS << BI->CountValue <<
"\\l";
1546 for (
auto BI = Node->
begin(); BI != Node->
end(); ++BI) {
1548 if (!isa<SelectInst>(I))
1551 OS <<
"SELECT : { T = ";
1553 bool HasProf = I->extractProfMetadata(TC, FC);
1555 OS <<
"Unknown, F = Unknown }\\l";
1557 OS << TC <<
", F = " << FC <<
" }\\l";
void push_back(const T &Elt)
static cl::opt< bool > PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off SELECT ""instruction instrumentation. "))
LinkageTypes getLinkage() const
void setProfMetadata(Module *M, Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
succ_const_iterator ChildIteratorType
ModulePass * createPGOInstrumentationGenLegacyPass()
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Base class for instruction visitors.
STATISTIC(NumFunctions,"Total number of functions")
A Module instance is used to store all the information related to an LLVM module. ...
static ChildIteratorType child_begin(const NodeRef N)
Diagnostic information for the PGO profiler.
Available for inspection, not emission.
const BasicBlock * NodeRef
static void collectComdatMembers(Module &M, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph)
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
An efficient, type-erasing, non-owning reference to a callable.
Externally visible function.
uint64_t getMaximumFunctionCount()
Return the maximum of all known function counts.
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
static IntegerType * getInt64Ty(LLVMContext &C)
Error takeError()
Take ownership of the stored error.
Base class for error info classes.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
An union-find based Minimum Spanning Tree for CFG.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
std::string str() const
Return the twine contents as a std::string.
This class represents the LLVM 'select' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
PGOInstrumentationUse(std::string Filename="")
StringRef getName() const
Get a short "name" for the module.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Legacy analysis pass which computes BlockFrequencyInfo.
static std::string getGraphName(const PGOUseFunc *G)
VisitMode
The select instruction visitor plays three roles specified by the mode.
void setName(const Twine &Name)
Change the name of the value.
Tagged union holding either a T or a Error.
StringRef getName() const
static std::string getSimpleNodeName(const BasicBlock *Node)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static bool isSimple(Instruction *I)
Analysis pass which computes BranchProbabilityInfo.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
static cl::opt< bool > EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden, cl::desc("When this option is on, the annotated ""branch probability will be emitted as "" optimization remarks: -Rpass-analysis=""pgo-instr-use"))
This file provides the interface for IR based instrumentation passes ( (profile-gen, and profile-use).
INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass,"pgo-instr-gen","PGO instrumentation.", false, false) INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass
static cl::opt< bool > DisableValueProfiling("disable-vp", cl::init(false), cl::Hidden, cl::desc("Disable Value Profiling"))
static NodeRef getEntryNode(const PGOUseFunc *G)
static void createIRLevelProfileFlagVariable(Module &M)
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
static cl::opt< unsigned > MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of annotations for a single indirect ""call callsite"))
void setComdat(Comdat *C)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void initializePGOInstrumentationGenLegacyPassPass(PassRegistry &)
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
static cl::opt< bool > PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, cl::desc("Use this option to turn on/off ""warnings about missing profile data for ""functions."))
static bool InstrumentAllFunctions(Module &M, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI)
static nodes_iterator nodes_end(const PGOUseFunc *G)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Legacy analysis pass which computes BranchProbabilityInfo.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static ChildIteratorType child_end(const NodeRef N)
Interval::succ_iterator succ_end(Interval *I)
static cl::opt< std::string > PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path of profile data file. This is""mainly for test purpose."))
std::string message() const override
Return the error message as a string.
static cl::opt< bool > NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true), cl::Hidden, cl::desc("The option is used to turn on/off ""warnings about hash mismatch for comdat ""functions."))
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Same, but only replaced by something equivalent.
initializer< Ty > init(const Ty &Val)
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
const Comdat * getComdat() const
const Value * getCondition() const
static StringRef getPredicateName(Predicate P)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
ModulePass * createPGOInstrumentationUseLegacyPass(StringRef Filename=StringRef(""))
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
This instruction compares its operands according to the predicate given to the constructor.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
pointer_iterator< Function::const_iterator > nodes_iterator
Value * getOperand(unsigned i) const
SelectionKind getSelectionKind() const
static uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
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.
Predicate getPredicate() const
Return the predicate for this instruction.
void initializePGOInstrumentationUseLegacyPassPass(PassRegistry &)
static uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
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...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Triple - Helper class for working with autoconf configuration names.
static 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...
bool isConditional() const
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
DOTGraphTraits(bool isSimple=false)
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
static nodes_iterator nodes_begin(const PGOUseFunc *G)
instrprof_error get() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
pgo instr PGO instrumentation
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Value * getLength() const
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
reference get()
Returns a reference to the stored T value.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Class for arbitrary precision integers.
static cl::opt< bool > NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, cl::desc("Use this option to turn off/on ""warnings about profile cfg mismatch."))
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
static cl::opt< unsigned > MaxNumMemOPAnnotations("memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of preicise value annotations for a single memop""intrinsic"))
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
pgo instr Read PGO instrumentation profile
Value * getCondition() const
Analysis providing branch probability information.
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...
Profiling information for a single function.
Expected< InstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
static bool annotateAllFunctions(Module &M, StringRef ProfileFileName, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI)
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
static std::vector< Instruction * > findIndirectCallSites(Function &F)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Keep one copy of named function when linking (weak)
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static cl::opt< bool > PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden, cl::desc("A boolean option to show CFG dag ""with raw profile counts from ""profile data. See also option ""-pgo-view-counts. To limit graph ""display to only one function, use ""filtering option -view-bfi-func-name."))
void emitOptimizationRemarkAnalysis(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization analysis remark message.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static cl::opt< bool > DoComdatRenaming("do-comdat-renaming", cl::init(false), cl::Hidden, cl::desc("Append function hash to the name of COMDAT function to avoid ""function hash mismatch due to the preinliner"))
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
void update(ArrayRef< char > Data)
Lightweight error class with error context and mandatory checking.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
virtual std::string message() const
Return the error message as a string.
cl::opt< std::string > ViewBlockFreqFuncName
StringRef - Represent a constant reference to a string, i.e.
Reader for the indexed binary instrprof format.
A container for analyses that lazily runs them and caches their results.
cl::opt< bool > PGOViewCounts
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static cl::opt< bool > PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off ""memory intrinsic size profiling."))
const BasicBlock * getParent() const
static 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...
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
LLVMContext & getContext() const
Get the global data context.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...