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/Support/Endian.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MD5.h"
26 #include <system_error>
31 /// Return the name of data section containing profile counter variables.
32 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
33 return AddSegment ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
36 /// Return the name of data section containing names of instrumented
38 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
39 return AddSegment ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
42 /// Return the name of the data section containing per-function control
44 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
45 return AddSegment ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
48 /// Return the name of the section containing function coverage mapping
50 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
51 return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
54 /// Return the name prefix of variables containing instrumented function names.
55 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
57 /// Return the name prefix of variables containing per-function control data.
58 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
60 /// Return the name prefix of profile counter variables.
61 inline StringRef getInstrProfCountersVarPrefix() {
62 return "__llvm_profile_counters_";
65 /// Return the name prefix of the COMDAT group for instrumentation variables
66 /// associated with a COMDAT function.
67 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
69 /// Return the name of a covarage mapping variable (internal linkage)
70 /// for each instrumented source module. Such variables are allocated
71 /// in the __llvm_covmap section.
72 inline StringRef getCoverageMappingVarName() {
73 return "__llvm_coverage_mapping";
76 /// Return the name of function that registers all the per-function control
77 /// data at program startup time by calling __llvm_register_function. This
78 /// function has internal linkage and is called by __llvm_profile_init
79 /// runtime method. This function is not generated for these platforms:
80 /// Darwin, Linux, and FreeBSD.
81 inline StringRef getInstrProfRegFuncsName() {
82 return "__llvm_profile_register_functions";
85 /// Return the name of the runtime interface that registers per-function control
86 /// data for one instrumented function.
87 inline StringRef getInstrProfRegFuncName() {
88 return "__llvm_profile_register_function";
91 /// Return the name of the runtime initialization method that is generated by
92 /// the compiler. The function calls __llvm_profile_register_functions and
93 /// __llvm_profile_override_default_filename functions if needed. This function
94 /// has internal linkage and invoked at startup time via init_array.
95 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
97 /// Return the name of the hook variable defined in profile runtime library.
98 /// A reference to the variable causes the linker to link in the runtime
99 /// initialization module (which defines the hook variable).
100 inline StringRef getInstrProfRuntimeHookVarName() {
101 return "__llvm_profile_runtime";
104 /// Return the name of the compiler generated function that references the
105 /// runtime hook variable. The function is a weak global.
106 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
107 return "__llvm_profile_runtime_user";
110 /// Return the name of the profile runtime interface that overrides the default
111 /// profile data file name.
112 inline StringRef getInstrProfFileOverriderFuncName() {
113 return "__llvm_profile_override_default_filename";
116 const std::error_category &instrprof_category();
118 enum class instrprof_error {
124 unsupported_hash_type,
132 value_site_count_mismatch
135 inline std::error_code make_error_code(instrprof_error E) {
136 return std::error_code(static_cast<int>(E), instrprof_category());
139 enum InstrProfValueKind : uint32_t {
140 IPVK_IndirectCallTarget = 0,
142 IPVK_First = IPVK_IndirectCallTarget,
143 IPVK_Last = IPVK_IndirectCallTarget
146 struct InstrProfStringTable {
147 // Set of string values in profiling data.
148 StringSet<> StringValueSet;
149 InstrProfStringTable() { StringValueSet.clear(); }
150 // Get a pointer to internal storage of a string in set
151 const char *getStringData(StringRef Str) {
152 auto Result = StringValueSet.find(Str);
153 return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
155 // Insert a string to StringTable
156 const char *insertString(StringRef Str) {
157 auto Result = StringValueSet.insert(Str);
158 return Result.first->first().data();
162 struct InstrProfValueData {
165 // Number of times the value appears in the training run.
169 struct InstrProfValueSiteRecord {
170 /// Value profiling data pairs at a given value site.
171 std::list<InstrProfValueData> ValueData;
173 InstrProfValueSiteRecord() { ValueData.clear(); }
174 template <class InputIterator>
175 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
178 /// Sort ValueData ascending by Value
179 void sortByTargetValues() {
181 [](const InstrProfValueData &left, const InstrProfValueData &right) {
182 return left.Value < right.Value;
186 /// Merge data from another InstrProfValueSiteRecord
187 void mergeValueData(InstrProfValueSiteRecord &Input) {
188 this->sortByTargetValues();
189 Input.sortByTargetValues();
190 auto I = ValueData.begin();
191 auto IE = ValueData.end();
192 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
194 while (I != IE && I->Value < J->Value) ++I;
195 if (I != IE && I->Value == J->Value) {
196 I->Count += J->Count;
200 ValueData.insert(I, *J);
205 /// Profiling information for a single function.
206 struct InstrProfRecord {
208 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
209 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
212 std::vector<uint64_t> Counts;
214 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
216 /// Return the number of value profile kinds with non-zero number
217 /// of profile sites.
218 inline uint32_t getNumValueKinds() const;
219 /// Return the number of instrumented sites for ValueKind.
220 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
221 /// Return the total number of ValueData for ValueKind.
222 inline uint32_t getNumValueData(uint32_t ValueKind) const;
223 /// Return the number of value data collected for ValueKind at profiling
225 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
226 uint32_t Site) const;
227 inline std::unique_ptr<InstrProfValueData[]> getValueForSite(
228 uint32_t ValueKind, uint32_t Site) const;
229 /// Reserve space for NumValueSites sites.
230 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
231 /// Add ValueData for ValueKind at value Site.
232 inline void addValueData(uint32_t ValueKind, uint32_t Site,
233 InstrProfValueData *VData, uint32_t N,
234 ValueMapType *HashKeys);
235 /// Merge Value Profile ddata from Src record to this record for ValueKind.
236 inline instrprof_error mergeValueProfData(uint32_t ValueKind,
237 InstrProfRecord &Src);
239 /// Used by InstrProfWriter: update the value strings to commoned strings in
240 /// the writer instance.
241 inline void updateStrings(InstrProfStringTable *StrTab);
244 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
245 const std::vector<InstrProfValueSiteRecord> &
246 getValueSitesForKind(uint32_t ValueKind) const {
248 case IPVK_IndirectCallTarget:
249 return IndirectCallSites;
251 llvm_unreachable("Unknown value kind!");
253 return IndirectCallSites;
256 std::vector<InstrProfValueSiteRecord> &
257 getValueSitesForKind(uint32_t ValueKind) {
258 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
259 const_cast<const InstrProfRecord *>(this)
260 ->getValueSitesForKind(ValueKind));
262 // Map indirect call target name hash to name string.
263 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
264 ValueMapType *HashKeys) {
265 if (!HashKeys) return Value;
267 case IPVK_IndirectCallTarget: {
269 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
270 [](const std::pair<uint64_t, const char *> &LHS,
271 uint64_t RHS) { return LHS.first < RHS; });
272 assert(Result != HashKeys->end() &&
273 "Hash does not match any known keys\n");
274 Value = (uint64_t)Result->second;
282 uint32_t InstrProfRecord::getNumValueKinds() const {
283 uint32_t NumValueKinds = 0;
284 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
285 NumValueKinds += !(getValueSitesForKind(Kind).empty());
286 return NumValueKinds;
289 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
290 return getValueSitesForKind(ValueKind).size();
293 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
294 uint32_t Site) const {
295 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
298 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
299 uint32_t ValueKind, uint32_t Site) const {
300 uint32_t N = getNumValueDataForSite(ValueKind, Site);
301 if (N == 0) return std::unique_ptr<InstrProfValueData[]>(nullptr);
303 std::unique_ptr<InstrProfValueData[]> VD(new InstrProfValueData[N]);
305 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
314 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
315 InstrProfValueData *VData, uint32_t N,
316 ValueMapType *HashKeys) {
317 for (uint32_t I = 0; I < N; I++) {
318 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
320 std::vector<InstrProfValueSiteRecord> &ValueSites =
321 getValueSitesForKind(ValueKind);
323 ValueSites.push_back(InstrProfValueSiteRecord());
325 ValueSites.emplace_back(VData, VData + N);
328 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
329 std::vector<InstrProfValueSiteRecord> &ValueSites =
330 getValueSitesForKind(ValueKind);
331 ValueSites.reserve(NumValueSites);
334 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
335 InstrProfRecord &Src) {
336 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
337 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
338 if (ThisNumValueSites != OtherNumValueSites)
339 return instrprof_error::value_site_count_mismatch;
340 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
341 getValueSitesForKind(ValueKind);
342 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
343 Src.getValueSitesForKind(ValueKind);
344 for (uint32_t I = 0; I < ThisNumValueSites; I++)
345 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
346 return instrprof_error::success;
349 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
352 Name = StrTab->insertString(Name);
353 for (auto &VSite : IndirectCallSites)
354 for (auto &VData : VSite.ValueData)
355 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
358 namespace IndexedInstrProf {
359 enum class HashT : uint32_t {
365 static inline uint64_t MD5Hash(StringRef Str) {
368 llvm::MD5::MD5Result Result;
370 // Return the least significant 8 bytes. Our MD5 implementation returns the
371 // result in little endian, so we may need to swap bytes.
372 using namespace llvm::support;
373 return endian::read<uint64_t, little, unaligned>(Result);
376 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
379 return IndexedInstrProf::MD5Hash(K);
381 llvm_unreachable("Unhandled hash type");
384 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
385 const uint64_t Version = 3;
386 const HashT HashType = HashT::MD5;
391 uint64_t MaxFunctionCount;
396 } // end namespace IndexedInstrProf
398 namespace RawInstrProf {
400 const uint64_t Version = 1;
402 // Magic number to detect file format and endianness.
403 // Use 255 at one end, since no UTF-8 file can use that character. Avoid 0,
404 // so that utilities, like strings, don't grab it as a string. 129 is also
405 // invalid UTF-8, and high enough to be interesting.
406 // Use "lprofr" in the centre to stand for "LLVM Profile Raw", or "lprofR"
407 // for 32-bit platforms.
408 // The magic and version need to be kept in sync with
409 // projects/compiler-rt/lib/profile/InstrProfiling.c
411 template <class IntPtrT>
412 inline uint64_t getMagic();
414 inline uint64_t getMagic<uint64_t>() {
415 return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
416 uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
417 uint64_t('r') << 8 | uint64_t(129);
421 inline uint64_t getMagic<uint32_t>() {
422 return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
423 uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
424 uint64_t('R') << 8 | uint64_t(129);
427 // The definition should match the structure defined in
428 // compiler-rt/lib/profile/InstrProfiling.h.
429 // It should also match the synthesized type in
430 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
432 template <class IntPtrT>
434 const uint32_t NameSize;
435 const uint32_t NumCounters;
436 const uint64_t FuncHash;
437 const IntPtrT NamePtr;
438 const IntPtrT CounterPtr;
441 // The definition should match the header referenced in
442 // compiler-rt/lib/profile/InstrProfilingFile.c and
443 // InstrProfilingBuffer.c.
446 const uint64_t Magic;
447 const uint64_t Version;
448 const uint64_t DataSize;
449 const uint64_t CountersSize;
450 const uint64_t NamesSize;
451 const uint64_t CountersDelta;
452 const uint64_t NamesDelta;
455 } // end namespace RawInstrProf
457 } // end namespace llvm
461 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
464 #endif // LLVM_PROFILEDATA_INSTRPROF_H_