52 #include <system_error> 60 cl::desc(
"Use full module build paths in the profile counter names for " 61 "static functions."));
73 cl::desc(
"Strip specified level of directory name from source path in " 74 "the profile counter name for static functions."));
83 return "Unrecognized instrumentation profile encoding format";
85 return "Invalid instrumentation profile data (bad magic)";
87 return "Invalid instrumentation profile data (file header is corrupt)";
89 return "Unsupported instrumentation profile format version";
91 return "Unsupported instrumentation profile hash type";
93 return "Too much profile data";
95 return "Truncated profile data";
97 return "Malformed instrumentation profile data";
99 return "No profile data available for function";
101 return "Function control flow change detected (hash mismatch)";
103 return "Function basic block count change detected (counter mismatch)";
105 return "Counter overflow";
107 return "Function value site count change detected (counter mismatch)";
109 return "Failed to compress data (zlib)";
111 return "Failed to uncompress data (zlib)";
113 return "Empty raw profile file";
115 return "Profile uses zlib compression but the profile reader was built without zlib support";
126 const char *
name()
const noexcept
override {
return "llvm.instrprof"; }
128 std::string message(
int IE)
const override {
143 const char *InstrProfSectNameCommon[] = {
144 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \ 149 const char *InstrProfSectNameCoff[] = {
150 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \ 155 const char *InstrProfSectNamePrefix[] = {
156 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \ 167 bool AddSegmentInfo) {
168 std::string SectName;
171 SectName = InstrProfSectNamePrefix[IPSK];
174 SectName += InstrProfSectNameCoff[IPSK];
176 SectName += InstrProfSectNameCommon[IPSK];
178 if (OF ==
Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
179 SectName +=
",regular,live_support";
196 ++NumCountMismatches;
199 ++NumCounterOverflows;
202 ++NumValueSiteCountMismatches;
228 for (
auto & CI : PathNameStr) {
237 return PathNameStr.substr(LastPos);
266 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
277 if (FileName.
empty())
296 const char *InvalidChars =
"-:<>/\"'";
297 size_t found = VarName.find_first_of(InvalidChars);
298 while (found != std::string::npos) {
299 VarName[found] =
'_';
300 found = VarName.find_first_of(InvalidChars, found + 1);
343 if (
Error E = addFuncName(PGOFuncName))
350 auto pos = PGOFuncName.find(
'.');
351 if (pos != std::string::npos) {
352 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
353 if (
Error E = addFuncName(OtherFuncName))
366 auto It =
partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
373 if (It != AddrToMD5Map.end() && It->first ==
Address)
374 return (uint64_t)It->second;
379 bool doCompression, std::string &Result) {
380 assert(!NameStrs.
empty() &&
"No name data to emit");
382 uint8_t Header[16], *
P = Header;
383 std::string UncompressedNameStrings =
388 "PGO name is invalid (contains separator token)");
390 unsigned EncLen =
encodeULEB128(UncompressedNameStrings.length(),
P);
393 auto WriteStringToResult = [&](
size_t CompressedLen,
StringRef InputStr) {
396 char *HeaderStr =
reinterpret_cast<char *
>(&Header[0]);
397 unsigned HeaderLen = P - &Header[0];
398 Result.append(HeaderStr, HeaderLen);
403 if (!doCompression) {
404 return WriteStringToResult(0, UncompressedNameStrings);
415 return WriteStringToResult(CompressedNameStrings.
size(),
416 CompressedNameStrings);
422 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
427 std::string &Result,
bool doCompression) {
428 std::vector<std::string> NameStrs;
429 for (
auto *NameVar : NameVars) {
438 const uint8_t *EndP = NameStrings.
bytes_end();
445 bool isCompressed = (CompressedSize != 0);
452 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
462 UncompressedNameStrings.
size());
465 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
466 P += UncompressedSize;
475 while (P < EndP && *P == 0)
482 uint64_t FuncSum = 0;
484 for (
size_t F = 0,
E = Counts.size();
F <
E; ++
F)
485 FuncSum += Counts[
F];
488 for (
uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
489 uint64_t KindSum = 0;
490 uint32_t NumValueSites = getNumValueSites(VK);
491 for (
size_t I = 0;
I < NumValueSites; ++
I) {
493 std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK,
I);
495 KindSum += VD[V].Count;
505 this->sortByTargetValues();
507 double Score = 0.0f, FuncLevelScore = 0.0f;
508 auto I = ValueData.begin();
509 auto IE = ValueData.end();
512 while (
I !=
IE && J != JE) {
513 if (
I->Value == J->Value) {
521 }
else if (
I->Value < J->Value) {
536 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
538 if (!ThisNumValueSites)
541 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
542 getOrCreateValueSitesForKind(ValueKind);
544 Other.getValueSitesForKind(ValueKind);
546 ThisSiteRecords[
I].overlap(OtherSiteRecords[
I], ValueKind, Overlap,
552 uint64_t ValueCutoff) {
555 accumulateCounts(FuncLevelOverlap.
Base);
556 bool Mismatch = (Counts.size() != Other.
Counts.size());
563 if (ThisNumValueSites != OtherNumValueSites) {
576 overlapValueProfData(
Kind, Other, Overlap, FuncLevelOverlap);
579 uint64_t MaxCount = 0;
581 for (
size_t I = 0,
E = Other.
Counts.size();
I <
E; ++
I) {
589 if (MaxCount >= ValueCutoff) {
590 double FuncScore = 0.0;
591 for (
size_t I = 0, E = Other.
Counts.size();
I <
E; ++
I)
597 FuncLevelOverlap.
Valid =
true;
604 this->sortByTargetValues();
606 auto I = ValueData.begin();
607 auto IE = ValueData.end();
610 while (
I !=
IE &&
I->Value < J->Value)
612 if (
I !=
IE &&
I->Value == J->Value) {
620 ValueData.insert(
I, *J);
626 for (
auto I = ValueData.begin(),
IE = ValueData.end();
I !=
IE; ++
I) {
636 void InstrProfRecord::mergeValueProfData(
639 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
641 if (ThisNumValueSites != OtherNumValueSites) {
645 if (!ThisNumValueSites)
647 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
648 getOrCreateValueSitesForKind(ValueKind);
650 Src.getValueSitesForKind(ValueKind);
652 ThisSiteRecords[
I].merge(OtherSiteRecords[
I], Weight, Warn);
659 if (Counts.size() != Other.
Counts.size()) {
664 for (
size_t I = 0,
E = Other.
Counts.size();
I <
E; ++
I) {
673 mergeValueProfData(
Kind, Other, Weight, Warn);
676 void InstrProfRecord::scaleValueProfData(
677 uint32_t ValueKind, uint64_t Weight,
679 for (
auto &R : getValueSitesForKind(ValueKind))
680 R.scale(Weight, Warn);
685 for (
auto &Count : this->Counts) {
692 scaleValueProfData(
Kind, Weight, Warn);
696 uint64_t InstrProfRecord::remapValue(uint64_t
Value,
uint32_t ValueKind,
701 if (ValueKind == IPVK_IndirectCallTarget)
711 VData[
I].Value = remapValue(VData[
I].Value, ValueKind, ValueMap);
713 std::vector<InstrProfValueSiteRecord> &ValueSites =
714 getOrCreateValueSitesForKind(ValueKind);
716 ValueSites.emplace_back();
718 ValueSites.emplace_back(VData, VData + N);
721 #define INSTR_PROF_COMMON_API_IMPL 730 return reinterpret_cast<const InstrProfRecord *
>(Record)->getNumValueKinds();
735 ->getNumValueSites(VKind);
740 ->getNumValueData(VKind);
746 ->getNumValueDataForSite(VK, S);
751 reinterpret_cast<const InstrProfRecord *
>(R)->getValueForSite(Dst, K, S);
756 (ValueProfData *)(
new (::
operator new(TotalSizeInBytes)) ValueProfData());
757 memset(VD, 0, TotalSizeInBytes);
774 Closure.Record = &Record;
775 return getValueProfDataSize(&Closure);
779 std::unique_ptr<ValueProfData>
781 InstrProfRecordClosure.Record = &Record;
783 std::unique_ptr<ValueProfData> VPD(
784 serializeValueProfDataFrom(&InstrProfRecordClosure,
nullptr));
792 InstrProfValueData *ValueData = getValueProfRecordValueData(
this);
793 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
794 uint8_t ValueDataCount = this->SiteCountArray[VSite];
796 ValueData += ValueDataCount;
805 using namespace support;
811 sys::swapByteOrder<uint32_t>(NumValueSites);
812 sys::swapByteOrder<uint32_t>(
Kind);
814 uint32_t ND = getValueProfRecordNumValueData(
this);
815 InstrProfValueData *VD = getValueProfRecordValueData(
this);
819 sys::swapByteOrder<uint64_t>(VD[
I].Value);
820 sys::swapByteOrder<uint64_t>(VD[
I].Count);
823 sys::swapByteOrder<uint32_t>(NumValueSites);
824 sys::swapByteOrder<uint32_t>(
Kind);
830 if (NumValueKinds == 0)
833 ValueProfRecord *VR = getFirstValueProfRecord(
this);
834 for (
uint32_t K = 0; K < NumValueKinds; K++) {
835 VR->deserializeTo(Record, SymTab);
836 VR = getValueProfRecordNext(VR);
842 using namespace support;
845 return endian::readNext<T, little, unaligned>(
D);
847 return endian::readNext<T, big, unaligned>(
D);
851 return std::unique_ptr<ValueProfData>(
new (::operator
new(TotalSize))
855 Error ValueProfData::checkIntegrity() {
856 if (NumValueKinds > IPVK_Last + 1)
859 if (TotalSize %
sizeof(uint64_t))
862 ValueProfRecord *VR = getFirstValueProfRecord(
this);
863 for (
uint32_t K = 0; K < this->NumValueKinds; K++) {
864 if (VR->Kind > IPVK_Last)
866 VR = getValueProfRecordNext(VR);
867 if ((
char *)VR - (
char *)
this > (
ptrdiff_t)TotalSize)
874 ValueProfData::getValueProfData(
const unsigned char *
D,
875 const unsigned char *
const BufferEnd,
877 using namespace support;
879 if (D +
sizeof(ValueProfData) > BufferEnd)
882 const unsigned char *Header =
D;
884 if (D + TotalSize > BufferEnd)
888 memcpy(VPD.get(),
D, TotalSize);
890 VPD->swapBytesToHost(Endianness);
892 Error E = VPD->checkIntegrity();
896 return std::move(VPD);
900 using namespace support;
905 sys::swapByteOrder<uint32_t>(TotalSize);
906 sys::swapByteOrder<uint32_t>(NumValueKinds);
908 ValueProfRecord *VR = getFirstValueProfRecord(
this);
909 for (
uint32_t K = 0; K < NumValueKinds; K++) {
911 VR = getValueProfRecordNext(VR);
916 using namespace support;
921 ValueProfRecord *VR = getFirstValueProfRecord(
this);
922 for (
uint32_t K = 0; K < NumValueKinds; K++) {
923 ValueProfRecord *NVR = getValueProfRecordNext(VR);
927 sys::swapByteOrder<uint32_t>(TotalSize);
928 sys::swapByteOrder<uint32_t>(NumValueKinds);
940 std::unique_ptr<InstrProfValueData[]> VD =
965 for (
auto &VD : VDs) {
979 InstrProfValueData ValueData[],
980 uint32_t &ActualNumValueData, uint64_t &TotalC) {
1011 ActualNumValueData = 0;
1013 for (
unsigned I = 3;
I < NOps;
I += 2) {
1014 if (ActualNumValueData >= MaxNumValueData)
1018 mdconst::dyn_extract<ConstantInt>(MD->
getOperand(
I + 1));
1019 if (!Value || !Count)
1022 ValueData[ActualNumValueData].Count = Count->getZExtValue();
1023 ActualNumValueData++;
1034 if (PGOFuncName == F.
getName())
1073 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
1074 IRInstrVar->hasLocalLinkage())
1078 if (!IRInstrVar->hasInitializer())
1081 auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
1084 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1112 int64_t &RangeLast) {
1113 static const int64_t DefaultMemOPSizeRangeStart = 0;
1114 static const int64_t DefaultMemOPSizeRangeLast = 8;
1115 RangeStart = DefaultMemOPSizeRangeStart;
1116 RangeLast = DefaultMemOPSizeRangeLast;
1118 if (!MemOPSizeRange.
empty()) {
1119 auto Pos = MemOPSizeRange.
find(
':');
1120 if (Pos != std::string::npos) {
1123 if (Pos < MemOPSizeRange.
size() - 1)
1128 assert(RangeLast >= RangeStart);
1136 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1138 ProfileVersion |= VARIANT_MASK_CSIR_PROF;
1144 if (
TT.supportsCOMDAT()) {
1152 if (InstrProfileOutput.
empty())
1158 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1160 if (
TT.supportsCOMDAT()) {
1163 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1168 const std::string &TestFilename,
1170 auto getProfileSum = [IsCS](
const std::string &Filename,
1173 if (
Error E = ReaderOrErr.takeError()) {
1176 auto Reader = std::move(ReaderOrErr.get());
1177 Reader->accumulateCounts(Sum, IsCS);
1180 auto Ret = getProfileSum(BaseFilename,
Base);
1183 Ret = getProfileSum(TestFilename,
Test);
1186 this->BaseFilename = &BaseFilename;
1187 this->TestFilename = &TestFilename;
1193 Mismatch.NumEntries += 1;
1194 Mismatch.CountSum += MismatchFunc.
CountSum /
Test.CountSum;
1195 for (
unsigned I = 0;
I < IPVK_Last - IPVK_First + 1;
I++) {
1196 if (
Test.ValueCounts[
I] >= 1.0f)
1197 Mismatch.ValueCounts[
I] +=
1203 Unique.NumEntries += 1;
1204 Unique.CountSum += UniqueFunc.
CountSum /
Test.CountSum;
1205 for (
unsigned I = 0;
I < IPVK_Last - IPVK_First + 1;
I++) {
1206 if (
Test.ValueCounts[
I] >= 1.0f)
1215 const char *EntryName =
1216 (
Level == ProgramLevel ?
"functions" :
"edge counters");
1217 if (
Level == ProgramLevel) {
1218 OS <<
"Profile overlap infomation for base_profile: " << *BaseFilename
1219 <<
" and test_profile: " << *TestFilename <<
"\nProgram level:\n";
1221 OS <<
"Function level:\n" 1222 <<
" Function: " << FuncName <<
" (Hash=" << FuncHash <<
")\n";
1225 OS <<
" # of " << EntryName <<
" overlap: " << Overlap.NumEntries <<
"\n";
1226 if (Mismatch.NumEntries)
1227 OS <<
" # of " << EntryName <<
" mismatch: " << Mismatch.NumEntries
1229 if (Unique.NumEntries)
1230 OS <<
" # of " << EntryName
1231 <<
" only in test_profile: " << Unique.NumEntries <<
"\n";
1233 OS <<
" Edge profile overlap: " <<
format(
"%.3f%%", Overlap.CountSum * 100)
1235 if (Mismatch.NumEntries)
1236 OS <<
" Mismatched count percentage (Edge): " 1237 <<
format(
"%.3f%%", Mismatch.CountSum * 100) <<
"\n";
1238 if (Unique.NumEntries)
1239 OS <<
" Percentage of Edge profile only in test_profile: " 1240 <<
format(
"%.3f%%", Unique.CountSum * 100) <<
"\n";
1241 OS <<
" Edge profile base count sum: " <<
format(
"%.0f",
Base.CountSum)
1243 <<
" Edge profile test count sum: " <<
format(
"%.0f",
Test.CountSum)
1246 for (
unsigned I = 0;
I < IPVK_Last - IPVK_First + 1;
I++) {
1247 if (
Base.ValueCounts[
I] < 1.0f &&
Test.ValueCounts[
I] < 1.0f)
1249 char ProfileKindName[20];
1251 case IPVK_IndirectCallTarget:
1252 strncpy(ProfileKindName,
"IndirectCall", 19);
1254 case IPVK_MemOPSize:
1255 strncpy(ProfileKindName,
"MemOP", 19);
1258 snprintf(ProfileKindName, 19,
"VP[%d]",
I);
1261 OS <<
" " << ProfileKindName
1262 <<
" profile overlap: " <<
format(
"%.3f%%", Overlap.ValueCounts[
I] * 100)
1264 if (Mismatch.NumEntries)
1265 OS <<
" Mismatched count percentage (" << ProfileKindName
1266 <<
"): " <<
format(
"%.3f%%", Mismatch.ValueCounts[
I] * 100) <<
"\n";
1267 if (Unique.NumEntries)
1268 OS <<
" Percentage of " << ProfileKindName
1269 <<
" profile only in test_profile: " 1270 <<
format(
"%.3f%%", Unique.ValueCounts[
I] * 100) <<
"\n";
1271 OS <<
" " << ProfileKindName
1272 <<
" profile base count sum: " <<
format(
"%.0f",
Base.ValueCounts[
I])
1274 <<
" " << ProfileKindName
1275 <<
" profile test count sum: " <<
format(
"%.0f",
Test.ValueCounts[
I])
void setVisibility(VisibilityTypes V)
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
cl::opt< std::string > MemOPSizeRange("memop-size-range", cl::desc("Set the range of size in memory intrinsic calls to be profiled " "precisely, in a format of <start_val>:<end_val>"), cl::init(""))
void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
void addOneMismatch(const CountSumOrPercent &MismatchFunc)
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
DiagnosticInfoOptimizationBase::Argument NV
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
const unsigned char * bytes_end() const
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
static MDString * get(LLVMContext &Context, StringRef Str)
uint32_t getNumValueDataForSite(uint32_t ValueKind, uint32_t Site) const
Return the number of value data collected for ValueKind at profiling site: Site.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Available for inspection, not emission.
void push_back(const T &Elt)
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
An efficient, type-erasing, non-owning reference to a callable.
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Like Internal, but omit from symbol table.
Externally visible function.
constexpr support::endianness Endianness
The endianness of all multi-byte encoded values in MessagePack.
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
static T swapToHostOrder(const unsigned char *&D, support::endianness Orig)
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
const MDOperand & getOperand(unsigned I) const
static IntegerType * getInt64Ty(LLVMContext &C)
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
static bool isLocalLinkage(LinkageTypes Linkage)
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight...
Error compress(StringRef InputBuffer, SmallVectorImpl< char > &CompressedBuffer, int Level=DefaultCompression)
static Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path)
Factory method to create an appropriately typed reader for the given instrprof file.
void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
LLVMContext & getContext() const
Get the global data context.
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by Weight.
const std::error_category & instrprof_category()
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Error collectPGOFuncNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (function PGO names) NameStrs, the method generates a combined string Resul...
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
Tagged union holding either a T or a Error.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
auto partition_point(R &&Range, Predicate P) -> decltype(adl_begin(Range))
Binary search for the first iterator in a range where a predicate is false.
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
Type * getType() const
All values are typed, get the type of this value.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
LLVM_NODISCARD size_t size() const
size - Get the string size.
void addError(instrprof_error IE)
Track a soft error (IE) and increment its associated counter.
LinkageTypes getLinkage() const
static constexpr int BestSizeCompression
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
const std::string & getSourceFileName() const
Get the module's original source file name.
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
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 ManagedStatic< InstrProfErrorCategoryType > ErrorCategory
std::string message() const override
Return the error message as a string.
StringRef getString() const
ExternalWeak linkage description.
uint64_t getFunctionHashFromAddress(uint64_t Address)
Return a function's hash, or 0, if the function isn't in this SymTab.
void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart, int64_t &RangeLast)
Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Same, but only replaced by something equivalent.
initializer< Ty > init(const Ty &Val)
bool getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, InstrProfValueData ValueData[], uint32_t &ActualNumValueData, uint64_t &TotalC)
Extract the value profile data from Inst which is annotated with value profile meta data...
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts.
std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static ValueProfRecordClosure InstrProfRecordClosure
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
static ManagedStatic< _object_error_category > error_category
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
#define LLVM_ATTRIBUTE_UNUSED
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
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...
Value(Type *Ty, unsigned scid)
void consumeError(Error Err)
Consume a Error without doing anything.
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab)
NameStrings is a string composed of one of more sub-strings encoded in the format described above...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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 isDiscardableIfUnused() const
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
std::enable_if< std::is_unsigned< T >::value, T >::type 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.
void addOneUnique(const CountSumOrPercent &UniqueFunc)
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
static ErrorSuccess success()
Create a success value.
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Keep one copy of function when linking (inline)
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
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)
StringRef getPGOFuncNameMetadataName()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Class for arbitrary precision integers.
LinkageTypes
An enumeration for the kinds of linkage for global values.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
CountSumOrPercent Overlap
void sortByTargetValues()
Sort ValueData ascending by Value.
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
std::vector< uint64_t > Counts
void dump(raw_fd_ostream &OS) const
const unsigned char * bytes_begin() const
A raw_ostream that writes to a file descriptor.
pointer data()
Return a pointer to the vector's buffer, even if empty().
Profiling information for a single function.
static IntegerType * getInt32Ty(LLVMContext &C)
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.
Linkage
Describes symbol linkage.
MDString * createString(StringRef Str)
Return the given string as metadata.
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
StringRef getName() const
Return a constant reference to the value's name.
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void createIRLevelProfileFlagVar(Module &M, bool IsCS)
Lightweight error class with error context and mandatory checking.
support::endianness getHostEndianness()
StringRef - Represent a constant reference to a string, i.e.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
std::unique_ptr< InstrProfValueData[]> getValueForSite(uint32_t ValueKind, uint32_t Site, uint64_t *TotalC=nullptr) const
Return the array of profiled values at Site.
unsigned getNumOperands() const
Return number of MDNode operands.
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
Error uncompress(StringRef InputBuffer, char *UncompressedBuffer, size_t &UncompressedSize)
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
double ValueCounts[IPVK_Last - IPVK_First+1]
bool empty() const
empty - Check if the array is empty.