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/StringRef.h"
20 #include "llvm/ADT/StringSet.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ErrorOr.h"
25 #include "llvm/Support/MD5.h"
28 #include <system_error>
37 /// Return the name of data section containing profile counter variables.
38 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
39 return AddSegment ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
42 /// Return the name of data section containing names of instrumented
44 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
45 return AddSegment ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
48 /// Return the name of the data section containing per-function control
50 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
51 return AddSegment ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
54 /// Return the name of the section containing function coverage mapping
56 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
57 return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
60 /// Return the name prefix of variables containing instrumented function names.
61 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
63 /// Return the name prefix of variables containing per-function control data.
64 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
66 /// Return the name prefix of profile counter variables.
67 inline StringRef getInstrProfCountersVarPrefix() {
68 return "__llvm_profile_counters_";
71 /// Return the name prefix of the COMDAT group for instrumentation variables
72 /// associated with a COMDAT function.
73 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
75 /// Return the name of a covarage mapping variable (internal linkage)
76 /// for each instrumented source module. Such variables are allocated
77 /// in the __llvm_covmap section.
78 inline StringRef getCoverageMappingVarName() {
79 return "__llvm_coverage_mapping";
82 /// Return the name of function that registers all the per-function control
83 /// data at program startup time by calling __llvm_register_function. This
84 /// function has internal linkage and is called by __llvm_profile_init
85 /// runtime method. This function is not generated for these platforms:
86 /// Darwin, Linux, and FreeBSD.
87 inline StringRef getInstrProfRegFuncsName() {
88 return "__llvm_profile_register_functions";
91 /// Return the name of the runtime interface that registers per-function control
92 /// data for one instrumented function.
93 inline StringRef getInstrProfRegFuncName() {
94 return "__llvm_profile_register_function";
97 /// Return the name of the runtime initialization method that is generated by
98 /// the compiler. The function calls __llvm_profile_register_functions and
99 /// __llvm_profile_override_default_filename functions if needed. This function
100 /// has internal linkage and invoked at startup time via init_array.
101 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
103 /// Return the name of the hook variable defined in profile runtime library.
104 /// A reference to the variable causes the linker to link in the runtime
105 /// initialization module (which defines the hook variable).
106 inline StringRef getInstrProfRuntimeHookVarName() {
107 return "__llvm_profile_runtime";
110 /// Return the name of the compiler generated function that references the
111 /// runtime hook variable. The function is a weak global.
112 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
113 return "__llvm_profile_runtime_user";
116 /// Return the name of the profile runtime interface that overrides the default
117 /// profile data file name.
118 inline StringRef getInstrProfFileOverriderFuncName() {
119 return "__llvm_profile_override_default_filename";
122 /// Return the modified name for function \c F suitable to be
123 /// used the key for profile lookup.
124 std::string getPGOFuncName(const Function &F);
126 /// Return the modified name for a function suitable to be
127 /// used the key for profile lookup. The function's original
128 /// name is \c RawFuncName and has linkage of type \c Linkage.
129 /// The function is defined in module \c FileName.
130 std::string getPGOFuncName(StringRef RawFuncName,
131 GlobalValue::LinkageTypes Linkage,
134 /// Create and return the global variable for function name used in PGO
135 /// instrumentation. \c FuncName is the name of the function returned
136 /// by \c getPGOFuncName call.
137 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
139 /// Create and return the global variable for function name used in PGO
140 /// instrumentation. /// \c FuncName is the name of the function
141 /// returned by \c getPGOFuncName call, \c M is the owning module,
142 /// and \c Linkage is the linkage of the instrumented function.
143 GlobalVariable *createPGOFuncNameVar(Module &M,
144 GlobalValue::LinkageTypes Linkage,
147 const std::error_category &instrprof_category();
149 enum class instrprof_error {
156 unsupported_hash_type,
164 value_site_count_mismatch
167 inline std::error_code make_error_code(instrprof_error E) {
168 return std::error_code(static_cast<int>(E), instrprof_category());
171 enum InstrProfValueKind : uint32_t {
172 IPVK_IndirectCallTarget = 0,
174 IPVK_First = IPVK_IndirectCallTarget,
175 IPVK_Last = IPVK_IndirectCallTarget
178 struct InstrProfStringTable {
179 // Set of string values in profiling data.
180 StringSet<> StringValueSet;
181 InstrProfStringTable() { StringValueSet.clear(); }
182 // Get a pointer to internal storage of a string in set
183 const char *getStringData(StringRef Str) {
184 auto Result = StringValueSet.find(Str);
185 return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
187 // Insert a string to StringTable
188 const char *insertString(StringRef Str) {
189 auto Result = StringValueSet.insert(Str);
190 return Result.first->first().data();
194 struct InstrProfValueData {
197 // Number of times the value appears in the training run.
201 struct InstrProfValueSiteRecord {
202 /// Value profiling data pairs at a given value site.
203 std::list<InstrProfValueData> ValueData;
205 InstrProfValueSiteRecord() { ValueData.clear(); }
206 template <class InputIterator>
207 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
210 /// Sort ValueData ascending by Value
211 void sortByTargetValues() {
213 [](const InstrProfValueData &left, const InstrProfValueData &right) {
214 return left.Value < right.Value;
218 /// Merge data from another InstrProfValueSiteRecord
219 void mergeValueData(InstrProfValueSiteRecord &Input) {
220 this->sortByTargetValues();
221 Input.sortByTargetValues();
222 auto I = ValueData.begin();
223 auto IE = ValueData.end();
224 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
226 while (I != IE && I->Value < J->Value)
228 if (I != IE && I->Value == J->Value) {
229 I->Count += J->Count;
233 ValueData.insert(I, *J);
238 /// Profiling information for a single function.
239 struct InstrProfRecord {
241 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
242 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
245 std::vector<uint64_t> Counts;
247 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
249 /// Return the number of value profile kinds with non-zero number
250 /// of profile sites.
251 inline uint32_t getNumValueKinds() const;
252 /// Return the number of instrumented sites for ValueKind.
253 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
254 /// Return the total number of ValueData for ValueKind.
255 inline uint32_t getNumValueData(uint32_t ValueKind) const;
256 /// Return the number of value data collected for ValueKind at profiling
258 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
259 uint32_t Site) const;
260 inline std::unique_ptr<InstrProfValueData[]>
261 getValueForSite(uint32_t ValueKind, uint32_t Site) const;
262 /// Reserve space for NumValueSites sites.
263 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
264 /// Add ValueData for ValueKind at value Site.
265 inline void addValueData(uint32_t ValueKind, uint32_t Site,
266 InstrProfValueData *VData, uint32_t N,
267 ValueMapType *HashKeys);
268 /// Merge Value Profile data from Src record to this record for ValueKind.
269 inline instrprof_error mergeValueProfData(uint32_t ValueKind,
270 InstrProfRecord &Src);
272 /// Used by InstrProfWriter: update the value strings to commoned strings in
273 /// the writer instance.
274 inline void updateStrings(InstrProfStringTable *StrTab);
276 /// Clear value data entries
277 inline void clearValueData() {
278 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
279 getValueSitesForKind(Kind).clear();
283 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
284 const std::vector<InstrProfValueSiteRecord> &
285 getValueSitesForKind(uint32_t ValueKind) const {
287 case IPVK_IndirectCallTarget:
288 return IndirectCallSites;
290 llvm_unreachable("Unknown value kind!");
292 return IndirectCallSites;
295 std::vector<InstrProfValueSiteRecord> &
296 getValueSitesForKind(uint32_t ValueKind) {
297 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
298 const_cast<const InstrProfRecord *>(this)
299 ->getValueSitesForKind(ValueKind));
302 // Map indirect call target name hash to name string.
303 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
304 ValueMapType *HashKeys) {
308 case IPVK_IndirectCallTarget: {
310 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
311 [](const std::pair<uint64_t, const char *> &LHS,
312 uint64_t RHS) { return LHS.first < RHS; });
313 if (Result != HashKeys->end())
314 Value = (uint64_t)Result->second;
322 uint32_t InstrProfRecord::getNumValueKinds() const {
323 uint32_t NumValueKinds = 0;
324 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
325 NumValueKinds += !(getValueSitesForKind(Kind).empty());
326 return NumValueKinds;
329 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
331 const std::vector<InstrProfValueSiteRecord> &SiteRecords =
332 getValueSitesForKind(ValueKind);
333 for (auto &SR : SiteRecords) {
334 N += SR.ValueData.size();
339 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
340 return getValueSitesForKind(ValueKind).size();
343 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
344 uint32_t Site) const {
345 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
348 std::unique_ptr<InstrProfValueData[]>
349 InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site) const {
350 uint32_t N = getNumValueDataForSite(ValueKind, Site);
352 return std::unique_ptr<InstrProfValueData[]>(nullptr);
354 std::unique_ptr<InstrProfValueData[]> VD(new InstrProfValueData[N]);
356 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
365 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
366 InstrProfValueData *VData, uint32_t N,
367 ValueMapType *HashKeys) {
368 for (uint32_t I = 0; I < N; I++) {
369 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
371 std::vector<InstrProfValueSiteRecord> &ValueSites =
372 getValueSitesForKind(ValueKind);
374 ValueSites.push_back(InstrProfValueSiteRecord());
376 ValueSites.emplace_back(VData, VData + N);
379 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
380 std::vector<InstrProfValueSiteRecord> &ValueSites =
381 getValueSitesForKind(ValueKind);
382 ValueSites.reserve(NumValueSites);
385 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
386 InstrProfRecord &Src) {
387 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
388 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
389 if (ThisNumValueSites != OtherNumValueSites)
390 return instrprof_error::value_site_count_mismatch;
391 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
392 getValueSitesForKind(ValueKind);
393 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
394 Src.getValueSitesForKind(ValueKind);
395 for (uint32_t I = 0; I < ThisNumValueSites; I++)
396 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
397 return instrprof_error::success;
400 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
404 Name = StrTab->insertString(Name);
405 for (auto &VSite : IndirectCallSites)
406 for (auto &VData : VSite.ValueData)
407 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
410 inline support::endianness getHostEndianness() {
411 return sys::IsLittleEndianHost ? support::little : support::big;
414 /// This is the header of the data structure that defines the on-disk
415 /// layout of the value profile data of a particular kind for one function.
416 struct ValueProfRecord {
417 // The kind of the value profile record.
419 // The number of value profile sites. It is guaranteed to be non-zero;
420 // otherwise the record for this kind won't be emitted.
421 uint32_t NumValueSites;
422 // The first element of the array that stores the number of profiled
423 // values for each value site. The size of the array is NumValueSites.
424 // Since NumValueSites is greater than zero, there is at least one
425 // element in the array.
426 uint8_t SiteCountArray[1];
428 // The fake declaration is for documentation purpose only.
429 // Align the start of next field to be on 8 byte boundaries.
430 // uint8_t Padding[X];
432 // The array of value profile data. The size of the array is the sum
433 // of all elements in SiteCountArray[].
434 // InstrProfValueData ValueData[];
436 /// Return the \c ValueProfRecord header size including the padding bytes.
437 static uint32_t getHeaderSize(uint32_t NumValueSites);
438 /// Return the total size of the value profile record including the
439 /// header and the value data.
440 static uint32_t getSize(uint32_t NumValueSites, uint32_t NumValueData);
441 /// Return the total size of the value profile record including the
442 /// header and the value data.
443 uint32_t getSize() const { return getSize(NumValueSites, getNumValueData()); }
444 /// Use this method to advance to the next \c ValueProfRecord.
445 ValueProfRecord *getNext();
446 /// Return the pointer to the first value profile data.
447 InstrProfValueData *getValueData();
448 /// Return the number of value sites.
449 uint32_t getNumValueSites() const { return NumValueSites; }
450 /// Return the number of value data.
451 uint32_t getNumValueData() const;
452 /// Read data from this record and save it to Record.
453 void deserializeTo(InstrProfRecord &Record,
454 InstrProfRecord::ValueMapType *VMap);
455 /// Extract data from \c Record and serialize into this instance.
456 void serializeFrom(const InstrProfRecord &Record, uint32_t ValueKind,
457 uint32_t NumValueSites);
458 /// In-place byte swap:
459 /// Do byte swap for this instance. \c Old is the original order before
460 /// the swap, and \c New is the New byte order.
461 void swapBytes(support::endianness Old, support::endianness New);
464 /// Per-function header/control data structure for value profiling
465 /// data in indexed format.
466 struct ValueProfData {
467 // Total size in bytes including this field. It must be a multiple
468 // of sizeof(uint64_t).
470 // The number of value profile kinds that has value profile data.
471 // In this implementation, a value profile kind is considered to
472 // have profile data if the number of value profile sites for the
473 // kind is not zero. More aggressively, the implementation can
474 // choose to check the actual data value: if none of the value sites
475 // has any profiled values, the kind can be skipped.
476 uint32_t NumValueKinds;
478 // Following are a sequence of variable length records. The prefix/header
479 // of each record is defined by ValueProfRecord type. The number of
480 // records is NumValueKinds.
481 // ValueProfRecord Record_1;
482 // ValueProfRecord Record_N;
484 /// Return the total size in bytes of the on-disk value profile data
485 /// given the data stored in Record.
486 static uint32_t getSize(const InstrProfRecord &Record);
487 /// Return a pointer to \c ValueProfData instance ready to be streamed.
488 static std::unique_ptr<ValueProfData>
489 serializeFrom(const InstrProfRecord &Record);
490 /// Return a pointer to \c ValueProfileData instance ready to be read.
491 /// All data in the instance are properly byte swapped. The input
492 /// data is assumed to be in little endian order.
493 static ErrorOr<std::unique_ptr<ValueProfData>>
494 getValueProfData(const unsigned char *D, const unsigned char *const BufferEnd,
495 support::endianness SrcDataEndianness);
496 /// Swap byte order from \c Endianness order to host byte order.
497 void swapBytesToHost(support::endianness Endianness);
498 /// Swap byte order from host byte order to \c Endianness order.
499 void swapBytesFromHost(support::endianness Endianness);
500 /// Return the total size of \c ValueProfileData.
501 uint32_t getSize() const { return TotalSize; }
502 /// Read data from this data and save it to \c Record.
503 void deserializeTo(InstrProfRecord &Record,
504 InstrProfRecord::ValueMapType *VMap);
505 /// Return the first \c ValueProfRecord instance.
506 ValueProfRecord *getFirstValueProfRecord();
509 namespace IndexedInstrProf {
511 enum class HashT : uint32_t {
517 static inline uint64_t MD5Hash(StringRef Str) {
520 llvm::MD5::MD5Result Result;
522 // Return the least significant 8 bytes. Our MD5 implementation returns the
523 // result in little endian, so we may need to swap bytes.
524 using namespace llvm::support;
525 return endian::read<uint64_t, little, unaligned>(Result);
528 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
531 return IndexedInstrProf::MD5Hash(K);
533 llvm_unreachable("Unhandled hash type");
536 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
537 const uint64_t Version = 3;
538 const HashT HashType = HashT::MD5;
540 // This structure defines the file header of the LLVM profile
541 // data file in indexed-format.
545 uint64_t MaxFunctionCount;
550 } // end namespace IndexedInstrProf
552 namespace RawInstrProf {
554 const uint64_t Version = 2;
556 // Magic number to detect file format and endianness.
557 // Use 255 at one end, since no UTF-8 file can use that character. Avoid 0,
558 // so that utilities, like strings, don't grab it as a string. 129 is also
559 // invalid UTF-8, and high enough to be interesting.
560 // Use "lprofr" in the centre to stand for "LLVM Profile Raw", or "lprofR"
561 // for 32-bit platforms.
562 // The magic and version need to be kept in sync with
563 // projects/compiler-rt/lib/profile/InstrProfiling.c
565 template <class IntPtrT>
566 inline uint64_t getMagic();
568 inline uint64_t getMagic<uint64_t>() {
569 return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
570 uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
571 uint64_t('r') << 8 | uint64_t(129);
575 inline uint64_t getMagic<uint32_t>() {
576 return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
577 uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
578 uint64_t('R') << 8 | uint64_t(129);
581 // Per-function profile data header/control structure.
582 // The definition should match the structure defined in
583 // compiler-rt/lib/profile/InstrProfiling.h.
584 // It should also match the synthesized type in
585 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
586 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
587 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
588 #include "llvm/ProfileData/InstrProfData.inc"
591 // File header structure of the LLVM profile data in raw format.
592 // The definition should match the header referenced in
593 // compiler-rt/lib/profile/InstrProfilingFile.c and
594 // InstrProfilingBuffer.c.
596 const uint64_t Magic;
597 const uint64_t Version;
598 const uint64_t DataSize;
599 const uint64_t CountersSize;
600 const uint64_t NamesSize;
601 const uint64_t CountersDelta;
602 const uint64_t NamesDelta;
603 const uint64_t ValueKindLast;
604 const uint64_t ValueDataSize;
605 const uint64_t ValueDataDelta;
608 } // end namespace RawInstrProf
612 // Profile coverage map has the following layout:
613 // [CoverageMapFileHeader]
615 // [CovMapFunctionRecord]
616 // [CovMapFunctionRecord]
619 // [Encoded Region Mapping Data]
621 template <class IntPtrT> struct CovMapFunctionRecord {
622 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
623 #include "llvm/ProfileData/InstrProfData.inc"
629 } // end namespace llvm
633 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
636 #endif // LLVM_PROFILEDATA_INSTRPROF_H_