19#include "llvm/Config/config.h"
56#include <system_error>
63#define DEBUG_TYPE "instrprof"
67 cl::desc(
"Use full module build paths in the profile counter names for "
68 "static functions."));
80 cl::desc(
"Strip specified level of directory name from source path in "
81 "the profile counter name for static functions."));
84 const std::string &ErrMsg =
"") {
96 OS <<
"unrecognized instrumentation profile encoding format";
99 OS <<
"invalid instrumentation profile data (bad magic)";
102 OS <<
"invalid instrumentation profile data (file header is corrupt)";
105 OS <<
"invalid instrumentation profile data (file is incomplete or header "
109 OS <<
"unsupported instrumentation profile format version";
112 OS <<
"unsupported instrumentation profile hash type";
115 OS <<
"too much profile data";
118 OS <<
"truncated profile data";
121 OS <<
"malformed instrumentation profile data";
124 OS <<
"debug info/binary for correlation is required";
127 OS <<
"debug info/binary for correlation is not necessary";
130 OS <<
"unable to correlate profile";
133 OS <<
"invalid profile created. Please file a bug "
134 "at: " BUG_REPORT_URL
135 " and include the profraw files that caused this error.";
138 OS <<
"no profile data available for function";
141 OS <<
"function control flow change detected (hash mismatch)";
144 OS <<
"function basic block count change detected (counter mismatch)";
147 OS <<
"function bitmap size change detected (bitmap size mismatch)";
150 OS <<
"counter overflow";
153 OS <<
"function value site count change detected (counter mismatch)";
156 OS <<
"failed to compress data (zlib)";
159 OS <<
"failed to uncompress data (zlib)";
162 OS <<
"empty raw profile file";
165 OS <<
"profile uses zlib compression but the profile reader was built "
166 "without zlib support";
169 OS <<
"raw profile version mismatch";
172 OS <<
"excessively large counter value suggests corrupted profile data";
175 OS <<
"cannot merge single-byte and incrementing counter profiles";
181 OS <<
": " << ErrMsg;
191class InstrProfErrorCategoryType :
public std::error_category {
192 const char *
name()
const noexcept
override {
return "llvm.instrprof"; }
194 std::string message(
int IE)
const override {
202 static InstrProfErrorCategoryType ErrorCategory;
203 return ErrorCategory;
208const char *InstrProfSectNameCommon[] = {
209#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
214const char *InstrProfSectNameCoff[] = {
215#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
220const char *InstrProfSectNamePrefix[] = {
221#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
231 "enable-name-compression",
235 "enable-vtable-value-profiling",
cl::init(
false),
236 cl::desc(
"If true, the virtual table address will be instrumented to know "
237 "the types of a C++ pointer. The information is used in indirect "
238 "call promotion to do selective vtable-based comparison."));
241 "enable-vtable-profile-use",
cl::init(
false),
242 cl::desc(
"If ThinLTO and WPD is enabled and this option is true, vtable "
243 "profiles will be used by ICP pass for more efficient indirect "
244 "call sequence. If false, type profiles won't be used."));
248 bool AddSegmentInfo) {
249 std::string SectName;
252 SectName = InstrProfSectNamePrefix[IPSK];
255 SectName += InstrProfSectNameCoff[IPSK];
257 SectName += InstrProfSectNameCommon[IPSK];
259 if (OF ==
Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
260 SectName +=
",regular,live_support";
287 const uint64_t LastPos = FDOStream.
tell();
288 for (
const auto &
K :
P) {
289 FDOStream.
seek(
K.Pos);
290 for (uint64_t Elem :
K.D)
296 FDOStream.
seek(LastPos);
299 std::string &
Data = SOStream.
str();
300 for (
const auto &
K :
P) {
301 for (
int I = 0, E =
K.D.size();
I != E;
I++) {
304 Data.replace(
K.Pos +
I *
sizeof(uint64_t),
sizeof(uint64_t),
305 (
const char *)&Bytes,
sizeof(uint64_t));
313 [[maybe_unused]] uint64_t
Version) {
318 Name = Name.substr(1);
320 std::string NewName = std::string(Name);
326 if (FileName.
empty())
327 NewName = NewName.insert(0,
"<unknown>:");
329 NewName = NewName.insert(0, FileName.
str() +
":");
340 for (
const auto &CI : PathNameStr) {
349 return PathNameStr.
substr(LastPos);
410 if (MangledName.empty())
411 return std::make_pair(
StringRef(), IRPGOName);
412 return std::make_pair(FileName, MangledName);
416 if (FileName.
empty())
436 const char InvalidChars[] =
"-:;<>/\"'";
437 size_t FoundPos = VarName.find_first_of(InvalidChars);
438 while (FoundPos != std::string::npos) {
439 VarName[FoundPos] =
'_';
440 FoundPos = VarName.find_first_of(InvalidChars, FoundPos + 1);
446 const Triple &
T = M.getTargetTriple();
485 bool KeyImportedAliasesByAliasGUID) {
492 if (
Error E = addFuncWithName(
F, IRPGOFuncName, AddCanonical,
493 KeyImportedAliasesByAliasGUID))
497 if (PGOFuncName != IRPGOFuncName)
498 if (
Error E = addFuncWithName(
F, PGOFuncName, AddCanonical,
499 KeyImportedAliasesByAliasGUID))
504 if (!
G.hasName() || !
G.hasMetadata(LLVMContext::MD_type))
513 std::stable_partition(
514 MD5FuncMap.begin(), MD5FuncMap.end(),
515 [](
const auto &Entry) { return !Entry.second->isDeclaration(); });
530 bool Inserted =
true;
531 std::tie(std::ignore, Inserted) = MD5VTableMap.try_emplace(
537 if (
Error E = NameToGUIDMap(VTablePGOName))
542 if (
auto GUID = VTable.getGUIDIfAssigned();
545 MD5VTableMap.try_emplace(*GUID, &VTable);
548 if (!CanonicalName.
empty() && CanonicalName != VTablePGOName)
549 return NameToGUIDMap(CanonicalName);
564 const bool IsCompressed = (CompressedSize != 0);
572 UncompressedNameStrings,
578 NameStrings =
toStringRef(UncompressedNameStrings);
581 StringRef(
reinterpret_cast<const char *
>(
P), UncompressedSize);
582 P += UncompressedSize;
588 if (
Error E = NameCallback(Name))
591 while (
P < EndP && *
P == 0)
646 bool KeyImportedAliasesByAliasGUID) {
656 if (
Error E = NameToGUIDMap(PGOFuncName))
664 std::optional<GlobalValue::GUID> GUID;
665 MDNode *AliasGUIDMD = KeyImportedAliasesByAliasGUID
666 ?
F.getMetadata(
"thinlto_alias_guid")
672 GUID =
F.getGUIDIfAssigned();
674 MD5FuncMap.emplace_back(*GUID, &
F);
680 if (!CanonicalFuncName.
empty() && CanonicalFuncName != PGOFuncName)
681 return NameToGUIDMap(CanonicalFuncName);
689 return VTableAddrMap.lookup(Address, 0);
694 auto It =
partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t>
A) {
695 return A.first < Address;
701 if (It != AddrToMD5Map.end() && It->first ==
Address)
702 return (uint64_t)It->second;
714 bool DoCompression, std::string &Result) {
715 assert(!NameStrs.
empty() &&
"No name data to emit");
718 std::string UncompressedNameStrings =
723 "PGO name is invalid (contains separator token)");
725 unsigned EncLen =
encodeULEB128(UncompressedNameStrings.length(),
P);
728 auto WriteStringToResult = [&](
size_t CompressedLen,
StringRef InputStr) {
731 char *HeaderStr =
reinterpret_cast<char *
>(&Header[0]);
732 unsigned HeaderLen =
P - &Header[0];
733 Result.append(HeaderStr, HeaderLen);
738 if (!DoCompression) {
739 return WriteStringToResult(0, UncompressedNameStrings);
744 CompressedNameStrings,
747 return WriteStringToResult(CompressedNameStrings.
size(),
754 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
759 std::string &Result,
bool DoCompression) {
760 std::vector<std::string> NameStrs;
761 for (
auto *NameVar : NameVars) {
769 std::string &Result,
bool DoCompression) {
770 std::vector<std::string> VTableNameStrs;
771 for (
auto *VTable : VTables)
779 uint64_t FuncSum = 0;
785 for (
uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
786 uint64_t KindSum = 0;
802 double Score = 0.0f, FuncLevelScore = 0.0f;
805 auto J =
Input.ValueData.begin();
806 auto JE =
Input.ValueData.end();
807 while (
I != IE && J != JE) {
808 if (
I->Value == J->Value) {
816 }
else if (
I->Value < J->Value) {
832 assert(ThisNumValueSites ==
Other.getNumValueSites(ValueKind));
833 if (!ThisNumValueSites)
836 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
837 getOrCreateValueSitesForKind(ValueKind);
839 Other.getValueSitesForKind(ValueKind);
841 ThisSiteRecords[
I].
overlap(OtherSiteRecords[
I], ValueKind, Overlap,
847 uint64_t ValueCutoff) {
851 bool Mismatch = (
Counts.size() !=
Other.Counts.size());
855 for (
uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
858 if (ThisNumValueSites != OtherNumValueSites) {
870 for (
uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
874 uint64_t MaxCount = 0;
876 for (
size_t I = 0, E =
Other.Counts.size();
I < E; ++
I) {
879 MaxCount = std::max(
Other.Counts[
I], MaxCount);
884 if (MaxCount >= ValueCutoff) {
885 double FuncScore = 0.0;
886 for (
size_t I = 0, E =
Other.Counts.size();
I < E; ++
I)
892 FuncLevelOverlap.
Valid =
true;
903 std::vector<InstrProfValueData> Merged;
904 Merged.reserve(std::max(
ValueData.size(),
Input.ValueData.size()));
905 for (
const InstrProfValueData &J :
Input.ValueData) {
906 while (
I != IE &&
I->Value < J.Value) {
907 Merged.push_back(*
I);
910 if (
I != IE &&
I->Value == J.Value) {
915 Merged.push_back(*
I);
921 Merged.insert(Merged.end(),
I, IE);
937void InstrProfRecord::mergeValueProfData(
941 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
942 if (ThisNumValueSites != OtherNumValueSites) {
946 if (!ThisNumValueSites)
948 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
949 getOrCreateValueSitesForKind(ValueKind);
951 Src.getValueSitesForKind(ValueKind);
953 ThisSiteRecords[
I].
merge(OtherSiteRecords[
I], Weight, Warn);
966 for (
size_t I = 0, E =
Counts.size();
I < E; ++
I) {
967 uint64_t TotalCount =
Counts[
I];
969 uint64_t MinUniformCount = TotalCount - TotalCount / 10;
970 bool IsUniform = UniformCount >= MinUniformCount;
979 Dst.assign(Src.begin(), Src.end());
985 if (Dst.size() != Src.size()) {
990 for (
size_t I = 0, E = Src.size();
I < E; ++
I)
1004 Other.computeBlockUniformity();
1025 bool OtherHasUniformCounts = !
Other.UniformCounts.empty();
1026 for (
size_t I = 0, E =
Other.Counts.size();
I < E; ++
I) {
1039 if (HasUniformCounts && OtherHasUniformCounts) {
1044 for (
size_t I = 0, E =
Other.UniformCounts.size();
I < E; ++
I) {
1070 for (
size_t I = 0, E =
Other.BitmapBytes.size();
I < E; ++
I) {
1074 for (
uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1075 mergeValueProfData(Kind,
Other, Weight, Warn);
1078void InstrProfRecord::scaleValueProfData(
1081 for (
auto &R : getValueSitesForKind(ValueKind))
1082 R.scale(
N,
D, Warn);
1087 assert(
D != 0 &&
"D cannot be 0");
1109 for (
uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1110 scaleValueProfData(Kind,
N,
D, Warn);
1114uint64_t InstrProfRecord::remapValue(uint64_t
Value,
uint32_t ValueKind,
1119 if (ValueKind == IPVK_IndirectCallTarget)
1122 if (ValueKind == IPVK_VTableTarget)
1132 std::vector<InstrProfValueData> RemappedVD;
1133 RemappedVD.reserve(VData.
size());
1134 for (
const auto &V : VData) {
1135 uint64_t NewValue = remapValue(V.Value, ValueKind,
ValueMap);
1136 RemappedVD.push_back({NewValue, V.Count});
1139 std::vector<InstrProfValueSiteRecord> &ValueSites =
1140 getOrCreateValueSitesForKind(ValueKind);
1141 assert(ValueSites.size() == Site);
1144 ValueSites.emplace_back(std::move(RemappedVD));
1149 bool RemoveOutlierUNs) {
1152 UtilityNodeT MaxUN = 0;
1158 for (
auto &
Trace : Traces) {
1159 size_t CutoffTimestamp = 1;
1160 for (
size_t Timestamp = 0; Timestamp <
Trace.FunctionNameRefs.
size();
1162 IDT Id =
Trace.FunctionNameRefs[Timestamp];
1163 auto [It, WasInserted] = IdToFirstTimestamp.
try_emplace(Id, Timestamp);
1165 It->getSecond() = std::min<size_t>(It->getSecond(), Timestamp);
1166 if (Timestamp >= CutoffTimestamp) {
1168 CutoffTimestamp = 2 * Timestamp;
1172 for (
auto &[Id, FirstUN] : IdToFirstUN)
1173 for (
auto UN = FirstUN; UN <= MaxUN; ++UN)
1174 IdToUNs[Id].push_back(UN);
1176 IdToFirstUN.
clear();
1179 if (RemoveOutlierUNs) {
1181 for (
auto &[Id, UNs] : IdToUNs)
1182 for (
auto &UN : UNs)
1186 for (
auto &[Id, UNs] : IdToUNs)
1188 unsigned Freq = UNFrequency[UN];
1189 return Freq <= 1 || 2 * Freq > IdToUNs.
size();
1193 for (
auto &[Id, UNs] : IdToUNs)
1194 Nodes.emplace_back(Id, UNs);
1199 return std::make_pair(IdToFirstTimestamp[L.Id], L.Id) <
1200 std::make_pair(IdToFirstTimestamp[R.Id], R.Id);
1204#define INSTR_PROF_COMMON_API_IMPL
1218 ->getNumValueSites(VKind);
1223 ->getNumValueData(VKind);
1240 memset(VD, 0, TotalSizeInBytes);
1257 Closure.Record = &
Record;
1262std::unique_ptr<ValueProfData>
1266 std::unique_ptr<ValueProfData> VPD(
1277 uint8_t ValueDataCount = this->SiteCountArray[VSite];
1279 Record.addValueData(Kind, VSite, VDs, SymTab);
1280 ValueData += ValueDataCount;
1301 for (uint32_t
I = 0;
I < ND;
I++) {
1318 VR->deserializeTo(Record, SymTab);
1324 return std::unique_ptr<ValueProfData>(
new (::operator
new(TotalSize))
1328Error ValueProfData::checkIntegrity() {
1338 for (
uint32_t K = 0;
K < this->NumValueKinds;
K++) {
1339 if (VR->Kind > IPVK_Last)
1341 "value kind is invalid");
1346 "value profile address is greater than total size");
1352ValueProfData::getValueProfData(
const unsigned char *
D,
1353 const unsigned char *
const BufferEnd,
1355 using namespace support;
1360 const unsigned char *Header =
D;
1369 VPD->swapBytesToHost(Endianness);
1371 Error E = VPD->checkIntegrity();
1373 return std::move(
E);
1375 return std::move(VPD);
1379 using namespace support;
1395 using namespace support;
1418 for (
const InstrProfValueData &V : VDs)
1454 uint64_t ZeroCount = 0;
1456 for (
const auto &VD : VDs) {
1457 auto [
_, ValueInserted] = VisitedValues.
insert(VD.Value);
1458 if (VD.Value != 0 && !ValueInserted)
1460 if (VD.Value == 0) {
1461 ZeroCount += VD.Count;
1471 if (ZeroCount != 0) {
1480 if (Vals.
size() >= 5)
1509 uint32_t MaxNumValueData, uint64_t &TotalC,
1510 bool GetNoICPValue) {
1524 ValueData.
reserve((NOps - 3) / 2);
1525 for (
unsigned I = 3;
I < NOps;
I += 2) {
1526 if (ValueData.
size() >= MaxNumValueData)
1535 uint64_t CntValue =
Count->getZExtValue();
1538 InstrProfValueData V;
1539 V.Value =
Value->getZExtValue();
1550 if (!M.getTargetTriple().supportsCOMDAT())
1595 if (
F.getName().empty())
1601 if (CheckAddressTaken &&
F.hasAddressTaken())
1609 if (!
F.hasComdat()) {
1618 if (InstrProfileOutput.
empty())
1626 Triple TT(M.getTargetTriple());
1627 if (TT.supportsCOMDAT()) {
1629 ProfileNameVar->
setComdat(M.getOrInsertComdat(
1637 auto GetProfileSum = [IsCS](
const std::string &
Filename,
1643 if (
Error E = ReaderOrErr.takeError()) {
1646 auto Reader = std::move(ReaderOrErr.get());
1647 Reader->accumulateCounts(Sum, IsCS);
1665 for (
unsigned I = 0;
I < IPVK_Last - IPVK_First + 1;
I++) {
1666 if (
Test.ValueCounts[
I] >= 1.0f)
1675 for (
unsigned I = 0;
I < IPVK_Last - IPVK_First + 1;
I++) {
1676 if (
Test.ValueCounts[
I] >= 1.0f)
1685 const char *EntryName =
1688 OS <<
"Profile overlap information for base_profile: " << *
BaseFilename
1689 <<
" and test_profile: " << *
TestFilename <<
"\nProgram level:\n";
1691 OS <<
"Function level:\n"
1695 OS <<
" # of " << EntryName <<
" overlap: " <<
Overlap.NumEntries <<
"\n";
1697 OS <<
" # of " << EntryName <<
" mismatch: " <<
Mismatch.NumEntries
1700 OS <<
" # of " << EntryName
1701 <<
" only in test_profile: " <<
Unique.NumEntries <<
"\n";
1703 OS <<
" Edge profile overlap: " <<
format(
"%.3f%%",
Overlap.CountSum * 100)
1706 OS <<
" Mismatched count percentage (Edge): "
1709 OS <<
" Percentage of Edge profile only in test_profile: "
1711 OS <<
" Edge profile base count sum: " <<
format(
"%.0f",
Base.CountSum)
1713 <<
" Edge profile test count sum: " <<
format(
"%.0f",
Test.CountSum)
1716 for (
unsigned I = 0;
I < IPVK_Last - IPVK_First + 1;
I++) {
1717 if (
Base.ValueCounts[
I] < 1.0f &&
Test.ValueCounts[
I] < 1.0f)
1719 char ProfileKindName[20] = {0};
1721 case IPVK_IndirectCallTarget:
1722 strncpy(ProfileKindName,
"IndirectCall", 19);
1724 case IPVK_MemOPSize:
1725 strncpy(ProfileKindName,
"MemOP", 19);
1727 case IPVK_VTableTarget:
1728 strncpy(ProfileKindName,
"VTable", 19);
1731 snprintf(ProfileKindName, 19,
"VP[%d]",
I);
1734 OS <<
" " << ProfileKindName
1735 <<
" profile overlap: " <<
format(
"%.3f%%",
Overlap.ValueCounts[
I] * 100)
1738 OS <<
" Mismatched count percentage (" << ProfileKindName
1741 OS <<
" Percentage of " << ProfileKindName
1742 <<
" profile only in test_profile: "
1744 OS <<
" " << ProfileKindName
1745 <<
" profile base count sum: " <<
format(
"%.0f",
Base.ValueCounts[
I])
1747 <<
" " << ProfileKindName
1748 <<
" profile test count sum: " <<
format(
"%.0f",
Test.ValueCounts[
I])
1756 static_assert(std::is_standard_layout_v<Header>,
1757 "Use standard layout for Header for simplicity");
1767 if (
H.getIndexedProfileVersion() >
1772 "Please update the reader as needed when a new field is added "
1773 "or when indexed profile version gets bumped.");
1775 Buffer +=
sizeof(uint64_t);
1778 if (
H.getIndexedProfileVersion() >= 8)
1781 if (
H.getIndexedProfileVersion() >= 9)
1785 if (
H.getIndexedProfileVersion() >= 10)
1786 H.TemporalProfTracesOffset =
1788 if (
H.getIndexedProfileVersion() >= 12)
1789 H.VTableNamesOffset =
1805 "Please update the size computation below if a new field has "
1806 "been added to the header; for a version bump without new "
1807 "fields, add a case statement to fall through to the latest version.");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
static cl::opt< bool > StaticFuncFullModulePrefix("static-func-full-module-prefix", cl::init(true), cl::Hidden, cl::desc("Use full module build paths in the profile counter names for " "static functions."))
static cl::opt< unsigned > StaticFuncStripDirNamePrefix("static-func-strip-dirname-prefix", cl::init(0), cl::Hidden, cl::desc("Strip specified level of directory name from source path in " "the profile counter name for static functions."))
static std::string getInstrProfErrString(instrprof_error Err, const std::string &ErrMsg="")
#define INSTR_PROF_QUOTE(x)
#define INSTR_PROF_PROFILE_NAME_VAR
#define INSTR_PROF_RAW_VERSION_VAR
#define VARIANT_MASK_IR_PROF
static constexpr StringLiteral Filename
This file contains the declarations for profiling metadata utility functions.
This file defines the SmallVector class.
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This is an important base class in LLVM.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
LLVM_ABI void setComdat(Comdat *C)
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
void setLinkage(LinkageTypes LT)
Module * getParent()
Get the module that this global value is contained inside of...
@ HiddenVisibility
The GV is hidden.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
std::string message() const override
Return the error message as a string.
static LLVM_ABI Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr, const object::BuildIDFetcher *BIDFetcher=nullptr, std::optional< ProfCorrelatorKind > BIDFetcherCorrelatorKind=std::nullopt, std::function< void(Error)> Warn=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
static LLVM_ABI StringRef getCanonicalName(StringRef PGOName)
Error addSymbolName(StringRef SymbolName)
Error addVTableName(StringRef VTableName)
Adds VTableName as a known symbol, and inserts it to a map that tracks all vtable names.
LLVM_ABI void dumpNames(raw_ostream &OS) const
Dump the symbols in this table.
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
The method name is kept since there are many callers.
LLVM_ABI Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames)
Initialize 'this' with the set of vtable names encoded in CompressedVTableNames.
LLVM_ABI uint64_t getVTableHashFromAddress(uint64_t Address) const
Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
LLVM_ABI uint64_t getFunctionHashFromAddress(uint64_t Address) const
Return a function's hash, or 0, if the function isn't in this SymTab.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
const MDOperand & getOperand(unsigned I) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
A Module instance is used to store all the information related to an LLVM module.
const std::string & getSourceFileName() const
Get the module's original source file name.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
LLVM_ABI uint64_t tell() const
LLVM_ABI void writeByte(uint8_t V)
LLVM_ABI void patch(ArrayRef< PatchItem > P)
LLVM_ABI void write32(uint32_t V)
support::endian::Writer LE
LLVM_ABI ProfOStream(raw_fd_ostream &FD)
LLVM_ABI void write(uint64_t V)
void reserve(size_type N)
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.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
std::string str() const
Get the contents as an std::string.
const unsigned char * bytes_end() const
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
constexpr size_t size() const
Get the string size.
const unsigned char * bytes_begin() const
Triple - Helper class for working with autoconf configuration names.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
This class implements an extremely fast bulk output stream that can only output to a stream.
uint64_t tell() const
tell - Return the current offset with the file.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
static constexpr const char * PartSuffix
static constexpr const char * LLVMSuffix
Name suffixes which canonicalization should handle to avoid profile mismatch.
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
static constexpr const char * CfiSuffix
initializer< Ty > init(const Ty &Val)
LLVM_ABI void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
constexpr int BestSizeCompression
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
value_type byte_swap(value_type value, endianness endian)
Swap the bytes of value to match the given endianness.
value_type readNext(const CharT *&memory, endianness endian)
Read a value of a particular endianness from a buffer, and increment the buffer past that value.
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
void swapByteOrder(T &Value)
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.
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
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.
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
LLVM_ABI cl::opt< bool > DoInstrProfNameCompression
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
INSTR_PROF_VISIBILITY ValueProfRecord * getValueProfRecordNext(ValueProfRecord *VPR)
Use this method to advance to the next This ValueProfRecord.
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
LLVM_ABI std::pair< StringRef, StringRef > getParsedIRPGOName(StringRef IRPGOName)
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr UniformCountersBegin(uintptr_t) UniformCountersBegin -(uintptr_t) DataBegin struct llvm::ValueProfData ValueProfData
This is the header of the data structure that defines the on-disk layout of the value profile data of...
MDNode * mayHaveValueProfileOfKind(const Instruction &Inst, InstrProfValueKind ValueKind)
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
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."))
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
auto dyn_cast_or_null(const Y &Val)
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...
INSTR_PROF_VISIBILITY uint32_t getValueProfDataSize(ValueProfRecordClosure *Closure)
Return the total size in bytes of the on-disk value profile data given the data stored in Record.
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI Error readAndDecodeStrings(StringRef NameStrings, std::function< Error(StringRef)> NameCallback)
NameStrings is a string composed of one or more possibly encoded sub-strings.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
INSTR_PROF_VISIBILITY ValueProfRecord * getFirstValueProfRecord(ValueProfData *VPD)
Return the first ValueProfRecord instance.
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
INSTR_PROF_VISIBILITY ValueProfData * serializeValueProfDataFrom(ValueProfRecordClosure *Closure, ValueProfData *DstData)
Extract value profile data of a function from the Closure and serialize the data into DstData if it i...
INSTR_PROF_VISIBILITY InstrProfValueData * getValueProfRecordValueData(ValueProfRecord *VPR)
Return the pointer to the start of value data array.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
@ unable_to_correlate_profile
@ raw_profile_version_mismatch
@ counter_value_too_large
@ missing_correlation_info
@ value_site_count_mismatch
@ coverage_count_mismatch
@ unexpected_correlation_info
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
LLVM_ABI const std::error_category & instrprof_category()
LLVM_ABI Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
static StringRef getStrippedSourceFileName(const GlobalObject &GO)
ArrayRef(const T &OneElt) -> ArrayRef< T >
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
OutputIt copy(R &&Range, OutputIt Out)
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)
constexpr char GlobalIdentifierDelimiter
LLVM_ABI Error collectGlobalObjectNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (names of global objects like functions or, virtual tables) NameStrs,...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
void setPGOFuncVisibility(Module &M, GlobalVariable *FuncNameVar)
INSTR_PROF_VISIBILITY INSTR_PROF_INLINE uint32_t getValueProfRecordNumValueData(ValueProfRecord *This)
Return the total number of value data for This record.
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
static ValueProfRecordClosure InstrProfRecordClosure
LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
static void mergeUniformityBits(std::vector< uint8_t > &Dst, ArrayRef< uint8_t > Src)
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
LLVM_ABI bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
void consumeError(Error Err)
Consume a Error without doing anything.
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
static std::string getIRPGONameForGlobalObject(const GlobalObject &GO, GlobalValue::LinkageTypes Linkage, StringRef FileName)
uint64_t decodeULEB128(const uint8_t *p, unsigned *n, const uint8_t *end, const char **error, ULEB128DecodeError *errorCode)
Utility function to decode a ULEB128 value and report a typed error.
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."))
std::array< double, IPVK_Last - IPVK_First+1 > ValueCounts
Profiling information for a single function.
LLVM_ABI void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
InstrProfRecord()=default
std::vector< uint64_t > Counts
ArrayRef< InstrProfValueData > getValueArrayForSite(uint32_t ValueKind, uint32_t Site) const
Return the array of profiled values at Site.
uint16_t OffloadDeviceWaveSize
CountPseudoKind getCountPseudoKind() const
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
std::vector< uint64_t > UniformCounts
For AMDGPU offload profiling: raw or merged uniform counters.
void setPseudoCount(CountPseudoKind Kind)
LLVM_ABI void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site, ArrayRef< InstrProfValueData > VData, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
std::vector< uint8_t > UniformityBits
For AMDGPU offload profiling: 1 bit per basic block indicating whether the block is usually entered w...
LLVM_ABI void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
std::vector< uint8_t > BitmapBytes
LLVM_ABI void computeBlockUniformity()
Recompute uniformity metadata from raw uniform counters, when present.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by a factor of (N / D).
InstrProfValueSiteRecord()=default
void sortByTargetValues()
Sort ValueData ascending by Value.
std::vector< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
LLVM_ABI void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
LLVM_ABI void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts by N (Numerator) / D (Denominator).
static LLVM_ABI const char * ValueProfile
LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc)
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
LLVM_ABI Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
LLVM_ABI void dump(raw_fd_ostream &OS) const
CountSumOrPercent Overlap
LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc)
const std::string * BaseFilename
const std::string * TestFilename
CountSumOrPercent Mismatch
static LLVM_ABI void createBPFunctionNodes(ArrayRef< TemporalProfTraceTy > Traces, std::vector< BPFunctionNode > &Nodes, bool RemoveOutlierUNs=true)
Use a set of temporal profile traces to create a list of balanced partitioning function nodes used by...
This is the header of the data structure that defines the on-disk layout of the value profile data of...