1 //=-- InstrProf.h - Instrumented profiling format support ---------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Instrumentation-based profiling data is generated by instrumented
11 // binaries through library functions in compiler-rt, and read by the clang
12 // frontend to feed PGO.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_PROFILEDATA_INSTRPROF_H_
17 #define LLVM_PROFILEDATA_INSTRPROF_H_
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/ProfileData/InstrProfData.inc"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/MD5.h"
30 #include <system_error>
39 /// Return the name of data section containing profile counter variables.
40 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
41 return AddSegment ? "__DATA," INSTR_PROF_CNTS_SECT_NAME_STR
42 : INSTR_PROF_CNTS_SECT_NAME_STR;
45 /// Return the name of data section containing names of instrumented
47 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
48 return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR
49 : INSTR_PROF_NAME_SECT_NAME_STR;
52 /// Return the name of the data section containing per-function control
54 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
55 return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR
56 : INSTR_PROF_DATA_SECT_NAME_STR;
59 /// Return the name profile runtime entry point to do value profiling
61 inline StringRef getInstrProfValueProfFuncName() {
62 return INSTR_PROF_VALUE_PROF_FUNC_STR;
65 /// Return the name of the section containing function coverage mapping
67 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
68 return AddSegment ? "__DATA," INSTR_PROF_COVMAP_SECT_NAME_STR
69 : INSTR_PROF_COVMAP_SECT_NAME_STR;
72 /// Return the name prefix of variables containing instrumented function names.
73 inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
75 /// Return the name prefix of variables containing per-function control data.
76 inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
78 /// Return the name prefix of profile counter variables.
79 inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
81 /// Return the name prefix of the COMDAT group for instrumentation variables
82 /// associated with a COMDAT function.
83 inline StringRef getInstrProfComdatPrefix() { return "__profv_"; }
85 /// Return the name of a covarage mapping variable (internal linkage)
86 /// for each instrumented source module. Such variables are allocated
87 /// in the __llvm_covmap section.
88 inline StringRef getCoverageMappingVarName() {
89 return "__llvm_coverage_mapping";
92 /// Return the name of the internal variable recording the array
93 /// of PGO name vars referenced by the coverage mapping, The owning
94 /// functions of those names are not emitted by FE (e.g, unused inline
96 inline StringRef getCoverageNamesVarName() { return "__llvm_coverage_names"; }
98 /// Return the name of function that registers all the per-function control
99 /// data at program startup time by calling __llvm_register_function. This
100 /// function has internal linkage and is called by __llvm_profile_init
101 /// runtime method. This function is not generated for these platforms:
102 /// Darwin, Linux, and FreeBSD.
103 inline StringRef getInstrProfRegFuncsName() {
104 return "__llvm_profile_register_functions";
107 /// Return the name of the runtime interface that registers per-function control
108 /// data for one instrumented function.
109 inline StringRef getInstrProfRegFuncName() {
110 return "__llvm_profile_register_function";
113 /// Return the name of the runtime initialization method that is generated by
114 /// the compiler. The function calls __llvm_profile_register_functions and
115 /// __llvm_profile_override_default_filename functions if needed. This function
116 /// has internal linkage and invoked at startup time via init_array.
117 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
119 /// Return the name of the hook variable defined in profile runtime library.
120 /// A reference to the variable causes the linker to link in the runtime
121 /// initialization module (which defines the hook variable).
122 inline StringRef getInstrProfRuntimeHookVarName() {
123 return "__llvm_profile_runtime";
126 /// Return the name of the compiler generated function that references the
127 /// runtime hook variable. The function is a weak global.
128 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
129 return "__llvm_profile_runtime_user";
132 /// Return the name of the profile runtime interface that overrides the default
133 /// profile data file name.
134 inline StringRef getInstrProfFileOverriderFuncName() {
135 return "__llvm_profile_override_default_filename";
138 /// Return the modified name for function \c F suitable to be
139 /// used the key for profile lookup.
140 std::string getPGOFuncName(const Function &F,
141 uint64_t Version = INSTR_PROF_INDEX_VERSION);
143 /// Return the modified name for a function suitable to be
144 /// used the key for profile lookup. The function's original
145 /// name is \c RawFuncName and has linkage of type \c Linkage.
146 /// The function is defined in module \c FileName.
147 std::string getPGOFuncName(StringRef RawFuncName,
148 GlobalValue::LinkageTypes Linkage,
150 uint64_t Version = INSTR_PROF_INDEX_VERSION);
152 /// Create and return the global variable for function name used in PGO
153 /// instrumentation. \c FuncName is the name of the function returned
154 /// by \c getPGOFuncName call.
155 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
157 /// Create and return the global variable for function name used in PGO
158 /// instrumentation. /// \c FuncName is the name of the function
159 /// returned by \c getPGOFuncName call, \c M is the owning module,
160 /// and \c Linkage is the linkage of the instrumented function.
161 GlobalVariable *createPGOFuncNameVar(Module &M,
162 GlobalValue::LinkageTypes Linkage,
164 /// Return the initializer in string of the PGO name var \c NameVar.
165 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
167 /// Given a PGO function name, remove the filename prefix and return
168 /// the original (static) function name.
169 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName);
171 /// Given a vector of strings (function PGO names) \c NameStrs, the
172 /// method generates a combined string \c Result thatis ready to be
173 /// serialized. The \c Result string is comprised of three fields:
174 /// The first field is the legnth of the uncompressed strings, and the
175 /// the second field is the length of the zlib-compressed string.
176 /// Both fields are encoded in ULEB128. If \c doCompress is false, the
177 /// third field is the uncompressed strings; otherwise it is the
178 /// compressed string. When the string compression is off, the
179 /// second field will have value zero.
180 int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
181 bool doCompression, std::string &Result);
182 /// Produce \c Result string with the same format described above. The input
183 /// is vector of PGO function name variables that are referenced.
184 int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
185 std::string &Result);
186 class InstrProfSymtab;
187 /// \c NameStrings is a string composed of one of more sub-strings encoded in
189 /// format described above. The substrings are seperated by 0 or more zero
191 /// This method decodes the string and populates the \c Symtab.
192 int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab);
194 const std::error_category &instrprof_category();
196 enum class instrprof_error {
203 unsupported_hash_type,
211 value_site_count_mismatch
214 inline std::error_code make_error_code(instrprof_error E) {
215 return std::error_code(static_cast<int>(E), instrprof_category());
218 inline instrprof_error MergeResult(instrprof_error &Accumulator,
219 instrprof_error Result) {
220 // Prefer first error encountered as later errors may be secondary effects of
221 // the initial problem.
222 if (Accumulator == instrprof_error::success &&
223 Result != instrprof_error::success)
224 Accumulator = Result;
228 enum InstrProfValueKind : uint32_t {
229 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
230 #include "llvm/ProfileData/InstrProfData.inc"
237 namespace IndexedInstrProf {
238 uint64_t ComputeHash(StringRef K);
241 /// A symbol table used for function PGO name look-up with keys
242 /// (such as pointers, md5hash values) to the function. A function's
243 /// PGO name or name's md5hash are used in retrieving the profile
244 /// data of the function. See \c getPGOFuncName() method for details
245 /// on how PGO name is formed.
246 class InstrProfSymtab {
248 typedef std::vector<std::pair<uint64_t, uint64_t>> AddrHashMap;
253 // A map from MD5 hash keys to function name strings.
254 std::vector<std::pair<uint64_t, std::string>> HashNameMap;
255 // A map from function runtime address to function name MD5 hash.
256 // This map is only populated and used by raw instr profile reader.
257 AddrHashMap AddrToMD5Map;
260 InstrProfSymtab() : Data(), Address(0), HashNameMap(), AddrToMD5Map() {}
262 /// Create InstrProfSymtab from an object file section which
263 /// contains function PGO names that are uncompressed.
264 /// This interface is used by CoverageMappingReader.
265 std::error_code create(object::SectionRef &Section);
266 /// This interface is used by reader of CoverageMapping test
268 inline std::error_code create(StringRef D, uint64_t BaseAddr);
269 /// \c NameStrings is a string composed of one of more sub-strings
270 /// encoded in the format described above. The substrings are
271 /// seperated by 0 or more zero bytes. This method decodes the
272 /// string and populates the \c Symtab.
273 inline std::error_code create(StringRef NameStrings);
274 /// Create InstrProfSymtab from a set of names iteratable from
275 /// \p IterRange. This interface is used by IndexedProfReader.
276 template <typename NameIterRange> void create(const NameIterRange &IterRange);
277 // If the symtab is created by a series of calls to \c addFuncName, \c
278 // finalizeSymtab needs to be called before looking up function names.
279 // This is required because the underlying map is a vector (for space
280 // efficiency) which needs to be sorted.
281 inline void finalizeSymtab();
282 /// Update the symtab by adding \p FuncName to the table. This interface
283 /// is used by the raw and text profile readers.
284 void addFuncName(StringRef FuncName) {
285 HashNameMap.push_back(std::make_pair(
286 IndexedInstrProf::ComputeHash(FuncName), FuncName.str()));
288 /// Map a function address to its name's MD5 hash. This interface
289 /// is only used by the raw profiler reader.
290 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
291 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
293 AddrHashMap &getAddrHashMap() { return AddrToMD5Map; }
294 /// Return function's PGO name from the function name's symbol
295 /// address in the object file. If an error occurs, return
297 StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
298 /// Return function's PGO name from the name's md5 hash value.
299 /// If not found, return an empty string.
300 inline StringRef getFuncName(uint64_t FuncMD5Hash);
303 std::error_code InstrProfSymtab::create(StringRef D, uint64_t BaseAddr) {
306 return std::error_code();
309 std::error_code InstrProfSymtab::create(StringRef NameStrings) {
310 if (readPGOFuncNameStrings(NameStrings, *this))
311 return make_error_code(instrprof_error::malformed);
312 return std::error_code();
315 template <typename NameIterRange>
316 void InstrProfSymtab::create(const NameIterRange &IterRange) {
317 for (auto Name : IterRange)
318 HashNameMap.push_back(
319 std::make_pair(IndexedInstrProf::ComputeHash(Name), Name.str()));
323 void InstrProfSymtab::finalizeSymtab() {
324 std::sort(HashNameMap.begin(), HashNameMap.end(), less_first());
325 HashNameMap.erase(std::unique(HashNameMap.begin(), HashNameMap.end()),
327 std::sort(AddrToMD5Map.begin(), AddrToMD5Map.end(), less_first());
328 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
332 StringRef InstrProfSymtab::getFuncName(uint64_t FuncMD5Hash) {
334 std::lower_bound(HashNameMap.begin(), HashNameMap.end(), FuncMD5Hash,
335 [](const std::pair<uint64_t, std::string> &LHS,
336 uint64_t RHS) { return LHS.first < RHS; });
337 if (Result != HashNameMap.end())
338 return Result->second;
342 struct InstrProfValueSiteRecord {
343 /// Value profiling data pairs at a given value site.
344 std::list<InstrProfValueData> ValueData;
346 InstrProfValueSiteRecord() { ValueData.clear(); }
347 template <class InputIterator>
348 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
351 /// Sort ValueData ascending by Value
352 void sortByTargetValues() {
354 [](const InstrProfValueData &left, const InstrProfValueData &right) {
355 return left.Value < right.Value;
358 /// Sort ValueData Descending by Count
359 inline void sortByCount();
361 /// Merge data from another InstrProfValueSiteRecord
362 /// Optionally scale merged counts by \p Weight.
363 instrprof_error merge(InstrProfValueSiteRecord &Input, uint64_t Weight = 1);
364 /// Scale up value profile data counts.
365 instrprof_error scale(uint64_t Weight);
368 /// Profiling information for a single function.
369 struct InstrProfRecord {
371 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
372 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
375 std::vector<uint64_t> Counts;
377 typedef std::vector<std::pair<uint64_t, uint64_t>> ValueMapType;
379 /// Return the number of value profile kinds with non-zero number
380 /// of profile sites.
381 inline uint32_t getNumValueKinds() const;
382 /// Return the number of instrumented sites for ValueKind.
383 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
384 /// Return the total number of ValueData for ValueKind.
385 inline uint32_t getNumValueData(uint32_t ValueKind) const;
386 /// Return the number of value data collected for ValueKind at profiling
388 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
389 uint32_t Site) const;
390 /// Return the array of profiled values at \p Site.
391 inline std::unique_ptr<InstrProfValueData[]>
392 getValueForSite(uint32_t ValueKind, uint32_t Site,
393 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
395 getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
396 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
397 /// Reserve space for NumValueSites sites.
398 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
399 /// Add ValueData for ValueKind at value Site.
400 void addValueData(uint32_t ValueKind, uint32_t Site,
401 InstrProfValueData *VData, uint32_t N,
402 ValueMapType *ValueMap);
404 /// Merge the counts in \p Other into this one.
405 /// Optionally scale merged counts by \p Weight.
406 instrprof_error merge(InstrProfRecord &Other, uint64_t Weight = 1);
408 /// Scale up profile counts (including value profile data) by
410 instrprof_error scale(uint64_t Weight);
412 /// Sort value profile data (per site) by count.
413 void sortValueData() {
414 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
415 std::vector<InstrProfValueSiteRecord> &SiteRecords =
416 getValueSitesForKind(Kind);
417 for (auto &SR : SiteRecords)
421 /// Clear value data entries
422 void clearValueData() {
423 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
424 getValueSitesForKind(Kind).clear();
428 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
429 const std::vector<InstrProfValueSiteRecord> &
430 getValueSitesForKind(uint32_t ValueKind) const {
432 case IPVK_IndirectCallTarget:
433 return IndirectCallSites;
435 llvm_unreachable("Unknown value kind!");
437 return IndirectCallSites;
440 std::vector<InstrProfValueSiteRecord> &
441 getValueSitesForKind(uint32_t ValueKind) {
442 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
443 const_cast<const InstrProfRecord *>(this)
444 ->getValueSitesForKind(ValueKind));
447 // Map indirect call target name hash to name string.
448 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
449 ValueMapType *HashKeys);
451 // Merge Value Profile data from Src record to this record for ValueKind.
452 // Scale merged value counts by \p Weight.
453 instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
455 // Scale up value profile data count.
456 instrprof_error scaleValueProfData(uint32_t ValueKind, uint64_t Weight);
459 uint32_t InstrProfRecord::getNumValueKinds() const {
460 uint32_t NumValueKinds = 0;
461 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
462 NumValueKinds += !(getValueSitesForKind(Kind).empty());
463 return NumValueKinds;
466 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
468 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
469 getValueSitesForKind(ValueKind);
470 for (auto &SR : SiteRecords) {
471 N += SR.ValueData.size();
476 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
477 return getValueSitesForKind(ValueKind).size();
480 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
481 uint32_t Site) const {
482 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
485 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
486 uint32_t ValueKind, uint32_t Site,
487 uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
488 uint32_t N = getNumValueDataForSite(ValueKind, Site);
490 return std::unique_ptr<InstrProfValueData[]>(nullptr);
492 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
493 getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
498 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
499 uint32_t ValueKind, uint32_t Site,
500 uint64_t (*ValueMapper)(uint32_t,
503 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
504 Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
505 Dest[I].Count = V.Count;
510 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
511 std::vector<InstrProfValueSiteRecord> &ValueSites =
512 getValueSitesForKind(ValueKind);
513 ValueSites.reserve(NumValueSites);
516 inline support::endianness getHostEndianness() {
517 return sys::IsLittleEndianHost ? support::little : support::big;
520 // Include definitions for value profile data
521 #define INSTR_PROF_VALUE_PROF_DATA
522 #include "llvm/ProfileData/InstrProfData.inc"
524 void InstrProfValueSiteRecord::sortByCount() {
526 [](const InstrProfValueData &left, const InstrProfValueData &right) {
527 return left.Count > right.Count;
530 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
531 if (ValueData.size() > max_s)
532 ValueData.resize(max_s);
536 * Initialize the record for runtime value profile data.
537 * Return 0 if the initialization is successful, otherwise
540 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
541 const uint16_t *NumValueSites,
542 ValueProfNode **Nodes);
544 /* Release memory allocated for the runtime record. */
545 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
547 /* Return the size of ValueProfData structure that can be used to store
548 the value profile data collected at runtime. */
549 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
551 /* Return a ValueProfData instance that stores the data collected at runtime. */
553 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
556 namespace IndexedInstrProf {
558 enum class HashT : uint32_t {
564 static inline uint64_t MD5Hash(StringRef Str) {
567 llvm::MD5::MD5Result Result;
569 // Return the least significant 8 bytes. Our MD5 implementation returns the
570 // result in little endian, so we may need to swap bytes.
571 using namespace llvm::support;
572 return endian::read<uint64_t, little, unaligned>(Result);
575 inline uint64_t ComputeHash(HashT Type, StringRef K) {
578 return IndexedInstrProf::MD5Hash(K);
580 llvm_unreachable("Unhandled hash type");
583 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
584 const uint64_t Version = INSTR_PROF_INDEX_VERSION;
585 const HashT HashType = HashT::MD5;
587 inline uint64_t ComputeHash(StringRef K) { return ComputeHash(HashType, K); }
589 // This structure defines the file header of the LLVM profile
590 // data file in indexed-format.
594 uint64_t MaxFunctionCount;
599 } // end namespace IndexedInstrProf
601 namespace RawInstrProf {
603 const uint64_t Version = INSTR_PROF_RAW_VERSION;
605 template <class IntPtrT> inline uint64_t getMagic();
606 template <> inline uint64_t getMagic<uint64_t>() {
607 return INSTR_PROF_RAW_MAGIC_64;
610 template <> inline uint64_t getMagic<uint32_t>() {
611 return INSTR_PROF_RAW_MAGIC_32;
614 // Per-function profile data header/control structure.
615 // The definition should match the structure defined in
616 // compiler-rt/lib/profile/InstrProfiling.h.
617 // It should also match the synthesized type in
618 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
619 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
620 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
621 #include "llvm/ProfileData/InstrProfData.inc"
624 // File header structure of the LLVM profile data in raw format.
625 // The definition should match the header referenced in
626 // compiler-rt/lib/profile/InstrProfilingFile.c and
627 // InstrProfilingBuffer.c.
629 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
630 #include "llvm/ProfileData/InstrProfData.inc"
633 } // end namespace RawInstrProf
637 // Profile coverage map has the following layout:
638 // [CoverageMapFileHeader]
640 // [CovMapFunctionRecord]
641 // [CovMapFunctionRecord]
644 // [Encoded Region Mapping Data]
646 template <class IntPtrT> struct CovMapFunctionRecord {
647 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
648 #include "llvm/ProfileData/InstrProfData.inc"
650 // Per module coverage mapping data header, i.e. CoverageMapFileHeader
652 struct CovMapHeader {
653 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Type Name;
654 #include "llvm/ProfileData/InstrProfData.inc"
659 enum CoverageMappingVersion {
660 CoverageMappingVersion1 = 0,
661 // The current versin is Version1
662 CoverageMappingCurrentVersion = INSTR_PROF_COVMAP_VERSION
666 } // end namespace llvm
670 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
673 #endif // LLVM_PROFILEDATA_INSTRPROF_H_