[PGO] Indexed Prof Reader refactoring (NFC)
[oota-llvm.git] / include / llvm / ProfileData / InstrProf.h
1 //=-- InstrProf.h - Instrumented profiling format support ---------*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_PROFILEDATA_INSTRPROF_H_
17 #define LLVM_PROFILEDATA_INSTRPROF_H_
18
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"
24 #include <cstdint>
25 #include <list>
26 #include <system_error>
27 #include <vector>
28
29 namespace llvm {
30
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";
34 }
35
36 /// Return the name of data section containing names of instrumented
37 /// functions.
38 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
39   return AddSegment ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
40 }
41
42 /// Return the name of the data section containing per-function control
43 /// data.
44 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
45   return AddSegment ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
46 }
47
48 /// Return the name of the section containing function coverage mapping
49 /// data.
50 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
51   return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
52 }
53
54 /// Return the name prefix of variables containing instrumented function names.
55 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
56
57 /// Return the name prefix of variables containing per-function control data.
58 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
59
60 /// Return the name prefix of profile counter variables.
61 inline StringRef getInstrProfCountersVarPrefix() {
62   return "__llvm_profile_counters_";
63 }
64
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_"; }
68
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";
74 }
75
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";
83 }
84
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";
89 }
90
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"; }
96
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";
102 }
103
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";
108 }
109
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";
114 }
115
116 const std::error_category &instrprof_category();
117
118 enum class instrprof_error {
119   success = 0,
120   eof,
121   bad_magic,
122   bad_header,
123   unsupported_version,
124   unsupported_hash_type,
125   too_large,
126   truncated,
127   malformed,
128   unknown_function,
129   hash_mismatch,
130   count_mismatch,
131   counter_overflow,
132   value_site_count_mismatch
133 };
134
135 inline std::error_code make_error_code(instrprof_error E) {
136   return std::error_code(static_cast<int>(E), instrprof_category());
137 }
138
139 enum InstrProfValueKind : uint32_t {
140   IPVK_IndirectCallTarget = 0,
141
142   IPVK_First = IPVK_IndirectCallTarget,
143   IPVK_Last = IPVK_IndirectCallTarget
144 };
145
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();
154   }
155   // Insert a string to StringTable
156   const char *insertString(StringRef Str) {
157     auto Result = StringValueSet.insert(Str);
158     return Result.first->first().data();
159   }
160 };
161
162 struct InstrProfValueSiteRecord {
163   /// Typedef for a single TargetValue-NumTaken pair.
164   typedef std::pair<uint64_t, uint64_t> ValueDataPair;
165   /// Value profiling data pairs at a given value site.
166   std::list<ValueDataPair> ValueData;
167
168   InstrProfValueSiteRecord() { ValueData.clear(); }
169
170   /// Sort ValueData ascending by TargetValue
171   void sortByTargetValues() {
172     ValueData.sort([](const ValueDataPair &left, const ValueDataPair &right) {
173       return left.first < right.first;
174     });
175   }
176
177   /// Merge data from another InstrProfValueSiteRecord
178   void mergeValueData(InstrProfValueSiteRecord &Input) {
179     this->sortByTargetValues();
180     Input.sortByTargetValues();
181     auto I = ValueData.begin();
182     auto IE = ValueData.end();
183     for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
184          ++J) {
185       while (I != IE && I->first < J->first)
186         ++I;
187       if (I != IE && I->first == J->first) {
188         I->second += J->second;
189         ++I;
190         continue;
191       }
192       ValueData.insert(I, *J);
193     }
194   }
195 };
196
197 /// Profiling information for a single function.
198 struct InstrProfRecord {
199   InstrProfRecord() {}
200   InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
201       : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
202   StringRef Name;
203   uint64_t Hash;
204   std::vector<uint64_t> Counts;
205   std::vector<InstrProfValueSiteRecord> IndirectCallSites;
206
207   const std::vector<InstrProfValueSiteRecord> &
208   getValueSitesForKind(uint32_t ValueKind) const {
209     switch (ValueKind) {
210     case IPVK_IndirectCallTarget:
211       return IndirectCallSites;
212     }
213     llvm_unreachable("Unknown value kind!");
214   }
215
216   std::vector<InstrProfValueSiteRecord> &
217   getValueSitesForKind(uint32_t ValueKind) {
218     return const_cast<std::vector<InstrProfValueSiteRecord> &>(
219         const_cast<const InstrProfRecord *>(this)
220             ->getValueSitesForKind(ValueKind));
221   }
222 };
223
224 namespace IndexedInstrProf {
225 enum class HashT : uint32_t {
226   MD5,
227
228   Last = MD5
229 };
230
231 static inline uint64_t MD5Hash(StringRef Str) {
232   MD5 Hash;
233   Hash.update(Str);
234   llvm::MD5::MD5Result Result;
235   Hash.final(Result);
236   // Return the least significant 8 bytes. Our MD5 implementation returns the
237   // result in little endian, so we may need to swap bytes.
238   using namespace llvm::support;
239   return endian::read<uint64_t, little, unaligned>(Result);
240 }
241
242 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
243   switch (Type) {
244     case HashT::MD5:
245       return IndexedInstrProf::MD5Hash(K);
246   }
247   llvm_unreachable("Unhandled hash type");
248 }
249
250 const uint64_t Magic = 0x8169666f72706cff;  // "\xfflprofi\x81"
251 const uint64_t Version = 3;
252 const HashT HashType = HashT::MD5;
253
254 struct Header {
255   uint64_t Magic;
256   uint64_t Version;
257   uint64_t MaxFunctionCount;
258   uint64_t HashType;
259   uint64_t HashOffset;
260 };
261
262 }  // end namespace IndexedInstrProf
263
264 namespace RawInstrProf {
265
266 const uint64_t Version = 1;
267
268 // Magic number to detect file format and endianness.
269 // Use 255 at one end, since no UTF-8 file can use that character.  Avoid 0,
270 // so that utilities, like strings, don't grab it as a string.  129 is also
271 // invalid UTF-8, and high enough to be interesting.
272 // Use "lprofr" in the centre to stand for "LLVM Profile Raw", or "lprofR"
273 // for 32-bit platforms.
274 // The magic and version need to be kept in sync with
275 // projects/compiler-rt/lib/profile/InstrProfiling.c
276
277 template <class IntPtrT>
278 inline uint64_t getMagic();
279 template <>
280 inline uint64_t getMagic<uint64_t>() {
281   return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
282          uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
283          uint64_t('r') << 8 | uint64_t(129);
284 }
285
286 template <>
287 inline uint64_t getMagic<uint32_t>() {
288   return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
289          uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
290          uint64_t('R') << 8 | uint64_t(129);
291 }
292
293 // The definition should match the structure defined in
294 // compiler-rt/lib/profile/InstrProfiling.h.
295 // It should also match the synthesized type in
296 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
297
298 template <class IntPtrT>
299 struct ProfileData {
300   const uint32_t NameSize;
301   const uint32_t NumCounters;
302   const uint64_t FuncHash;
303   const IntPtrT NamePtr;
304   const IntPtrT CounterPtr;
305 };
306
307 // The definition should match the header referenced in
308 // compiler-rt/lib/profile/InstrProfilingFile.c  and
309 // InstrProfilingBuffer.c.
310
311 struct Header {
312   const uint64_t Magic;
313   const uint64_t Version;
314   const uint64_t DataSize;
315   const uint64_t CountersSize;
316   const uint64_t NamesSize;
317   const uint64_t CountersDelta;
318   const uint64_t NamesDelta;
319 };
320
321 }  // end namespace RawInstrProf
322
323 } // end namespace llvm
324
325 namespace std {
326 template <>
327 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
328 }
329
330 #endif // LLVM_PROFILEDATA_INSTRPROF_H_