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 "__llvm_profile_name_"; }
75 /// Return the name prefix of variables containing per-function control data.
76 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
78 /// Return the name prefix of profile counter variables.
79 inline StringRef getInstrProfCountersVarPrefix() {
80 return "__llvm_profile_counters_";
83 /// Return the name prefix of the COMDAT group for instrumentation variables
84 /// associated with a COMDAT function.
85 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
87 /// Return the name of a covarage mapping variable (internal linkage)
88 /// for each instrumented source module. Such variables are allocated
89 /// in the __llvm_covmap section.
90 inline StringRef getCoverageMappingVarName() {
91 return "__llvm_coverage_mapping";
94 /// Return the name of function that registers all the per-function control
95 /// data at program startup time by calling __llvm_register_function. This
96 /// function has internal linkage and is called by __llvm_profile_init
97 /// runtime method. This function is not generated for these platforms:
98 /// Darwin, Linux, and FreeBSD.
99 inline StringRef getInstrProfRegFuncsName() {
100 return "__llvm_profile_register_functions";
103 /// Return the name of the runtime interface that registers per-function control
104 /// data for one instrumented function.
105 inline StringRef getInstrProfRegFuncName() {
106 return "__llvm_profile_register_function";
109 /// Return the name of the runtime initialization method that is generated by
110 /// the compiler. The function calls __llvm_profile_register_functions and
111 /// __llvm_profile_override_default_filename functions if needed. This function
112 /// has internal linkage and invoked at startup time via init_array.
113 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
115 /// Return the name of the hook variable defined in profile runtime library.
116 /// A reference to the variable causes the linker to link in the runtime
117 /// initialization module (which defines the hook variable).
118 inline StringRef getInstrProfRuntimeHookVarName() {
119 return "__llvm_profile_runtime";
122 /// Return the name of the compiler generated function that references the
123 /// runtime hook variable. The function is a weak global.
124 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
125 return "__llvm_profile_runtime_user";
128 /// Return the name of the profile runtime interface that overrides the default
129 /// profile data file name.
130 inline StringRef getInstrProfFileOverriderFuncName() {
131 return "__llvm_profile_override_default_filename";
134 /// Return the modified name for function \c F suitable to be
135 /// used the key for profile lookup.
136 std::string getPGOFuncName(const Function &F,
137 uint64_t Version = INSTR_PROF_INDEX_VERSION);
139 /// Return the modified name for a function suitable to be
140 /// used the key for profile lookup. The function's original
141 /// name is \c RawFuncName and has linkage of type \c Linkage.
142 /// The function is defined in module \c FileName.
143 std::string getPGOFuncName(StringRef RawFuncName,
144 GlobalValue::LinkageTypes Linkage,
146 uint64_t Version = INSTR_PROF_INDEX_VERSION);
148 /// Create and return the global variable for function name used in PGO
149 /// instrumentation. \c FuncName is the name of the function returned
150 /// by \c getPGOFuncName call.
151 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
153 /// Create and return the global variable for function name used in PGO
154 /// instrumentation. /// \c FuncName is the name of the function
155 /// returned by \c getPGOFuncName call, \c M is the owning module,
156 /// and \c Linkage is the linkage of the instrumented function.
157 GlobalVariable *createPGOFuncNameVar(Module &M,
158 GlobalValue::LinkageTypes Linkage,
161 const std::error_category &instrprof_category();
163 enum class instrprof_error {
170 unsupported_hash_type,
178 value_site_count_mismatch
181 inline std::error_code make_error_code(instrprof_error E) {
182 return std::error_code(static_cast<int>(E), instrprof_category());
185 enum InstrProfValueKind : uint32_t {
186 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
187 #include "llvm/ProfileData/InstrProfData.inc"
190 struct InstrProfStringTable {
191 // Set of string values in profiling data.
192 StringSet<> StringValueSet;
193 InstrProfStringTable() { StringValueSet.clear(); }
194 // Get a pointer to internal storage of a string in set
195 const char *getStringData(StringRef Str) {
196 auto Result = StringValueSet.find(Str);
197 return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
199 // Insert a string to StringTable
200 const char *insertString(StringRef Str) {
201 auto Result = StringValueSet.insert(Str);
202 return Result.first->first().data();
206 struct InstrProfValueSiteRecord {
207 /// Value profiling data pairs at a given value site.
208 std::list<InstrProfValueData> ValueData;
210 InstrProfValueSiteRecord() { ValueData.clear(); }
211 template <class InputIterator>
212 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
215 /// Sort ValueData ascending by Value
216 void sortByTargetValues() {
218 [](const InstrProfValueData &left, const InstrProfValueData &right) {
219 return left.Value < right.Value;
223 /// Merge data from another InstrProfValueSiteRecord
224 void mergeValueData(InstrProfValueSiteRecord &Input) {
225 this->sortByTargetValues();
226 Input.sortByTargetValues();
227 auto I = ValueData.begin();
228 auto IE = ValueData.end();
229 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
231 while (I != IE && I->Value < J->Value)
233 if (I != IE && I->Value == J->Value) {
234 I->Count = SaturatingAdd(I->Count, J->Count);
238 ValueData.insert(I, *J);
243 /// Profiling information for a single function.
244 struct InstrProfRecord {
246 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
247 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
250 std::vector<uint64_t> Counts;
252 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
254 /// Return the number of value profile kinds with non-zero number
255 /// of profile sites.
256 inline uint32_t getNumValueKinds() const;
257 /// Return the number of instrumented sites for ValueKind.
258 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
259 /// Return the total number of ValueData for ValueKind.
260 inline uint32_t getNumValueData(uint32_t ValueKind) const;
261 /// Return the number of value data collected for ValueKind at profiling
263 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
264 uint32_t Site) const;
265 /// Return the array of profiled values at \p Site.
266 inline std::unique_ptr<InstrProfValueData[]>
267 getValueForSite(uint32_t ValueKind, uint32_t Site,
268 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
270 getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
271 uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
272 /// Reserve space for NumValueSites sites.
273 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
274 /// Add ValueData for ValueKind at value Site.
275 inline void addValueData(uint32_t ValueKind, uint32_t Site,
276 InstrProfValueData *VData, uint32_t N,
277 ValueMapType *HashKeys);
279 /// Merge the counts in \p Other into this one.
280 inline instrprof_error merge(InstrProfRecord &Other);
282 /// Used by InstrProfWriter: update the value strings to commoned strings in
283 /// the writer instance.
284 inline void updateStrings(InstrProfStringTable *StrTab);
286 /// Clear value data entries
287 inline void clearValueData() {
288 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
289 getValueSitesForKind(Kind).clear();
293 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
294 const std::vector<InstrProfValueSiteRecord> &
295 getValueSitesForKind(uint32_t ValueKind) const {
297 case IPVK_IndirectCallTarget:
298 return IndirectCallSites;
300 llvm_unreachable("Unknown value kind!");
302 return IndirectCallSites;
305 std::vector<InstrProfValueSiteRecord> &
306 getValueSitesForKind(uint32_t ValueKind) {
307 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
308 const_cast<const InstrProfRecord *>(this)
309 ->getValueSitesForKind(ValueKind));
312 // Map indirect call target name hash to name string.
313 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
314 ValueMapType *HashKeys) {
318 case IPVK_IndirectCallTarget: {
320 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
321 [](const std::pair<uint64_t, const char *> &LHS,
322 uint64_t RHS) { return LHS.first < RHS; });
323 if (Result != HashKeys->end())
324 Value = (uint64_t)Result->second;
331 // Merge Value Profile data from Src record to this record for ValueKind.
332 instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src) {
333 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
334 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
335 if (ThisNumValueSites != OtherNumValueSites)
336 return instrprof_error::value_site_count_mismatch;
337 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
338 getValueSitesForKind(ValueKind);
339 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
340 Src.getValueSitesForKind(ValueKind);
341 for (uint32_t I = 0; I < ThisNumValueSites; I++)
342 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
343 return instrprof_error::success;
347 uint32_t InstrProfRecord::getNumValueKinds() const {
348 uint32_t NumValueKinds = 0;
349 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
350 NumValueKinds += !(getValueSitesForKind(Kind).empty());
351 return NumValueKinds;
354 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
356 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
357 getValueSitesForKind(ValueKind);
358 for (auto &SR : SiteRecords) {
359 N += SR.ValueData.size();
364 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
365 return getValueSitesForKind(ValueKind).size();
368 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
369 uint32_t Site) const {
370 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
373 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
374 uint32_t ValueKind, uint32_t Site,
375 uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
376 uint32_t N = getNumValueDataForSite(ValueKind, Site);
378 return std::unique_ptr<InstrProfValueData[]>(nullptr);
380 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
381 getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
386 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
387 uint32_t ValueKind, uint32_t Site,
388 uint64_t (*ValueMapper)(uint32_t,
391 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
392 Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
393 Dest[I].Count = V.Count;
398 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
399 InstrProfValueData *VData, uint32_t N,
400 ValueMapType *HashKeys) {
401 for (uint32_t I = 0; I < N; I++) {
402 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
404 std::vector<InstrProfValueSiteRecord> &ValueSites =
405 getValueSitesForKind(ValueKind);
407 ValueSites.push_back(InstrProfValueSiteRecord());
409 ValueSites.emplace_back(VData, VData + N);
412 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
413 std::vector<InstrProfValueSiteRecord> &ValueSites =
414 getValueSitesForKind(ValueKind);
415 ValueSites.reserve(NumValueSites);
418 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
422 Name = StrTab->insertString(Name);
423 for (auto &VSite : IndirectCallSites)
424 for (auto &VData : VSite.ValueData)
425 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
428 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other) {
429 // If the number of counters doesn't match we either have bad data
430 // or a hash collision.
431 if (Counts.size() != Other.Counts.size())
432 return instrprof_error::count_mismatch;
434 instrprof_error Result = instrprof_error::success;
436 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
437 bool ResultOverflowed;
438 Counts[I] = SaturatingAdd(Counts[I], Other.Counts[I], &ResultOverflowed);
439 if (ResultOverflowed)
440 Result = instrprof_error::counter_overflow;
443 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
444 instrprof_error MergeValueResult = mergeValueProfData(Kind, Other);
445 if (MergeValueResult != instrprof_error::success)
446 Result = MergeValueResult;
452 inline support::endianness getHostEndianness() {
453 return sys::IsLittleEndianHost ? support::little : support::big;
457 // Include definitions for value profile data
458 #define INSTR_PROF_VALUE_PROF_DATA
459 #include "llvm/ProfileData/InstrProfData.inc"
462 * Initialize the record for runtime value profile data.
463 * Return 0 if the initialization is successful, otherwise
466 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
467 const uint16_t *NumValueSites,
468 ValueProfNode **Nodes);
470 /* Release memory allocated for the runtime record. */
471 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
473 /* Return the size of ValueProfData structure that can be used to store
474 the value profile data collected at runtime. */
475 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
477 /* Return a ValueProfData instance that stores the data collected at runtime. */
479 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
482 namespace IndexedInstrProf {
484 enum class HashT : uint32_t {
490 static inline uint64_t MD5Hash(StringRef Str) {
493 llvm::MD5::MD5Result Result;
495 // Return the least significant 8 bytes. Our MD5 implementation returns the
496 // result in little endian, so we may need to swap bytes.
497 using namespace llvm::support;
498 return endian::read<uint64_t, little, unaligned>(Result);
501 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
504 return IndexedInstrProf::MD5Hash(K);
506 llvm_unreachable("Unhandled hash type");
509 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
510 const uint64_t Version = INSTR_PROF_INDEX_VERSION;
511 const HashT HashType = HashT::MD5;
513 // This structure defines the file header of the LLVM profile
514 // data file in indexed-format.
518 uint64_t MaxFunctionCount;
523 } // end namespace IndexedInstrProf
525 namespace RawInstrProf {
527 const uint64_t Version = INSTR_PROF_RAW_VERSION;
529 template <class IntPtrT> inline uint64_t getMagic();
530 template <> inline uint64_t getMagic<uint64_t>() {
531 return INSTR_PROF_RAW_MAGIC_64;
534 template <> inline uint64_t getMagic<uint32_t>() {
535 return INSTR_PROF_RAW_MAGIC_32;
538 // Per-function profile data header/control structure.
539 // The definition should match the structure defined in
540 // compiler-rt/lib/profile/InstrProfiling.h.
541 // It should also match the synthesized type in
542 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
543 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
544 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
545 #include "llvm/ProfileData/InstrProfData.inc"
548 // File header structure of the LLVM profile data in raw format.
549 // The definition should match the header referenced in
550 // compiler-rt/lib/profile/InstrProfilingFile.c and
551 // InstrProfilingBuffer.c.
553 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
554 #include "llvm/ProfileData/InstrProfData.inc"
557 } // end namespace RawInstrProf
561 // Profile coverage map has the following layout:
562 // [CoverageMapFileHeader]
564 // [CovMapFunctionRecord]
565 // [CovMapFunctionRecord]
568 // [Encoded Region Mapping Data]
570 template <class IntPtrT> struct CovMapFunctionRecord {
571 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
572 #include "llvm/ProfileData/InstrProfData.inc"
578 } // end namespace llvm
582 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
585 #endif // LLVM_PROFILEDATA_INSTRPROF_H_