7056057e50f631b8934b98fb01471095ca0171e0
[oota-llvm.git] / include / llvm / ProfileData / InstrProfReader.h
1 //=-- InstrProfReader.h - Instrumented profiling readers ----------*- 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 // This file contains support for reading profiling data for instrumentation
11 // based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PROFILEDATA_INSTRPROFREADER_H
16 #define LLVM_PROFILEDATA_INSTRPROFREADER_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ProfileData/InstrProf.h"
21 #include "llvm/Support/EndianStream.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/LineIterator.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/OnDiskHashTable.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <iterator>
28
29 namespace llvm {
30
31 class InstrProfReader;
32
33 /// A file format agnostic iterator over profiling data.
34 class InstrProfIterator : public std::iterator<std::input_iterator_tag,
35                                                InstrProfRecord> {
36   InstrProfReader *Reader;
37   InstrProfRecord Record;
38
39   void Increment();
40 public:
41   InstrProfIterator() : Reader(nullptr) {}
42   InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); }
43
44   InstrProfIterator &operator++() { Increment(); return *this; }
45   bool operator==(const InstrProfIterator &RHS) { return Reader == RHS.Reader; }
46   bool operator!=(const InstrProfIterator &RHS) { return Reader != RHS.Reader; }
47   InstrProfRecord &operator*() { return Record; }
48   InstrProfRecord *operator->() { return &Record; }
49 };
50
51 /// Base class and interface for reading profiling data of any known instrprof
52 /// format. Provides an iterator over InstrProfRecords.
53 class InstrProfReader {
54   std::error_code LastError;
55
56 public:
57   InstrProfReader() : LastError(instrprof_error::success) {}
58   virtual ~InstrProfReader() {}
59
60   /// Read the header.  Required before reading first record.
61   virtual std::error_code readHeader() = 0;
62   /// Read a single record.
63   virtual std::error_code readNextRecord(InstrProfRecord &Record) = 0;
64   /// Iterator over profile data.
65   InstrProfIterator begin() { return InstrProfIterator(this); }
66   InstrProfIterator end() { return InstrProfIterator(); }
67
68  protected:
69   /// Set the current std::error_code and return same.
70   std::error_code error(std::error_code EC) {
71     LastError = EC;
72     return EC;
73   }
74
75   /// Clear the current error code and return a successful one.
76   std::error_code success() { return error(instrprof_error::success); }
77
78 public:
79   /// Return true if the reader has finished reading the profile data.
80   bool isEOF() { return LastError == instrprof_error::eof; }
81   /// Return true if the reader encountered an error reading profiling data.
82   bool hasError() { return LastError && !isEOF(); }
83   /// Get the current error code.
84   std::error_code getError() { return LastError; }
85
86   /// Factory method to create an appropriately typed reader for the given
87   /// instrprof file.
88   static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path);
89
90   static ErrorOr<std::unique_ptr<InstrProfReader>>
91   create(std::unique_ptr<MemoryBuffer> Buffer);
92 };
93
94 /// Reader for the simple text based instrprof format.
95 ///
96 /// This format is a simple text format that's suitable for test data. Records
97 /// are separated by one or more blank lines, and record fields are separated by
98 /// new lines.
99 ///
100 /// Each record consists of a function name, a function hash, a number of
101 /// counters, and then each counter value, in that order.
102 class TextInstrProfReader : public InstrProfReader {
103 private:
104   /// The profile data file contents.
105   std::unique_ptr<MemoryBuffer> DataBuffer;
106   /// Iterator over the profile data.
107   line_iterator Line;
108
109   // String table for holding a unique copy of all the strings in the profile.
110   InstrProfStringTable StringTable;
111
112   TextInstrProfReader(const TextInstrProfReader &) = delete;
113   TextInstrProfReader &operator=(const TextInstrProfReader &) = delete;
114   std::error_code readValueProfileData(InstrProfRecord &Record);
115
116 public:
117   TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
118       : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
119
120   /// Return true if the given buffer is in text instrprof format.
121   static bool hasFormat(const MemoryBuffer &Buffer);
122
123   /// Read the header.
124   std::error_code readHeader() override { return success(); }
125   /// Read a single record.
126   std::error_code readNextRecord(InstrProfRecord &Record) override;
127 };
128
129 /// Reader for the raw instrprof binary format from runtime.
130 ///
131 /// This format is a raw memory dump of the instrumentation-baed profiling data
132 /// from the runtime.  It has no index.
133 ///
134 /// Templated on the unsigned type whose size matches pointers on the platform
135 /// that wrote the profile.
136 template <class IntPtrT>
137 class RawInstrProfReader : public InstrProfReader {
138 private:
139   /// The profile data file contents.
140   std::unique_ptr<MemoryBuffer> DataBuffer;
141   bool ShouldSwapBytes;
142   uint64_t CountersDelta;
143   uint64_t NamesDelta;
144   const RawInstrProf::ProfileData<IntPtrT> *Data;
145   const RawInstrProf::ProfileData<IntPtrT> *DataEnd;
146   const uint64_t *CountersStart;
147   const char *NamesStart;
148   const uint8_t *ValueDataStart;
149   const char *ProfileEnd;
150   uint32_t ValueKindLast;
151   uint32_t CurValueDataSize;
152
153   // String table for holding a unique copy of all the strings in the profile.
154   InstrProfStringTable StringTable;
155   InstrProfRecord::ValueMapType FunctionPtrToNameMap;
156
157   RawInstrProfReader(const RawInstrProfReader &) = delete;
158   RawInstrProfReader &operator=(const RawInstrProfReader &) = delete;
159 public:
160   RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
161       : DataBuffer(std::move(DataBuffer)) { }
162
163   static bool hasFormat(const MemoryBuffer &DataBuffer);
164   std::error_code readHeader() override;
165   std::error_code readNextRecord(InstrProfRecord &Record) override;
166
167 private:
168   std::error_code readNextHeader(const char *CurrentPos);
169   std::error_code readHeader(const RawInstrProf::Header &Header);
170   template <class IntT> IntT swap(IntT Int) const {
171     return ShouldSwapBytes ? sys::getSwappedBytes(Int) : Int;
172   }
173   support::endianness getDataEndianness() const {
174     support::endianness HostEndian = getHostEndianness();
175     if (!ShouldSwapBytes)
176       return HostEndian;
177     if (HostEndian == support::little)
178       return support::big;
179     else
180       return support::little;
181   }
182
183   inline uint8_t getNumPaddingBytes(uint64_t SizeInBytes) {
184     return 7 & (sizeof(uint64_t) - SizeInBytes % sizeof(uint64_t));
185   }
186   std::error_code readName(InstrProfRecord &Record);
187   std::error_code readFuncHash(InstrProfRecord &Record);
188   std::error_code readRawCounts(InstrProfRecord &Record);
189   std::error_code readValueProfilingData(InstrProfRecord &Record);
190   bool atEnd() const { return Data == DataEnd; }
191   void advanceData() {
192     Data++;
193     ValueDataStart += CurValueDataSize;
194   }
195
196   const uint64_t *getCounter(IntPtrT CounterPtr) const {
197     ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t);
198     return CountersStart + Offset;
199   }
200   const char *getName(IntPtrT NamePtr) const {
201     ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char);
202     return NamesStart + Offset;
203   }
204 };
205
206 typedef RawInstrProfReader<uint32_t> RawInstrProfReader32;
207 typedef RawInstrProfReader<uint64_t> RawInstrProfReader64;
208
209 namespace IndexedInstrProf {
210 enum class HashT : uint32_t;
211 }
212
213 /// Trait for lookups into the on-disk hash table for the binary instrprof
214 /// format.
215 class InstrProfLookupTrait {
216   std::vector<InstrProfRecord> DataBuffer;
217   IndexedInstrProf::HashT HashType;
218   unsigned FormatVersion;
219   // Endianness of the input value profile data.
220   // It should be LE by default, but can be changed
221   // for testing purpose.
222   support::endianness ValueProfDataEndianness;
223   std::vector<std::pair<uint64_t, const char *>> HashKeys;
224
225 public:
226   InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
227       : HashType(HashType), FormatVersion(FormatVersion),
228         ValueProfDataEndianness(support::little) {}
229
230   typedef ArrayRef<InstrProfRecord> data_type;
231
232   typedef StringRef internal_key_type;
233   typedef StringRef external_key_type;
234   typedef uint64_t hash_value_type;
235   typedef uint64_t offset_type;
236
237   static bool EqualKey(StringRef A, StringRef B) { return A == B; }
238   static StringRef GetInternalKey(StringRef K) { return K; }
239   static StringRef GetExternalKey(StringRef K) { return K; }
240
241   hash_value_type ComputeHash(StringRef K);
242
243   void setHashKeys(std::vector<std::pair<uint64_t, const char *>> HashKeys) {
244     this->HashKeys = std::move(HashKeys);
245   }
246   static std::pair<offset_type, offset_type>
247   ReadKeyDataLength(const unsigned char *&D) {
248     using namespace support;
249     offset_type KeyLen = endian::readNext<offset_type, little, unaligned>(D);
250     offset_type DataLen = endian::readNext<offset_type, little, unaligned>(D);
251     return std::make_pair(KeyLen, DataLen);
252   }
253
254   StringRef ReadKey(const unsigned char *D, offset_type N) {
255     return StringRef((const char *)D, N);
256   }
257
258   bool readValueProfilingData(const unsigned char *&D,
259                               const unsigned char *const End);
260   data_type ReadData(StringRef K, const unsigned char *D, offset_type N);
261
262   // Used for testing purpose only.
263   void setValueProfDataEndianness(support::endianness Endianness) {
264     ValueProfDataEndianness = Endianness;
265   }
266 };
267
268 struct InstrProfReaderIndexBase {
269   // Read all the profile records with the same key pointed to the current
270   // iterator.
271   virtual std::error_code getRecords(ArrayRef<InstrProfRecord> &Data) = 0;
272   // Read all the profile records with the key equal to FuncName
273   virtual std::error_code getRecords(StringRef FuncName,
274                                      ArrayRef<InstrProfRecord> &Data) = 0;
275   virtual void advanceToNextKey() = 0;
276   virtual bool atEnd() const = 0;
277   virtual void setValueProfDataEndianness(support::endianness Endianness) = 0;
278   virtual ~InstrProfReaderIndexBase() {}
279   virtual uint64_t getVersion() const = 0;
280 };
281
282 typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait>
283     OnDiskHashTableImplV3;
284
285 template <typename HashTableImpl>
286 class InstrProfReaderIndex : public InstrProfReaderIndexBase {
287
288 private:
289   std::unique_ptr<HashTableImpl> HashTable;
290   typename HashTableImpl::data_iterator RecordIterator;
291   uint64_t FormatVersion;
292
293   // String table for holding a unique copy of all the strings in the profile.
294   InstrProfStringTable StringTable;
295
296 public:
297   InstrProfReaderIndex(const unsigned char *Buckets,
298                        const unsigned char *const Payload,
299                        const unsigned char *const Base,
300                        IndexedInstrProf::HashT HashType, uint64_t Version);
301
302   std::error_code getRecords(ArrayRef<InstrProfRecord> &Data) override;
303   std::error_code getRecords(StringRef FuncName,
304                              ArrayRef<InstrProfRecord> &Data) override;
305   void advanceToNextKey() override { RecordIterator++; }
306   bool atEnd() const override {
307     return RecordIterator == HashTable->data_end();
308   }
309   void setValueProfDataEndianness(support::endianness Endianness) override {
310     HashTable->getInfoObj().setValueProfDataEndianness(Endianness);
311   }
312   ~InstrProfReaderIndex() override {}
313   uint64_t getVersion() const override { return FormatVersion; }
314 };
315
316 /// Reader for the indexed binary instrprof format.
317 class IndexedInstrProfReader : public InstrProfReader {
318 private:
319   /// The profile data file contents.
320   std::unique_ptr<MemoryBuffer> DataBuffer;
321   /// The index into the profile data.
322   std::unique_ptr<InstrProfReaderIndexBase> Index;
323   /// The maximal execution count among all functions.
324   uint64_t MaxFunctionCount;
325
326   IndexedInstrProfReader(const IndexedInstrProfReader &) = delete;
327   IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete;
328
329 public:
330   uint64_t getVersion() const { return Index->getVersion(); }
331   IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
332       : DataBuffer(std::move(DataBuffer)), Index(nullptr) {}
333
334   /// Return true if the given buffer is in an indexed instrprof format.
335   static bool hasFormat(const MemoryBuffer &DataBuffer);
336
337   /// Read the file header.
338   std::error_code readHeader() override;
339   /// Read a single record.
340   std::error_code readNextRecord(InstrProfRecord &Record) override;
341
342   /// Return the pointer to InstrProfRecord associated with FuncName
343   /// and FuncHash
344   ErrorOr<InstrProfRecord> getInstrProfRecord(StringRef FuncName,
345                                               uint64_t FuncHash);
346
347   /// Fill Counts with the profile data for the given function name.
348   std::error_code getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
349                                     std::vector<uint64_t> &Counts);
350
351   /// Return the maximum of all known function counts.
352   uint64_t getMaximumFunctionCount() { return MaxFunctionCount; }
353
354   /// Factory method to create an indexed reader.
355   static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
356   create(std::string Path);
357
358   static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
359   create(std::unique_ptr<MemoryBuffer> Buffer);
360
361   // Used for testing purpose only.
362   void setValueProfDataEndianness(support::endianness Endianness) {
363     Index->setValueProfDataEndianness(Endianness);
364   }
365 };
366
367 } // end namespace llvm
368
369 #endif