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>
33 #define INSTR_PROF_INDEX_VERSION 3
40 /// Return the name of data section containing profile counter variables.
41 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
42 return AddSegment ? "__DATA," INSTR_PROF_CNTS_SECT_NAME_STR
43 : INSTR_PROF_CNTS_SECT_NAME_STR;
46 /// Return the name of data section containing names of instrumented
48 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
49 return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR
50 : INSTR_PROF_NAME_SECT_NAME_STR;
53 /// Return the name of the data section containing per-function control
55 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
56 return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR
57 : INSTR_PROF_DATA_SECT_NAME_STR;
60 /// Return the name profile runtime entry point to do value profiling
62 inline StringRef getInstrProfValueProfFuncName() {
63 return INSTR_PROF_VALUE_PROF_FUNC_STR;
66 /// Return the name of the section containing function coverage mapping
68 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
69 return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
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 function that registers all the per-function control
93 /// data at program startup time by calling __llvm_register_function. This
94 /// function has internal linkage and is called by __llvm_profile_init
95 /// runtime method. This function is not generated for these platforms:
96 /// Darwin, Linux, and FreeBSD.
97 inline StringRef getInstrProfRegFuncsName() {
98 return "__llvm_profile_register_functions";
101 /// Return the name of the runtime interface that registers per-function control
102 /// data for one instrumented function.
103 inline StringRef getInstrProfRegFuncName() {
104 return "__llvm_profile_register_function";
107 /// Return the name of the runtime initialization method that is generated by
108 /// the compiler. The function calls __llvm_profile_register_functions and
109 /// __llvm_profile_override_default_filename functions if needed. This function
110 /// has internal linkage and invoked at startup time via init_array.
111 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
113 /// Return the name of the hook variable defined in profile runtime library.
114 /// A reference to the variable causes the linker to link in the runtime
115 /// initialization module (which defines the hook variable).
116 inline StringRef getInstrProfRuntimeHookVarName() {
117 return "__llvm_profile_runtime";
120 /// Return the name of the compiler generated function that references the
121 /// runtime hook variable. The function is a weak global.
122 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
123 return "__llvm_profile_runtime_user";
126 /// Return the name of the profile runtime interface that overrides the default
127 /// profile data file name.
128 inline StringRef getInstrProfFileOverriderFuncName() {
129 return "__llvm_profile_override_default_filename";
132 /// Return the modified name for function \c F suitable to be
133 /// used the key for profile lookup.
134 std::string getPGOFuncName(const Function &F,
135 uint64_t Version = INSTR_PROF_INDEX_VERSION);
137 /// Return the modified name for a function suitable to be
138 /// used the key for profile lookup. The function's original
139 /// name is \c RawFuncName and has linkage of type \c Linkage.
140 /// The function is defined in module \c FileName.
141 std::string getPGOFuncName(StringRef RawFuncName,
142 GlobalValue::LinkageTypes Linkage,
144 uint64_t Version = INSTR_PROF_INDEX_VERSION);
146 /// Create and return the global variable for function name used in PGO
147 /// instrumentation. \c FuncName is the name of the function returned
148 /// by \c getPGOFuncName call.
149 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
151 /// Create and return the global variable for function name used in PGO
152 /// instrumentation. /// \c FuncName is the name of the function
153 /// returned by \c getPGOFuncName call, \c M is the owning module,
154 /// and \c Linkage is the linkage of the instrumented function.
155 GlobalVariable *createPGOFuncNameVar(Module &M,
156 GlobalValue::LinkageTypes Linkage,
158 /// Return the initializer in string of the PGO name var \c NameVar.
159 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
161 /// Given a PGO function name, remove the filename prefix and return
162 /// the original (static) function name.
163 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName);
165 /// Given a vector of strings (function PGO names) \c NameStrs, the
166 /// method generates a combined string \c Result thatis ready to be
167 /// serialized. The \c Result string is comprised of three fields:
168 /// The first field is the legnth of the uncompressed strings, and the
169 /// the second field is the length of the zlib-compressed string.
170 /// Both fields are encoded in ULEB128. If \c doCompress is false, the
171 /// third field is the uncompressed strings; otherwise it is the
172 /// compressed string. When the string compression is off, the
173 /// second field will have value zero.
174 int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
175 bool doCompression, std::string &Result);
176 /// Produce \c Result string with the same format described above. The input
177 /// is vector of PGO function name variables that are referenced.
178 int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
179 std::string &Result);
180 class InstrProfSymtab;
181 /// \c NameStrings is a string composed of one of more sub-strings encoded in
183 /// format described above. The substrings are seperated by 0 or more zero
185 /// This method decodes the string and populates the \c Symtab.
186 int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab);
188 const std::error_category &instrprof_category();
190 enum class instrprof_error {
197 unsupported_hash_type,
205 value_site_count_mismatch
208 inline std::error_code make_error_code(instrprof_error E) {
209 return std::error_code(static_cast<int>(E), instrprof_category());
212 inline instrprof_error MergeResult(instrprof_error &Accumulator,
213 instrprof_error Result) {
214 // Prefer first error encountered as later errors may be secondary effects of
215 // the initial problem.
216 if (Accumulator == instrprof_error::success &&
217 Result != instrprof_error::success)
218 Accumulator = Result;
222 enum InstrProfValueKind : uint32_t {
223 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
224 #include "llvm/ProfileData/InstrProfData.inc"
231 namespace IndexedInstrProf {
232 uint64_t ComputeHash(StringRef K);
235 /// A symbol table used for function PGO name look-up with keys
236 /// (such as pointers, md5hash values) to the function. A function's
237 /// PGO name or name's md5hash are used in retrieving the profile
238 /// data of the function. See \c getPGOFuncName() method for details
239 /// on how PGO name is formed.
240 class InstrProfSymtab {
242 typedef std::vector<std::pair<uint64_t, uint64_t>> AddrHashMap;
247 // A map from MD5 hash keys to function name strings.
248 std::vector<std::pair<uint64_t, std::string>> HashNameMap;
249 // A map from function runtime address to function name MD5 hash.
250 // This map is only populated and used by raw instr profile reader.
251 AddrHashMap AddrToMD5Map;
254 InstrProfSymtab() : Data(), Address(0), HashNameMap(), AddrToMD5Map() {}
256 /// Create InstrProfSymtab from an object file section which
257 /// contains function PGO names that are uncompressed.
258 /// This interface is used by CoverageMappingReader.
259 std::error_code create(object::SectionRef &Section);
260 /// This interface is used by reader of CoverageMapping test
262 inline std::error_code create(StringRef D, uint64_t BaseAddr);
263 /// \c NameStrings is a string composed of one of more sub-strings
264 /// encoded in the format described above. The substrings are
265 /// seperated by 0 or more zero bytes. This method decodes the
266 /// string and populates the \c Symtab.
267 inline std::error_code create(StringRef NameStrings);
268 /// Create InstrProfSymtab from a set of names iteratable from
269 /// \p IterRange. This interface is used by IndexedProfReader.
270 template <typename NameIterRange> void create(const NameIterRange &IterRange);
271 // If the symtab is created by a series of calls to \c addFuncName, \c
272 // finalizeSymtab needs to be called before looking up function names.
273 // This is required because the underlying map is a vector (for space
274 // efficiency) which needs to be sorted.
275 inline void finalizeSymtab();
276 /// Update the symtab by adding \p FuncName to the table. This interface
277 /// is used by the raw and text profile readers.
278 void addFuncName(StringRef FuncName) {
279 HashNameMap.push_back(std::make_pair(
280 IndexedInstrProf::ComputeHash(FuncName), FuncName.str()));
282 /// Map a function address to its name's MD5 hash. This interface
283 /// is only used by the raw profiler reader.
284 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
285 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
287 AddrHashMap &getAddrHashMap() { return AddrToMD5Map; }
288 /// Return function's PGO name from the function name's symbol
289 /// address in the object file. If an error occurs, return
291 StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
292 /// Return function's PGO name from the name's md5 hash value.
293 /// If not found, return an empty string.
294 inline StringRef getFuncName(uint64_t FuncMD5Hash);
297 std::error_code InstrProfSymtab::create(StringRef D, uint64_t BaseAddr) {
300 return std::error_code();
303 std::error_code InstrProfSymtab::create(StringRef NameStrings) {
304 if (readPGOFuncNameStrings(NameStrings, *this))
305 return make_error_code(instrprof_error::malformed);
306 return std::error_code();
309 template <typename NameIterRange>
310 void InstrProfSymtab::create(const NameIterRange &IterRange) {
311 for (auto Name : IterRange)
312 HashNameMap.push_back(
313 std::make_pair(IndexedInstrProf::ComputeHash(Name), Name.str()));
317 void InstrProfSymtab::finalizeSymtab() {
318 std::sort(HashNameMap.begin(), HashNameMap.end(), less_first());
319 HashNameMap.erase(std::unique(HashNameMap.begin(), HashNameMap.end()),
321 std::sort(AddrToMD5Map.begin(), AddrToMD5Map.end(), less_first());
322 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
326 StringRef InstrProfSymtab::getFuncName(uint64_t FuncMD5Hash) {
328 std::lower_bound(HashNameMap.begin(), HashNameMap.end(), FuncMD5Hash,
329 [](const std::pair<uint64_t, std::string> &LHS,
330 uint64_t RHS) { return LHS.first < RHS; });
331 if (Result != HashNameMap.end())
332 return Result->second;
336 struct InstrProfValueSiteRecord {
337 /// Value profiling data pairs at a given value site.
338 std::list<InstrProfValueData> ValueData;
340 InstrProfValueSiteRecord() { ValueData.clear(); }
341 template <class InputIterator>
342 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
345 /// Sort ValueData ascending by Value
346 void sortByTargetValues() {
348 [](const InstrProfValueData &left, const InstrProfValueData &right) {
349 return left.Value < right.Value;
353 /// Merge data from another InstrProfValueSiteRecord
354 /// Optionally scale merged counts by \p Weight.
355 instrprof_error mergeValueData(InstrProfValueSiteRecord &Input,
356 uint64_t Weight = 1);
359 /// Profiling information for a single function.
360 struct InstrProfRecord {
362 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
363 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
366 std::vector<uint64_t> Counts;
368 typedef std::vector<std::pair<uint64_t, uint64_t>> ValueMapType;
370 /// Return the number of value profile kinds with non-zero number
371 /// of profile sites.
372 inline uint32_t getNumValueKinds() const;
373 /// Return the number of instrumented sites for ValueKind.
374 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
375 /// Return the total number of ValueData for ValueKind.
376 inline uint32_t getNumValueData(uint32_t ValueKind) const;
377 /// Return the number of value data collected for ValueKind at profiling
379 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
380 uint32_t Site) const;
381 /// Return the array of profiled values at \p Site.
382 inline std::unique_ptr<InstrProfValueData[]>
383 getValueForSite(uint32_t ValueKind, uint32_t Site,
384 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
386 getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
387 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
388 /// Reserve space for NumValueSites sites.
389 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
390 /// Add ValueData for ValueKind at value Site.
391 void addValueData(uint32_t ValueKind, uint32_t Site,
392 InstrProfValueData *VData, uint32_t N,
393 ValueMapType *ValueMap);
395 /// Merge the counts in \p Other into this one.
396 /// Optionally scale merged counts by \p Weight.
397 instrprof_error merge(InstrProfRecord &Other, uint64_t Weight = 1);
399 /// Clear value data entries
400 void clearValueData() {
401 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
402 getValueSitesForKind(Kind).clear();
406 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
407 const std::vector<InstrProfValueSiteRecord> &
408 getValueSitesForKind(uint32_t ValueKind) const {
410 case IPVK_IndirectCallTarget:
411 return IndirectCallSites;
413 llvm_unreachable("Unknown value kind!");
415 return IndirectCallSites;
418 std::vector<InstrProfValueSiteRecord> &
419 getValueSitesForKind(uint32_t ValueKind) {
420 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
421 const_cast<const InstrProfRecord *>(this)
422 ->getValueSitesForKind(ValueKind));
425 // Map indirect call target name hash to name string.
426 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
427 ValueMapType *HashKeys);
429 // Merge Value Profile data from Src record to this record for ValueKind.
430 // Scale merged value counts by \p Weight.
431 instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
435 uint32_t InstrProfRecord::getNumValueKinds() const {
436 uint32_t NumValueKinds = 0;
437 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
438 NumValueKinds += !(getValueSitesForKind(Kind).empty());
439 return NumValueKinds;
442 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
444 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
445 getValueSitesForKind(ValueKind);
446 for (auto &SR : SiteRecords) {
447 N += SR.ValueData.size();
452 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
453 return getValueSitesForKind(ValueKind).size();
456 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
457 uint32_t Site) const {
458 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
461 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
462 uint32_t ValueKind, uint32_t Site,
463 uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
464 uint32_t N = getNumValueDataForSite(ValueKind, Site);
466 return std::unique_ptr<InstrProfValueData[]>(nullptr);
468 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
469 getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
474 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
475 uint32_t ValueKind, uint32_t Site,
476 uint64_t (*ValueMapper)(uint32_t,
479 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
480 Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
481 Dest[I].Count = V.Count;
486 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
487 std::vector<InstrProfValueSiteRecord> &ValueSites =
488 getValueSitesForKind(ValueKind);
489 ValueSites.reserve(NumValueSites);
492 inline support::endianness getHostEndianness() {
493 return sys::IsLittleEndianHost ? support::little : support::big;
496 // Include definitions for value profile data
497 #define INSTR_PROF_VALUE_PROF_DATA
498 #include "llvm/ProfileData/InstrProfData.inc"
501 * Initialize the record for runtime value profile data.
502 * Return 0 if the initialization is successful, otherwise
505 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
506 const uint16_t *NumValueSites,
507 ValueProfNode **Nodes);
509 /* Release memory allocated for the runtime record. */
510 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
512 /* Return the size of ValueProfData structure that can be used to store
513 the value profile data collected at runtime. */
514 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
516 /* Return a ValueProfData instance that stores the data collected at runtime. */
518 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
521 namespace IndexedInstrProf {
523 enum class HashT : uint32_t {
529 static inline uint64_t MD5Hash(StringRef Str) {
532 llvm::MD5::MD5Result Result;
534 // Return the least significant 8 bytes. Our MD5 implementation returns the
535 // result in little endian, so we may need to swap bytes.
536 using namespace llvm::support;
537 return endian::read<uint64_t, little, unaligned>(Result);
540 inline uint64_t ComputeHash(HashT Type, StringRef K) {
543 return IndexedInstrProf::MD5Hash(K);
545 llvm_unreachable("Unhandled hash type");
548 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
549 const uint64_t Version = INSTR_PROF_INDEX_VERSION;
550 const HashT HashType = HashT::MD5;
552 inline uint64_t ComputeHash(StringRef K) { return ComputeHash(HashType, K); }
554 // This structure defines the file header of the LLVM profile
555 // data file in indexed-format.
559 uint64_t MaxFunctionCount;
564 } // end namespace IndexedInstrProf
566 namespace RawInstrProf {
568 const uint64_t Version = INSTR_PROF_RAW_VERSION;
570 template <class IntPtrT> inline uint64_t getMagic();
571 template <> inline uint64_t getMagic<uint64_t>() {
572 return INSTR_PROF_RAW_MAGIC_64;
575 template <> inline uint64_t getMagic<uint32_t>() {
576 return INSTR_PROF_RAW_MAGIC_32;
579 // Per-function profile data header/control structure.
580 // The definition should match the structure defined in
581 // compiler-rt/lib/profile/InstrProfiling.h.
582 // It should also match the synthesized type in
583 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
584 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
585 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
586 #include "llvm/ProfileData/InstrProfData.inc"
589 // File header structure of the LLVM profile data in raw format.
590 // The definition should match the header referenced in
591 // compiler-rt/lib/profile/InstrProfilingFile.c and
592 // InstrProfilingBuffer.c.
594 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
595 #include "llvm/ProfileData/InstrProfData.inc"
598 } // end namespace RawInstrProf
602 // Profile coverage map has the following layout:
603 // [CoverageMapFileHeader]
605 // [CovMapFunctionRecord]
606 // [CovMapFunctionRecord]
609 // [Encoded Region Mapping Data]
611 template <class IntPtrT> struct CovMapFunctionRecord {
612 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
613 #include "llvm/ProfileData/InstrProfData.inc"
619 } // end namespace llvm
623 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
626 #endif // LLVM_PROFILEDATA_INSTRPROF_H_