e4dfc386000ad2d211e29f72e8c2e7c6a06b6144
[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 <iterator>
27
28 namespace llvm {
29
30 class InstrProfReader;
31
32 /// A file format agnostic iterator over profiling data.
33 class InstrProfIterator : public std::iterator<std::input_iterator_tag,
34                                                InstrProfRecord> {
35   InstrProfReader *Reader;
36   InstrProfRecord Record;
37
38   void Increment();
39 public:
40   InstrProfIterator() : Reader(nullptr) {}
41   InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); }
42
43   InstrProfIterator &operator++() { Increment(); return *this; }
44   bool operator==(const InstrProfIterator &RHS) { return Reader == RHS.Reader; }
45   bool operator!=(const InstrProfIterator &RHS) { return Reader != RHS.Reader; }
46   InstrProfRecord &operator*() { return Record; }
47   InstrProfRecord *operator->() { return &Record; }
48 };
49
50 /// Base class and interface for reading profiling data of any known instrprof
51 /// format. Provides an iterator over InstrProfRecords.
52 class InstrProfReader {
53   std::error_code LastError;
54
55 public:
56   InstrProfReader() : LastError(instrprof_error::success) {}
57   virtual ~InstrProfReader() {}
58
59   /// Read the header.  Required before reading first record.
60   virtual std::error_code readHeader() = 0;
61   /// Read a single record.
62   virtual std::error_code readNextRecord(InstrProfRecord &Record) = 0;
63   /// Iterator over profile data.
64   InstrProfIterator begin() { return InstrProfIterator(this); }
65   InstrProfIterator end() { return InstrProfIterator(); }
66
67  protected:
68   /// Set the current std::error_code and return same.
69   std::error_code error(std::error_code EC) {
70     LastError = EC;
71     return EC;
72   }
73
74   /// Clear the current error code and return a successful one.
75   std::error_code success() { return error(instrprof_error::success); }
76
77 public:
78   /// Return true if the reader has finished reading the profile data.
79   bool isEOF() { return LastError == instrprof_error::eof; }
80   /// Return true if the reader encountered an error reading profiling data.
81   bool hasError() { return LastError && !isEOF(); }
82   /// Get the current error code.
83   std::error_code getError() { return LastError; }
84
85   /// Factory method to create an appropriately typed reader for the given
86   /// instrprof file.
87   static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path);
88
89   static ErrorOr<std::unique_ptr<InstrProfReader>>
90   create(std::unique_ptr<MemoryBuffer> Buffer);
91 };
92
93 /// Reader for the simple text based instrprof format.
94 ///
95 /// This format is a simple text format that's suitable for test data. Records
96 /// are separated by one or more blank lines, and record fields are separated by
97 /// new lines.
98 ///
99 /// Each record consists of a function name, a function hash, a number of
100 /// counters, and then each counter value, in that order.
101 class TextInstrProfReader : public InstrProfReader {
102 private:
103   /// The profile data file contents.
104   std::unique_ptr<MemoryBuffer> DataBuffer;
105   /// Iterator over the profile data.
106   line_iterator Line;
107
108   TextInstrProfReader(const TextInstrProfReader &) = delete;
109   TextInstrProfReader &operator=(const TextInstrProfReader &) = delete;
110 public:
111   TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
112       : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
113
114   /// Read the header.
115   std::error_code readHeader() override { return success(); }
116   /// Read a single record.
117   std::error_code readNextRecord(InstrProfRecord &Record) override;
118 };
119
120 /// Reader for the raw instrprof binary format from runtime.
121 ///
122 /// This format is a raw memory dump of the instrumentation-baed profiling data
123 /// from the runtime.  It has no index.
124 ///
125 /// Templated on the unsigned type whose size matches pointers on the platform
126 /// that wrote the profile.
127 template <class IntPtrT>
128 class RawInstrProfReader : public InstrProfReader {
129 private:
130   /// The profile data file contents.
131   std::unique_ptr<MemoryBuffer> DataBuffer;
132
133   bool ShouldSwapBytes;
134   uint64_t CountersDelta;
135   uint64_t NamesDelta;
136   const RawInstrProf::ProfileData<IntPtrT> *Data;
137   const RawInstrProf::ProfileData<IntPtrT> *DataEnd;
138   const uint64_t *CountersStart;
139   const char *NamesStart;
140   const char *ProfileEnd;
141
142   RawInstrProfReader(const RawInstrProfReader &) = delete;
143   RawInstrProfReader &operator=(const RawInstrProfReader &) = delete;
144 public:
145   RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
146       : DataBuffer(std::move(DataBuffer)) { }
147
148   static bool hasFormat(const MemoryBuffer &DataBuffer);
149   std::error_code readHeader() override;
150   std::error_code readNextRecord(InstrProfRecord &Record) override;
151
152 private:
153   std::error_code readNextHeader(const char *CurrentPos);
154   std::error_code readHeader(const RawInstrProf::Header &Header);
155   template <class IntT>
156   IntT swap(IntT Int) const {
157     return ShouldSwapBytes ? sys::getSwappedBytes(Int) : Int;
158   }
159   const uint64_t *getCounter(IntPtrT CounterPtr) const {
160     ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t);
161     return CountersStart + Offset;
162   }
163   const char *getName(IntPtrT NamePtr) const {
164     ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char);
165     return NamesStart + Offset;
166   }
167 };
168
169 typedef RawInstrProfReader<uint32_t> RawInstrProfReader32;
170 typedef RawInstrProfReader<uint64_t> RawInstrProfReader64;
171
172 namespace IndexedInstrProf {
173 enum class HashT : uint32_t;
174 }
175
176 /// Trait for lookups into the on-disk hash table for the binary instrprof
177 /// format.
178 class InstrProfLookupTrait {
179   std::vector<InstrProfRecord> DataBuffer;
180   IndexedInstrProf::HashT HashType;
181   unsigned FormatVersion;
182   std::vector<std::pair<uint64_t, const char *>> HashKeys;
183
184 public:
185   InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
186       : HashType(HashType), FormatVersion(FormatVersion) {}
187
188   typedef ArrayRef<InstrProfRecord> data_type;
189
190   typedef StringRef internal_key_type;
191   typedef StringRef external_key_type;
192   typedef uint64_t hash_value_type;
193   typedef uint64_t offset_type;
194
195   static bool EqualKey(StringRef A, StringRef B) { return A == B; }
196   static StringRef GetInternalKey(StringRef K) { return K; }
197   static StringRef GetExternalKey(StringRef K) { return K; }
198
199   hash_value_type ComputeHash(StringRef K);
200
201   void setHashKeys(std::vector<std::pair<uint64_t, const char *>> HashKeys) {
202     this->HashKeys = std::move(HashKeys);
203   }
204   static std::pair<offset_type, offset_type>
205   ReadKeyDataLength(const unsigned char *&D) {
206     using namespace support;
207     offset_type KeyLen = endian::readNext<offset_type, little, unaligned>(D);
208     offset_type DataLen = endian::readNext<offset_type, little, unaligned>(D);
209     return std::make_pair(KeyLen, DataLen);
210   }
211
212   StringRef ReadKey(const unsigned char *D, offset_type N) {
213     return StringRef((const char *)D, N);
214   }
215
216   bool ReadValueProfilingData(const unsigned char *&D,
217                               const unsigned char *const End);
218   data_type ReadData(StringRef K, const unsigned char *D, offset_type N);
219 };
220
221 class InstrProfReaderIndex {
222  private:
223   typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait> IndexType;
224
225   std::unique_ptr<IndexType> Index;
226   IndexType::data_iterator RecordIterator;
227   uint64_t FormatVersion;
228
229   // String table for holding a unique copy of all the strings in the profile.
230   InstrProfStringTable StringTable;
231
232  public:
233   InstrProfReaderIndex() : Index(nullptr) {}
234   void Init(const unsigned char *Buckets, const unsigned char *const Payload,
235             const unsigned char *const Base, IndexedInstrProf::HashT HashType,
236             uint64_t Version);
237
238   // Read all the pofile records with the same key pointed to the current
239   // iterator.
240   std::error_code getRecords(ArrayRef<InstrProfRecord> &Data);
241   // Read all the profile records with the key equal to FuncName
242   std::error_code getRecords(StringRef FuncName,
243                              ArrayRef<InstrProfRecord> &Data);
244
245   void advanceToNextKey() { RecordIterator++; }
246   bool atEnd() const { return RecordIterator == Index->data_end(); }
247 };
248
249 /// Reader for the indexed binary instrprof format.
250 class IndexedInstrProfReader : public InstrProfReader {
251 private:
252   /// The profile data file contents.
253   std::unique_ptr<MemoryBuffer> DataBuffer;
254   /// The index into the profile data.
255   InstrProfReaderIndex Index;
256   /// The maximal execution count among all functions.
257   uint64_t MaxFunctionCount;
258
259   IndexedInstrProfReader(const IndexedInstrProfReader &) = delete;
260   IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete;
261
262  public:
263   IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
264       : DataBuffer(std::move(DataBuffer)), Index() {}
265
266   /// Return true if the given buffer is in an indexed instrprof format.
267   static bool hasFormat(const MemoryBuffer &DataBuffer);
268
269   /// Read the file header.
270   std::error_code readHeader() override;
271   /// Read a single record.
272   std::error_code readNextRecord(InstrProfRecord &Record) override;
273
274   /// Fill Counts with the profile data for the given function name.
275   std::error_code getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
276                                     std::vector<uint64_t> &Counts);
277   /// Return the maximum of all known function counts.
278   uint64_t getMaximumFunctionCount() { return MaxFunctionCount; }
279
280   /// Factory method to create an indexed reader.
281   static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
282   create(std::string Path);
283
284   static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
285   create(std::unique_ptr<MemoryBuffer> Buffer);
286 };
287
288 } // end namespace llvm
289
290 #endif