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/MD5.h"
27 #include <system_error>
36 /// Return the name of data section containing profile counter variables.
37 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
38 return AddSegment ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
41 /// Return the name of data section containing names of instrumented
43 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
44 return AddSegment ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
47 /// Return the name of the data section containing per-function control
49 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
50 return AddSegment ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
53 /// Return the name of the section containing function coverage mapping
55 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
56 return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
59 /// Return the name prefix of variables containing instrumented function names.
60 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
62 /// Return the name prefix of variables containing per-function control data.
63 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
65 /// Return the name prefix of profile counter variables.
66 inline StringRef getInstrProfCountersVarPrefix() {
67 return "__llvm_profile_counters_";
70 /// Return the name prefix of the COMDAT group for instrumentation variables
71 /// associated with a COMDAT function.
72 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
74 /// Return the name of a covarage mapping variable (internal linkage)
75 /// for each instrumented source module. Such variables are allocated
76 /// in the __llvm_covmap section.
77 inline StringRef getCoverageMappingVarName() {
78 return "__llvm_coverage_mapping";
81 /// Return the name of function that registers all the per-function control
82 /// data at program startup time by calling __llvm_register_function. This
83 /// function has internal linkage and is called by __llvm_profile_init
84 /// runtime method. This function is not generated for these platforms:
85 /// Darwin, Linux, and FreeBSD.
86 inline StringRef getInstrProfRegFuncsName() {
87 return "__llvm_profile_register_functions";
90 /// Return the name of the runtime interface that registers per-function control
91 /// data for one instrumented function.
92 inline StringRef getInstrProfRegFuncName() {
93 return "__llvm_profile_register_function";
96 /// Return the name of the runtime initialization method that is generated by
97 /// the compiler. The function calls __llvm_profile_register_functions and
98 /// __llvm_profile_override_default_filename functions if needed. This function
99 /// has internal linkage and invoked at startup time via init_array.
100 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
102 /// Return the name of the hook variable defined in profile runtime library.
103 /// A reference to the variable causes the linker to link in the runtime
104 /// initialization module (which defines the hook variable).
105 inline StringRef getInstrProfRuntimeHookVarName() {
106 return "__llvm_profile_runtime";
109 /// Return the name of the compiler generated function that references the
110 /// runtime hook variable. The function is a weak global.
111 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
112 return "__llvm_profile_runtime_user";
115 /// Return the name of the profile runtime interface that overrides the default
116 /// profile data file name.
117 inline StringRef getInstrProfFileOverriderFuncName() {
118 return "__llvm_profile_override_default_filename";
121 /// Return the modified name for function \c F suitable to be
122 /// used the key for profile lookup.
123 std::string getPGOFuncName(const Function &F);
125 /// Return the modified name for a function suitable to be
126 /// used the key for profile lookup. The function's original
127 /// name is \c RawFuncName and has linkage of type \c Linkage.
128 /// The function is defined in module \c FileName.
129 std::string getPGOFuncName(StringRef RawFuncName,
130 GlobalValue::LinkageTypes Linkage,
133 /// Create and return the global variable for function name used in PGO
134 /// instrumentation. \c FuncName is the name of the function returned
135 /// by \c getPGOFuncName call.
136 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
138 /// Create and return the global variable for function name used in PGO
139 /// instrumentation. /// \c FuncName is the name of the function
140 /// returned by \c getPGOFuncName call, \c M is the owning module,
141 /// and \c Linkage is the linkage of the instrumented function.
142 GlobalVariable *createPGOFuncNameVar(Module &M,
143 GlobalValue::LinkageTypes Linkage,
146 const std::error_category &instrprof_category();
148 enum class instrprof_error {
154 unsupported_hash_type,
162 value_site_count_mismatch
165 inline std::error_code make_error_code(instrprof_error E) {
166 return std::error_code(static_cast<int>(E), instrprof_category());
169 enum InstrProfValueKind : uint32_t {
170 IPVK_IndirectCallTarget = 0,
172 IPVK_First = IPVK_IndirectCallTarget,
173 IPVK_Last = IPVK_IndirectCallTarget
176 struct InstrProfStringTable {
177 // Set of string values in profiling data.
178 StringSet<> StringValueSet;
179 InstrProfStringTable() { StringValueSet.clear(); }
180 // Get a pointer to internal storage of a string in set
181 const char *getStringData(StringRef Str) {
182 auto Result = StringValueSet.find(Str);
183 return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
185 // Insert a string to StringTable
186 const char *insertString(StringRef Str) {
187 auto Result = StringValueSet.insert(Str);
188 return Result.first->first().data();
192 struct InstrProfValueData {
195 // Number of times the value appears in the training run.
199 struct InstrProfValueSiteRecord {
200 /// Value profiling data pairs at a given value site.
201 std::list<InstrProfValueData> ValueData;
203 InstrProfValueSiteRecord() { ValueData.clear(); }
204 template <class InputIterator>
205 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
208 /// Sort ValueData ascending by Value
209 void sortByTargetValues() {
211 [](const InstrProfValueData &left, const InstrProfValueData &right) {
212 return left.Value < right.Value;
216 /// Merge data from another InstrProfValueSiteRecord
217 void mergeValueData(InstrProfValueSiteRecord &Input) {
218 this->sortByTargetValues();
219 Input.sortByTargetValues();
220 auto I = ValueData.begin();
221 auto IE = ValueData.end();
222 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
224 while (I != IE && I->Value < J->Value)
226 if (I != IE && I->Value == J->Value) {
227 I->Count += J->Count;
231 ValueData.insert(I, *J);
236 /// Profiling information for a single function.
237 struct InstrProfRecord {
239 InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
240 : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
243 std::vector<uint64_t> Counts;
245 typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
247 /// Return the number of value profile kinds with non-zero number
248 /// of profile sites.
249 inline uint32_t getNumValueKinds() const;
250 /// Return the number of instrumented sites for ValueKind.
251 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
252 /// Return the total number of ValueData for ValueKind.
253 inline uint32_t getNumValueData(uint32_t ValueKind) const;
254 /// Return the number of value data collected for ValueKind at profiling
256 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
257 uint32_t Site) const;
258 inline std::unique_ptr<InstrProfValueData[]>
259 getValueForSite(uint32_t ValueKind, uint32_t Site) const;
260 /// Reserve space for NumValueSites sites.
261 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
262 /// Add ValueData for ValueKind at value Site.
263 inline void addValueData(uint32_t ValueKind, uint32_t Site,
264 InstrProfValueData *VData, uint32_t N,
265 ValueMapType *HashKeys);
266 /// Merge Value Profile ddata from Src record to this record for ValueKind.
267 inline instrprof_error mergeValueProfData(uint32_t ValueKind,
268 InstrProfRecord &Src);
270 /// Used by InstrProfWriter: update the value strings to commoned strings in
271 /// the writer instance.
272 inline void updateStrings(InstrProfStringTable *StrTab);
275 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
276 const std::vector<InstrProfValueSiteRecord> &
277 getValueSitesForKind(uint32_t ValueKind) const {
279 case IPVK_IndirectCallTarget:
280 return IndirectCallSites;
282 llvm_unreachable("Unknown value kind!");
284 return IndirectCallSites;
287 std::vector<InstrProfValueSiteRecord> &
288 getValueSitesForKind(uint32_t ValueKind) {
289 return const_cast<std::vector<InstrProfValueSiteRecord> &>(
290 const_cast<const InstrProfRecord *>(this)
291 ->getValueSitesForKind(ValueKind));
293 // Map indirect call target name hash to name string.
294 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
295 ValueMapType *HashKeys) {
299 case IPVK_IndirectCallTarget: {
301 std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
302 [](const std::pair<uint64_t, const char *> &LHS,
303 uint64_t RHS) { return LHS.first < RHS; });
304 assert(Result != HashKeys->end() &&
305 "Hash does not match any known keys\n");
306 Value = (uint64_t)Result->second;
314 uint32_t InstrProfRecord::getNumValueKinds() const {
315 uint32_t NumValueKinds = 0;
316 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
317 NumValueKinds += !(getValueSitesForKind(Kind).empty());
318 return NumValueKinds;
321 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
322 return getValueSitesForKind(ValueKind).size();
325 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
326 uint32_t Site) const {
327 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
330 std::unique_ptr<InstrProfValueData[]>
331 InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site) const {
332 uint32_t N = getNumValueDataForSite(ValueKind, Site);
334 return std::unique_ptr<InstrProfValueData[]>(nullptr);
336 std::unique_ptr<InstrProfValueData[]> VD(new InstrProfValueData[N]);
338 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
347 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
348 InstrProfValueData *VData, uint32_t N,
349 ValueMapType *HashKeys) {
350 for (uint32_t I = 0; I < N; I++) {
351 VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
353 std::vector<InstrProfValueSiteRecord> &ValueSites =
354 getValueSitesForKind(ValueKind);
356 ValueSites.push_back(InstrProfValueSiteRecord());
358 ValueSites.emplace_back(VData, VData + N);
361 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
362 std::vector<InstrProfValueSiteRecord> &ValueSites =
363 getValueSitesForKind(ValueKind);
364 ValueSites.reserve(NumValueSites);
367 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
368 InstrProfRecord &Src) {
369 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
370 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
371 if (ThisNumValueSites != OtherNumValueSites)
372 return instrprof_error::value_site_count_mismatch;
373 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
374 getValueSitesForKind(ValueKind);
375 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
376 Src.getValueSitesForKind(ValueKind);
377 for (uint32_t I = 0; I < ThisNumValueSites; I++)
378 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I]);
379 return instrprof_error::success;
382 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
386 Name = StrTab->insertString(Name);
387 for (auto &VSite : IndirectCallSites)
388 for (auto &VData : VSite.ValueData)
389 VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
392 namespace IndexedInstrProf {
393 enum class HashT : uint32_t {
399 static inline uint64_t MD5Hash(StringRef Str) {
402 llvm::MD5::MD5Result Result;
404 // Return the least significant 8 bytes. Our MD5 implementation returns the
405 // result in little endian, so we may need to swap bytes.
406 using namespace llvm::support;
407 return endian::read<uint64_t, little, unaligned>(Result);
410 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
413 return IndexedInstrProf::MD5Hash(K);
415 llvm_unreachable("Unhandled hash type");
418 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
419 const uint64_t Version = 3;
420 const HashT HashType = HashT::MD5;
425 uint64_t MaxFunctionCount;
430 } // end namespace IndexedInstrProf
432 namespace RawInstrProf {
434 const uint64_t Version = 1;
436 // Magic number to detect file format and endianness.
437 // Use 255 at one end, since no UTF-8 file can use that character. Avoid 0,
438 // so that utilities, like strings, don't grab it as a string. 129 is also
439 // invalid UTF-8, and high enough to be interesting.
440 // Use "lprofr" in the centre to stand for "LLVM Profile Raw", or "lprofR"
441 // for 32-bit platforms.
442 // The magic and version need to be kept in sync with
443 // projects/compiler-rt/lib/profile/InstrProfiling.c
445 template <class IntPtrT>
446 inline uint64_t getMagic();
448 inline uint64_t getMagic<uint64_t>() {
449 return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
450 uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
451 uint64_t('r') << 8 | uint64_t(129);
455 inline uint64_t getMagic<uint32_t>() {
456 return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
457 uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
458 uint64_t('R') << 8 | uint64_t(129);
461 // The definition should match the structure defined in
462 // compiler-rt/lib/profile/InstrProfiling.h.
463 // It should also match the synthesized type in
464 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
466 template <class IntPtrT> struct ProfileData {
467 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
468 #include "llvm/ProfileData/InstrProfData.inc"
471 // The definition should match the header referenced in
472 // compiler-rt/lib/profile/InstrProfilingFile.c and
473 // InstrProfilingBuffer.c.
476 const uint64_t Magic;
477 const uint64_t Version;
478 const uint64_t DataSize;
479 const uint64_t CountersSize;
480 const uint64_t NamesSize;
481 const uint64_t CountersDelta;
482 const uint64_t NamesDelta;
485 } // end namespace RawInstrProf
490 template <class IntPtrT> struct CovMapFunctionRecord {
491 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
492 #include "llvm/ProfileData/InstrProfData.inc"
498 } // end namespace llvm
502 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
505 #endif // LLVM_PROFILEDATA_INSTRPROF_H_