15 #ifndef LLVM_PROFILEDATA_INSTRPROF_H 16 #define LLVM_PROFILEDATA_INSTRPROF_H 42 #include <system_error> 50 struct InstrProfRecord;
51 class InstrProfSymtab;
57 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind, 68 bool AddSegmentInfo =
true);
73 return INSTR_PROF_VALUE_PROF_FUNC_STR;
78 return INSTR_PROF_VALUE_RANGE_PROF_FUNC_STR;
99 return "__llvm_prf_nm";
106 return "__llvm_coverage_mapping";
114 return "__llvm_coverage_names";
123 return "__llvm_profile_register_functions";
129 return "__llvm_profile_register_function";
134 return "__llvm_profile_register_names_function";
147 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
153 return "__llvm_profile_runtime_user";
163 uint64_t
Version = INSTR_PROF_INDEX_VERSION);
172 uint64_t
Version = INSTR_PROF_INDEX_VERSION);
211 bool doCompression, std::string &Result);
216 std::string &Result,
bool doCompression =
true);
233 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value, 241 const InstrProfRecord &InstrProfR,
247 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
256 InstrProfValueData ValueData[],
257 uint32_t &ActualNumValueData, uint64_t &TotalC);
307 std::string message()
const override;
342 unsigned NumHashMismatches = 0;
345 unsigned NumCountMismatches = 0;
348 unsigned NumCounterOverflows = 0;
351 unsigned NumValueSiteCountMismatches = 0;
358 "Unchecked soft error encountered");
375 return NumValueSiteCountMismatches;
383 auto E = make_error<InstrProfError>(FirstError);
395 namespace IndexedInstrProf {
416 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
419 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
426 return "** External Symbol **";
433 inline void finalizeSymtab();
463 template <
typename NameIterRange>
Error create(
const NameIterRange &IterRange);
468 if (FuncName.
empty())
472 MD5NameMap.push_back(std::make_pair(
482 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
486 uint64_t getFunctionHashFromAddress(uint64_t Address);
495 inline StringRef getFuncName(uint64_t FuncMD5Hash);
500 inline StringRef getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash);
504 return Symbol == InstrProfSymtab::getExternalSymbol();
513 inline StringRef getOrigFuncName(uint64_t FuncMD5Hash);
529 template <
typename NameIterRange>
531 for (
auto Name : IterRange)
539 void InstrProfSymtab::finalizeSymtab() {
545 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
551 StringRef ret = getFuncName(FuncMD5Hash);
553 return InstrProfSymtab::getExternalSymbol();
561 [](
const std::pair<uint64_t, std::string> &LHS,
562 uint64_t RHS) {
return LHS.first < RHS; });
563 if (Result != MD5NameMap.end() && Result->first == FuncMD5Hash)
564 return Result->second;
572 [](
const std::pair<uint64_t, Function*> &LHS,
573 uint64_t RHS) {
return LHS.first < RHS; });
574 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
575 return Result->second;
582 StringRef PGOName = getFuncName(FuncMD5Hash);
594 double ValueCounts[IPVK_Last - IPVK_First + 1];
599 for (
unsigned I = 0;
I < IPVK_Last - IPVK_First + 1;
I++)
600 ValueCounts[
I] = 0.0f;
623 : Level(L), BaseFilename(nullptr), TestFilename(nullptr), FuncHash(0),
633 Error accumulateCounts(
const std::string &BaseFilename,
634 const std::string &TestFilename,
bool IsCS);
638 static inline double score(uint64_t Val1, uint64_t Val2,
double Sum1,
640 if (Sum1 < 1.0f || Sum2 < 1.0f)
642 return std::min(Val1 / Sum1, Val2 / Sum2);
658 template <
class InputIterator>
665 [](
const InstrProfValueData &left,
const InstrProfValueData &right) {
666 return left.Value < right.Value;
670 inline void sortByCount();
692 : Counts(RHS.Counts),
693 ValueData(RHS.ValueData
694 ?
std::make_unique<ValueProfData>(*RHS.ValueData)
699 if (!RHS.ValueData) {
704 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
706 *ValueData = *RHS.ValueData;
712 inline uint32_t getNumValueKinds()
const;
727 inline std::unique_ptr<InstrProfValueData[]>
729 uint64_t *TotalC =
nullptr)
const;
734 inline uint64_t getValueForSite(InstrProfValueData Dest[],
uint32_t ValueKind,
757 for (
auto &SR : getValueSitesForKind(
Kind))
783 struct ValueProfData {
784 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
785 std::vector<InstrProfValueSiteRecord> MemOPSizes;
787 std::unique_ptr<ValueProfData> ValueData;
790 getValueSitesForKind(
uint32_t ValueKind) {
794 auto AR =
const_cast<const InstrProfRecord *
>(
this)->getValueSitesForKind(
797 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
800 getValueSitesForKind(
uint32_t ValueKind)
const {
804 case IPVK_IndirectCallTarget:
805 return ValueData->IndirectCallSites;
807 return ValueData->MemOPSizes;
813 std::vector<InstrProfValueSiteRecord> &
814 getOrCreateValueSitesForKind(
uint32_t ValueKind) {
816 ValueData = std::make_unique<ValueProfData>();
818 case IPVK_IndirectCallTarget:
819 return ValueData->IndirectCallSites;
821 return ValueData->MemOPSizes;
838 void scaleValueProfData(
uint32_t ValueKind, uint64_t Weight,
847 static const int CS_FLAG_IN_FUNC_HASH = 60;
851 std::vector<uint64_t> Counts)
855 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
858 FuncHash |= ((uint64_t)1 << CS_FLAG_IN_FUNC_HASH);
865 NumValueKinds += !(getValueSitesForKind(
Kind).
empty());
866 return NumValueKinds;
871 for (
auto &SR : getValueSitesForKind(ValueKind))
872 N += SR.ValueData.size();
877 return getValueSitesForKind(ValueKind).size();
882 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
885 std::unique_ptr<InstrProfValueData[]>
887 uint64_t *TotalC)
const {
889 uint64_t &TotalCount = (TotalC ==
nullptr ?
Dummy : *TotalC);
890 uint32_t N = getNumValueDataForSite(ValueKind, Site);
893 return std::unique_ptr<InstrProfValueData[]>(
nullptr);
896 auto VD = std::make_unique<InstrProfValueData[]>(
N);
897 TotalCount = getValueForSite(VD.get(),
ValueKind, Site);
906 uint64_t TotalCount = 0;
907 for (
auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
908 Dest[
I].Value = V.Value;
909 Dest[
I].Count = V.Count;
919 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
927 #define INSTR_PROF_VALUE_PROF_DATA 932 [](
const InstrProfValueData &left,
const InstrProfValueData &right) {
933 return left.Count > right.Count;
936 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
937 if (ValueData.size() > max_s)
938 ValueData.resize(max_s);
941 namespace IndexedInstrProf {
956 const uint64_t
Magic = 0x8169666f72706cff;
1011 TotalNumFunctions = 0,
1017 MaxFunctionCount = 2,
1021 MaxInternalBlockCount = 4,
1023 TotalBlockCount = 5,
1024 NumKinds = TotalBlockCount + 1
1035 void operator delete(
void *ptr) { ::operator
delete(ptr); }
1038 return sizeof(
Summary) + NumCutoffEntries *
sizeof(
Entry) +
1039 NumSumFields *
sizeof(uint64_t);
1043 return reinterpret_cast<const uint64_t *
>(
this + 1);
1047 return reinterpret_cast<uint64_t *
>(
this + 1);
1051 return reinterpret_cast<const Entry *
>(
1052 &getSummaryDataBase()[NumSummaryFields]);
1056 return reinterpret_cast<Entry *
>(&getSummaryDataBase()[NumSummaryFields]);
1060 return getSummaryDataBase()[K];
1064 getSummaryDataBase()[K] = V;
1070 Entry &ER = getCutoffEntryBase()[
I];
1078 return std::unique_ptr<Summary>(
new (::operator
new(TotalSize))
1084 namespace RawInstrProf {
1097 template <
class IntPtrT>
inline uint64_t
getMagic();
1099 return INSTR_PROF_RAW_MAGIC_64;
1103 return INSTR_PROF_RAW_MAGIC_32;
1112 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name; 1121 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name; 1129 int64_t &RangeLast);
1139 #endif // LLVM_PROFILEDATA_INSTRPROF_H auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
void log(raw_ostream &OS) const override
Print an error message to an output stream.
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable...
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
uint64_t NumCutoffEntries
void sortByCount()
Sort ValueData Descending by Count.
uint32_t Cutoff
The required percentile of counts.
MutableArrayRef< T > makeMutableArrayRef(T &OneElt)
Construct a MutableArrayRef from a single element.
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
void sortValueData()
Sort value profile data (per site) by count.
This class represents lattice values for constants.
uint64_t MinBlockCount
The minimum execution count for this percentile.
StringRef getOrigFuncName(uint64_t FuncMD5Hash)
Return the function's original assembly name by stripping off the prefix attached (to symbols with pr...
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
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
const std::string * BaseFilename
uint32_t getNumValueDataForSite(uint32_t ValueKind, uint32_t Site) const
Return the number of value data collected for ValueKind at profiling site: Site.
void setEntry(uint32_t I, const ProfileSummaryEntry &E)
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
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.
uint64_t MD5Hash(StringRef Str)
Helper to compute and return lower 64 bits of the given string's MD5 hash.
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Function * getFunction(uint64_t FuncMD5Hash)
Return function from the name's md5 hash. Return nullptr if not found.
uint64_t getMagic< uint64_t >()
const std::string NameFilter
An efficient, type-erasing, non-owning reference to a callable.
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts)
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
uint32_t getNumValueData(uint32_t ValueKind) const
Return the total number of ValueData for ValueKind.
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
InstrProfValueSiteRecord()
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
uint64_t * getSummaryDataBase()
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
unsigned getNumValueSiteCountMismatches() const
Get the number of value site count mismatches.
const Entry & getEntry(uint32_t I) const
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
const std::error_category & instrprof_category()
std::error_code make_error_code(BitcodeError E)
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...
uint64_t ComputeHash(HashT Type, StringRef K)
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
uint64_t NumSummaryFields
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
const std::string * TestFilename
static const bool IsLittleEndianHost
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize)
Return function's PGO name from the function name's symbol address in the object file.
Entry * getCutoffEntryBase()
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.
static Function * getFunction(Constant *C)
InstrProfRecord(const InstrProfRecord &RHS)
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
instrprof_error get() const
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
unsigned getNumCountMismatches() const
Get the number of count mismatches.
uint64_t getMagic< uint32_t >()
void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart, int64_t &RangeLast)
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
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...
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
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)
uint64_t Cutoff
The required percentile of total execution count.
The instances of the Type class are immutable: once they are created, they are never changed...
const uint64_t * getSummaryDataBase() const
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
unsigned getNumCounterOverflows() const
Get the number of counter overflows.
static ManagedStatic< _object_error_category > error_category
uint32_t getNumValueKinds() const
Return the number of value profile kinds with non-zero number of profile sites.
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
static uint64_t scale(uint64_t Num, uint32_t N, uint32_t D)
static bool hasCSFlagInHash(uint64_t FuncHash)
uint64_t ComputeHash(StringRef K)
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...
const Entry * getCutoffEntryBase() const
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab)
NameStrings is a string composed of one of more sub-strings encoded in the format described above...
std::pair< typename base::iterator, bool > insert(StringRef Key)
unsigned getNumHashMismatches() const
Get the number of hash mismatches.
Error takeError()
Return the first encountered error and reset FirstError to a success value.
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
void sort(IteratorTy Start, IteratorTy End)
void clearValueData()
Clear value data entries.
static const char *const Magic
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
InstrProfRecord(std::vector< uint64_t > Counts)
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
static ErrorSuccess success()
Create a success value.
StringRef getCoverageMappingVarName()
Return the name of a covarage mapping variable (internal linkage) for each instrumented source module...
StringRef getPGOFuncNameMetadataName()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
OverlapStats(OverlapStatsLevel L=ProgramLevel)
LinkageTypes
An enumeration for the kinds of linkage for global values.
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
static void setCSFlagInHash(uint64_t &FuncHash)
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Base class for user error types.
CountSumOrPercent Overlap
void sortByTargetValues()
Sort ValueData ascending by Value.
std::vector< uint64_t > Counts
A raw_ostream that writes to a file descriptor.
Profiling information for a single function.
StringRef getNameData() const
Return the name section data.
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.
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
CountSumOrPercent Mismatch
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
InstrProfValueSiteRecord(InputIterator F, InputIterator L)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef getInstrProfValueRangeProfFuncName()
Return the name profile runtime entry point to do value range profiling.
LLVM Value Representation.
void createIRLevelProfileFlagVar(Module &M, bool IsCS)
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
std::vector< std::pair< uint64_t, uint64_t > > AddrHashMap
Lightweight error class with error context and mandatory checking.
uint64_t MinCount
The minimum count for this percentile.
StringSet - A wrapper for StringMap that provides set-like functionality.
support::endianness getHostEndianness()
This class implements an extremely fast bulk output stream that can only output to a stream...
InstrProfRecord & operator=(const InstrProfRecord &RHS)
StringRef - Represent a constant reference to a string, i.e.
std::unique_ptr< InstrProfValueData[]> getValueForSite(uint32_t ValueKind, uint32_t Site, uint64_t *TotalC=nullptr) const
Return the array of profiled values at Site.
uint64_t NumCounts
Number of counts >= the minimum count.
StringRef getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash)
Just like getFuncName, except that it will return a non-empty StringRef if the function is external t...
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
InstrProfError(instrprof_error Err)
void setFuncInfo(StringRef Name, uint64_t Hash)
Function object to check whether the first component of a std::pair compares less than the first comp...
void Clear()
Clear value data entries and edge counters.
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
This is a value type class that represents a single section in the list of sections in the object fil...