995d1f13c1cc6f8f4797ba34aa4044d3b6db922d
[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 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
32   return AddSegment ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
33 }
34
35 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
36   return AddSegment ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
37 }
38
39 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
40   return AddSegment ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
41 }
42
43 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
44   return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
45 }
46
47 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
48
49 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
50
51 inline StringRef getInstrProfCountersVarPrefix() {
52   return "__llvm_profile_counters_";
53 }
54
55 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
56
57 inline StringRef getCoverageMappingVarName() {
58   return "__llvm_coverage_mapping";
59 }
60
61 const std::error_category &instrprof_category();
62
63 enum class instrprof_error {
64   success = 0,
65   eof,
66   bad_magic,
67   bad_header,
68   unsupported_version,
69   unsupported_hash_type,
70   too_large,
71   truncated,
72   malformed,
73   unknown_function,
74   hash_mismatch,
75   count_mismatch,
76   counter_overflow,
77   value_site_count_mismatch
78 };
79
80 inline std::error_code make_error_code(instrprof_error E) {
81   return std::error_code(static_cast<int>(E), instrprof_category());
82 }
83
84 enum InstrProfValueKind : uint32_t {
85   IPVK_IndirectCallTarget = 0,
86
87   IPVK_First = IPVK_IndirectCallTarget,
88   IPVK_Last = IPVK_IndirectCallTarget
89 };
90
91 struct InstrProfStringTable {
92   // Set of string values in profiling data.
93   StringSet<> StringValueSet;
94   InstrProfStringTable() { StringValueSet.clear(); }
95   // Get a pointer to internal storage of a string in set
96   const char *getStringData(StringRef Str) {
97     auto Result = StringValueSet.find(Str);
98     return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
99   }
100   // Insert a string to StringTable
101   const char *insertString(StringRef Str) {
102     auto Result = StringValueSet.insert(Str);
103     return Result.first->first().data();
104   }
105 };
106
107 struct InstrProfValueSiteRecord {
108   /// Typedef for a single TargetValue-NumTaken pair.
109   typedef std::pair<uint64_t, uint64_t> ValueDataPair;
110   /// Value profiling data pairs at a given value site.
111   std::list<ValueDataPair> ValueData;
112
113   InstrProfValueSiteRecord() { ValueData.clear(); }
114
115   /// Sort ValueData ascending by TargetValue
116   void sortByTargetValues() {
117     ValueData.sort([](const ValueDataPair &left, const ValueDataPair &right) {
118       return left.first < right.first;
119     });
120   }
121
122   /// Merge data from another InstrProfValueSiteRecord
123   void mergeValueData(InstrProfValueSiteRecord &Input) {
124     this->sortByTargetValues();
125     Input.sortByTargetValues();
126     auto I = ValueData.begin();
127     auto IE = ValueData.end();
128     for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
129          ++J) {
130       while (I != IE && I->first < J->first)
131         ++I;
132       if (I != IE && I->first == J->first) {
133         I->second += J->second;
134         ++I;
135         continue;
136       }
137       ValueData.insert(I, *J);
138     }
139   }
140 };
141
142 /// Profiling information for a single function.
143 struct InstrProfRecord {
144   InstrProfRecord() {}
145   InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
146       : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
147   StringRef Name;
148   uint64_t Hash;
149   std::vector<uint64_t> Counts;
150   std::vector<InstrProfValueSiteRecord> IndirectCallSites;
151
152   const std::vector<InstrProfValueSiteRecord> &
153   getValueSitesForKind(uint32_t ValueKind) const {
154     switch (ValueKind) {
155     case IPVK_IndirectCallTarget:
156       return IndirectCallSites;
157     }
158     llvm_unreachable("Unknown value kind!");
159   }
160
161   std::vector<InstrProfValueSiteRecord> &
162   getValueSitesForKind(uint32_t ValueKind) {
163     return const_cast<std::vector<InstrProfValueSiteRecord> &>(
164         const_cast<const InstrProfRecord *>(this)
165             ->getValueSitesForKind(ValueKind));
166   }
167 };
168
169 namespace IndexedInstrProf {
170 enum class HashT : uint32_t {
171   MD5,
172
173   Last = MD5
174 };
175
176 static inline uint64_t MD5Hash(StringRef Str) {
177   MD5 Hash;
178   Hash.update(Str);
179   llvm::MD5::MD5Result Result;
180   Hash.final(Result);
181   // Return the least significant 8 bytes. Our MD5 implementation returns the
182   // result in little endian, so we may need to swap bytes.
183   using namespace llvm::support;
184   return endian::read<uint64_t, little, unaligned>(Result);
185 }
186
187 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
188   switch (Type) {
189     case HashT::MD5:
190       return IndexedInstrProf::MD5Hash(K);
191   }
192   llvm_unreachable("Unhandled hash type");
193 }
194
195 const uint64_t Magic = 0x8169666f72706cff;  // "\xfflprofi\x81"
196 const uint64_t Version = 3;
197 const HashT HashType = HashT::MD5;
198
199 struct Header {
200   uint64_t Magic;
201   uint64_t Version;
202   uint64_t MaxFunctionCount;
203   uint64_t HashType;
204   uint64_t HashOffset;
205 };
206
207 }  // end namespace IndexedInstrProf
208
209 namespace RawInstrProf {
210
211 const uint64_t Version = 1;
212
213 // Magic number to detect file format and endianness.
214 // Use 255 at one end, since no UTF-8 file can use that character.  Avoid 0,
215 // so that utilities, like strings, don't grab it as a string.  129 is also
216 // invalid UTF-8, and high enough to be interesting.
217 // Use "lprofr" in the centre to stand for "LLVM Profile Raw", or "lprofR"
218 // for 32-bit platforms.
219 // The magic and version need to be kept in sync with
220 // projects/compiler-rt/lib/profile/InstrProfiling.c
221
222 template <class IntPtrT>
223 inline uint64_t getMagic();
224 template <>
225 inline uint64_t getMagic<uint64_t>() {
226   return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
227          uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
228          uint64_t('r') << 8 | uint64_t(129);
229 }
230
231 template <>
232 inline uint64_t getMagic<uint32_t>() {
233   return uint64_t(255) << 56 | uint64_t('l') << 48 | uint64_t('p') << 40 |
234          uint64_t('r') << 32 | uint64_t('o') << 24 | uint64_t('f') << 16 |
235          uint64_t('R') << 8 | uint64_t(129);
236 }
237
238 // The definition should match the structure defined in
239 // compiler-rt/lib/profile/InstrProfiling.h.
240 // It should also match the synthesized type in
241 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
242
243 template <class IntPtrT>
244 struct ProfileData {
245   const uint32_t NameSize;
246   const uint32_t NumCounters;
247   const uint64_t FuncHash;
248   const IntPtrT NamePtr;
249   const IntPtrT CounterPtr;
250 };
251
252 // The definition should match the header referenced in
253 // compiler-rt/lib/profile/InstrProfilingFile.c  and
254 // InstrProfilingBuffer.c.
255
256 struct Header {
257   const uint64_t Magic;
258   const uint64_t Version;
259   const uint64_t DataSize;
260   const uint64_t CountersSize;
261   const uint64_t NamesSize;
262   const uint64_t CountersDelta;
263   const uint64_t NamesDelta;
264 };
265
266 }  // end namespace RawInstrProf
267
268 } // end namespace llvm
269
270 namespace std {
271 template <>
272 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
273 }
274
275 #endif // LLVM_PROFILEDATA_INSTRPROF_H_