16 #ifndef LLVM_PROFILEDATA_INSTRPROF_H 17 #define LLVM_PROFILEDATA_INSTRPROF_H 43 #include <system_error> 51 struct InstrProfRecord;
52 class InstrProfSymtab;
58 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind, 69 bool AddSegmentInfo =
true);
74 return INSTR_PROF_VALUE_PROF_FUNC_STR;
79 return INSTR_PROF_VALUE_RANGE_PROF_FUNC_STR;
104 return "__llvm_prf_nm";
111 return "__llvm_coverage_mapping";
119 return "__llvm_coverage_names";
128 return "__llvm_profile_register_functions";
134 return "__llvm_profile_register_function";
139 return "__llvm_profile_register_names_function";
152 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
158 return "__llvm_profile_runtime_user";
168 uint64_t
Version = INSTR_PROF_INDEX_VERSION);
177 uint64_t
Version = INSTR_PROF_INDEX_VERSION);
216 bool doCompression, std::string &Result);
221 std::string &Result,
bool doCompression =
true);
238 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value, 246 const InstrProfRecord &InstrProfR,
252 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
261 InstrProfValueData ValueData[],
262 uint32_t &ActualNumValueData, uint64_t &TotalC);
312 std::string message()
const override;
347 unsigned NumHashMismatches = 0;
350 unsigned NumCountMismatches = 0;
353 unsigned NumCounterOverflows = 0;
356 unsigned NumValueSiteCountMismatches = 0;
363 "Unchecked soft error encountered");
380 return NumValueSiteCountMismatches;
388 auto E = make_error<InstrProfError>(FirstError);
400 namespace IndexedInstrProf {
421 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
424 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
431 return "** External Symbol **";
438 inline void finalizeSymtab();
468 template <
typename NameIterRange>
Error create(
const NameIterRange &IterRange);
473 if (FuncName.
empty())
477 MD5NameMap.push_back(std::make_pair(
487 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
491 uint64_t getFunctionHashFromAddress(uint64_t Address);
500 inline StringRef getFuncName(uint64_t FuncMD5Hash);
505 inline StringRef getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash);
509 return Symbol == InstrProfSymtab::getExternalSymbol();
518 inline StringRef getOrigFuncName(uint64_t FuncMD5Hash);
534 template <
typename NameIterRange>
536 for (
auto Name : IterRange)
544 void InstrProfSymtab::finalizeSymtab() {
550 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
556 StringRef ret = getFuncName(FuncMD5Hash);
558 return InstrProfSymtab::getExternalSymbol();
566 [](
const std::pair<uint64_t, std::string> &LHS,
567 uint64_t RHS) {
return LHS.first < RHS; });
568 if (Result != MD5NameMap.end() && Result->first == FuncMD5Hash)
569 return Result->second;
577 [](
const std::pair<uint64_t, Function*> &LHS,
578 uint64_t RHS) {
return LHS.first < RHS; });
579 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
580 return Result->second;
587 StringRef PGOName = getFuncName(FuncMD5Hash);
599 template <
class InputIterator>
606 [](
const InstrProfValueData &left,
const InstrProfValueData &right) {
607 return left.Value < right.Value;
611 inline void sortByCount();
629 : Counts(RHS.Counts),
630 ValueData(RHS.ValueData
636 if (!RHS.ValueData) {
641 ValueData = llvm::make_unique<ValueProfData>(*RHS.ValueData);
643 *ValueData = *RHS.ValueData;
649 inline uint32_t getNumValueKinds()
const;
664 inline std::unique_ptr<InstrProfValueData[]>
666 uint64_t *TotalC =
nullptr)
const;
671 inline uint64_t getValueForSite(InstrProfValueData Dest[],
uint32_t ValueKind,
694 for (
auto &SR : getValueSitesForKind(
Kind))
708 struct ValueProfData {
709 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
710 std::vector<InstrProfValueSiteRecord> MemOPSizes;
712 std::unique_ptr<ValueProfData> ValueData;
715 getValueSitesForKind(
uint32_t ValueKind) {
719 auto AR =
const_cast<const InstrProfRecord *
>(
this)->getValueSitesForKind(
722 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
725 getValueSitesForKind(
uint32_t ValueKind)
const {
729 case IPVK_IndirectCallTarget:
730 return ValueData->IndirectCallSites;
732 return ValueData->MemOPSizes;
738 std::vector<InstrProfValueSiteRecord> &
739 getOrCreateValueSitesForKind(
uint32_t ValueKind) {
741 ValueData = llvm::make_unique<ValueProfData>();
743 case IPVK_IndirectCallTarget:
744 return ValueData->IndirectCallSites;
746 return ValueData->MemOPSizes;
763 void scaleValueProfData(
uint32_t ValueKind, uint64_t Weight,
773 std::vector<uint64_t> Counts)
780 NumValueKinds += !(getValueSitesForKind(
Kind).
empty());
781 return NumValueKinds;
786 for (
auto &SR : getValueSitesForKind(ValueKind))
787 N += SR.ValueData.size();
792 return getValueSitesForKind(ValueKind).size();
797 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
800 std::unique_ptr<InstrProfValueData[]>
802 uint64_t *TotalC)
const {
804 uint64_t &TotalCount = (TotalC ==
nullptr ?
Dummy : *TotalC);
805 uint32_t N = getNumValueDataForSite(ValueKind, Site);
808 return std::unique_ptr<InstrProfValueData[]>(
nullptr);
811 auto VD = llvm::make_unique<InstrProfValueData[]>(
N);
812 TotalCount = getValueForSite(VD.get(),
ValueKind, Site);
821 uint64_t TotalCount = 0;
822 for (
auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
823 Dest[
I].Value = V.Value;
824 Dest[
I].Count = V.Count;
834 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
842 #define INSTR_PROF_VALUE_PROF_DATA 847 [](
const InstrProfValueData &left,
const InstrProfValueData &right) {
848 return left.Count > right.Count;
851 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
852 if (ValueData.size() > max_s)
853 ValueData.resize(max_s);
856 namespace IndexedInstrProf {
871 const uint64_t
Magic = 0x8169666f72706cff;
926 TotalNumFunctions = 0,
932 MaxFunctionCount = 2,
936 MaxInternalBlockCount = 4,
939 NumKinds = TotalBlockCount + 1
950 void operator delete(
void *ptr) { ::operator
delete(ptr); }
953 return sizeof(
Summary) + NumCutoffEntries *
sizeof(
Entry) +
954 NumSumFields *
sizeof(uint64_t);
958 return reinterpret_cast<const uint64_t *
>(
this + 1);
962 return reinterpret_cast<uint64_t *
>(
this + 1);
966 return reinterpret_cast<const Entry *
>(
967 &getSummaryDataBase()[NumSummaryFields]);
971 return reinterpret_cast<Entry *
>(&getSummaryDataBase()[NumSummaryFields]);
975 return getSummaryDataBase()[K];
979 getSummaryDataBase()[K] = V;
985 Entry &ER = getCutoffEntryBase()[
I];
993 return std::unique_ptr<Summary>(
new (::operator
new(TotalSize))
999 namespace RawInstrProf {
1010 template <
class IntPtrT>
inline uint64_t
getMagic();
1012 return INSTR_PROF_RAW_MAGIC_64;
1016 return INSTR_PROF_RAW_MAGIC_32;
1025 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name; 1034 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name; 1042 int64_t &RangeLast);
1046 #endif // LLVM_PROFILEDATA_INSTRPROF_H 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. ...
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 >()
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()
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
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.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
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...
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.
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()
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
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.
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
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...
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.
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)
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)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
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")
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.
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Base class for user error types.
void sortByTargetValues()
Sort ValueData ascending by Value.
std::vector< uint64_t > Counts
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.
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
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.
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 getInstrProfComdatPrefix()
Return the name prefix of the COMDAT group for instrumentation variables associated with a COMDAT fun...
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)
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...