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;
359 /// Merge data from another InstrProfValueSiteRecord
360 /// Optionally scale merged counts by \p Weight.
361 instrprof_error mergeValueData(InstrProfValueSiteRecord &Input,
362 uint64_t Weight = 1);
365 /// Profiling information for a single function.
366 struct InstrProfRecord {
368 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
369 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
372 std::vector<uint64_t> Counts;
374 typedef std::vector<std::pair<uint64_t, uint64_t>> ValueMapType;
376 /// Return the number of value profile kinds with non-zero number
377 /// of profile sites.
378 inline uint32_t getNumValueKinds() const;
379 /// Return the number of instrumented sites for ValueKind.
380 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
381 /// Return the total number of ValueData for ValueKind.
382 inline uint32_t getNumValueData(uint32_t ValueKind) const;
383 /// Return the number of value data collected for ValueKind at profiling
385 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
386 uint32_t Site) const;
387 /// Return the array of profiled values at \p Site.
388 inline std::unique_ptr<InstrProfValueData[]>
389 getValueForSite(uint32_t ValueKind, uint32_t Site,
390 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
392 getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
393 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
394 /// Reserve space for NumValueSites sites.
395 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
396 /// Add ValueData for ValueKind at value Site.
397 void addValueData(uint32_t ValueKind, uint32_t Site,
398 InstrProfValueData *VData, uint32_t N,
399 ValueMapType *ValueMap);
401 /// Merge the counts in \p Other into this one.
402 /// Optionally scale merged counts by \p Weight.
403 instrprof_error merge(InstrProfRecord &Other, uint64_t Weight = 1);
405 /// Clear value data entries
406 void clearValueData() {
407 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
408 getValueSitesForKind(Kind).clear();
412 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
413 const std::vector<InstrProfValueSiteRecord> &
414 getValueSitesForKind(uint32_t ValueKind) const {
416 case IPVK_IndirectCallTarget:
417 return IndirectCallSites;
419 llvm_unreachable("Unknown value kind!");
421 return IndirectCallSites;
424 std::vector<InstrProfValueSiteRecord> &
425 getValueSitesForKind(uint32_t ValueKind) {
426 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
427 const_cast<const InstrProfRecord *>(this)
428 ->getValueSitesForKind(ValueKind));
431 // Map indirect call target name hash to name string.
432 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
433 ValueMapType *HashKeys);
435 // Merge Value Profile data from Src record to this record for ValueKind.
436 // Scale merged value counts by \p Weight.
437 instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
441 uint32_t InstrProfRecord::getNumValueKinds() const {
442 uint32_t NumValueKinds = 0;
443 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
444 NumValueKinds += !(getValueSitesForKind(Kind).empty());
445 return NumValueKinds;
448 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
450 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
451 getValueSitesForKind(ValueKind);
452 for (auto &SR : SiteRecords) {
453 N += SR.ValueData.size();
458 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
459 return getValueSitesForKind(ValueKind).size();
462 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
463 uint32_t Site) const {
464 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
467 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
468 uint32_t ValueKind, uint32_t Site,
469 uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
470 uint32_t N = getNumValueDataForSite(ValueKind, Site);
472 return std::unique_ptr<InstrProfValueData[]>(nullptr);
474 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
475 getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
480 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
481 uint32_t ValueKind, uint32_t Site,
482 uint64_t (*ValueMapper)(uint32_t,
485 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
486 Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
487 Dest[I].Count = V.Count;
492 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
493 std::vector<InstrProfValueSiteRecord> &ValueSites =
494 getValueSitesForKind(ValueKind);
495 ValueSites.reserve(NumValueSites);
498 inline support::endianness getHostEndianness() {
499 return sys::IsLittleEndianHost ? support::little : support::big;
502 // Include definitions for value profile data
503 #define INSTR_PROF_VALUE_PROF_DATA
504 #include "llvm/ProfileData/InstrProfData.inc"
507 * Initialize the record for runtime value profile data.
508 * Return 0 if the initialization is successful, otherwise
511 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
512 const uint16_t *NumValueSites,
513 ValueProfNode **Nodes);
515 /* Release memory allocated for the runtime record. */
516 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
518 /* Return the size of ValueProfData structure that can be used to store
519 the value profile data collected at runtime. */
520 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
522 /* Return a ValueProfData instance that stores the data collected at runtime. */
524 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
527 namespace IndexedInstrProf {
529 enum class HashT : uint32_t {
535 static inline uint64_t MD5Hash(StringRef Str) {
538 llvm::MD5::MD5Result Result;
540 // Return the least significant 8 bytes. Our MD5 implementation returns the
541 // result in little endian, so we may need to swap bytes.
542 using namespace llvm::support;
543 return endian::read<uint64_t, little, unaligned>(Result);
546 inline uint64_t ComputeHash(HashT Type, StringRef K) {
549 return IndexedInstrProf::MD5Hash(K);
551 llvm_unreachable("Unhandled hash type");
554 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
555 const uint64_t Version = INSTR_PROF_INDEX_VERSION;
556 const HashT HashType = HashT::MD5;
558 inline uint64_t ComputeHash(StringRef K) { return ComputeHash(HashType, K); }
560 // This structure defines the file header of the LLVM profile
561 // data file in indexed-format.
565 uint64_t MaxFunctionCount;
570 } // end namespace IndexedInstrProf
572 namespace RawInstrProf {
574 const uint64_t Version = INSTR_PROF_RAW_VERSION;
576 template <class IntPtrT> inline uint64_t getMagic();
577 template <> inline uint64_t getMagic<uint64_t>() {
578 return INSTR_PROF_RAW_MAGIC_64;
581 template <> inline uint64_t getMagic<uint32_t>() {
582 return INSTR_PROF_RAW_MAGIC_32;
585 // Per-function profile data header/control structure.
586 // The definition should match the structure defined in
587 // compiler-rt/lib/profile/InstrProfiling.h.
588 // It should also match the synthesized type in
589 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
590 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
591 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
592 #include "llvm/ProfileData/InstrProfData.inc"
595 // File header structure of the LLVM profile data in raw format.
596 // The definition should match the header referenced in
597 // compiler-rt/lib/profile/InstrProfilingFile.c and
598 // InstrProfilingBuffer.c.
600 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
601 #include "llvm/ProfileData/InstrProfData.inc"
604 } // end namespace RawInstrProf
608 // Profile coverage map has the following layout:
609 // [CoverageMapFileHeader]
611 // [CovMapFunctionRecord]
612 // [CovMapFunctionRecord]
615 // [Encoded Region Mapping Data]
617 template <class IntPtrT> struct CovMapFunctionRecord {
618 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
619 #include "llvm/ProfileData/InstrProfData.inc"
621 // Per module coverage mapping data header, i.e. CoverageMapFileHeader
623 struct CovMapHeader {
624 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Type Name;
625 #include "llvm/ProfileData/InstrProfData.inc"
630 enum CoverageMappingVersion {
631 CoverageMappingVersion1 = 0,
632 // The current versin is Version1
633 CoverageMappingCurrentVersion = INSTR_PROF_COVMAP_VERSION
637 } // end namespace llvm
641 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
644 #endif // LLVM_PROFILEDATA_INSTRPROF_H_