1 //=-- InstrProfReader.h - Instrumented profiling readers ----------*- 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 // This file contains support for reading profiling data for instrumentation
11 // based PGO and coverage.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PROFILEDATA_INSTRPROFREADER_H
16 #define LLVM_PROFILEDATA_INSTRPROFREADER_H
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"
31 class InstrProfReader;
33 /// A file format agnostic iterator over profiling data.
34 class InstrProfIterator : public std::iterator<std::input_iterator_tag,
36 InstrProfReader *Reader;
37 InstrProfRecord Record;
41 InstrProfIterator() : Reader(nullptr) {}
42 InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); }
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; }
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;
57 InstrProfReader() : LastError(instrprof_error::success) {}
58 virtual ~InstrProfReader() {}
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(); }
69 /// Set the current std::error_code and return same.
70 std::error_code error(std::error_code EC) {
75 /// Clear the current error code and return a successful one.
76 std::error_code success() { return error(instrprof_error::success); }
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; }
86 /// Factory method to create an appropriately typed reader for the given
88 static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path);
90 static ErrorOr<std::unique_ptr<InstrProfReader>>
91 create(std::unique_ptr<MemoryBuffer> Buffer);
94 /// Reader for the simple text based instrprof format.
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
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 {
104 /// The profile data file contents.
105 std::unique_ptr<MemoryBuffer> DataBuffer;
106 /// Iterator over the profile data.
109 TextInstrProfReader(const TextInstrProfReader &) = delete;
110 TextInstrProfReader &operator=(const TextInstrProfReader &) = delete;
112 TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_)
113 : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {}
115 /// Return true if the given buffer is in text instrprof format.
116 static bool hasFormat(const MemoryBuffer &Buffer);
119 std::error_code readHeader() override { return success(); }
120 /// Read a single record.
121 std::error_code readNextRecord(InstrProfRecord &Record) override;
124 /// Reader for the raw instrprof binary format from runtime.
126 /// This format is a raw memory dump of the instrumentation-baed profiling data
127 /// from the runtime. It has no index.
129 /// Templated on the unsigned type whose size matches pointers on the platform
130 /// that wrote the profile.
131 template <class IntPtrT>
132 class RawInstrProfReader : public InstrProfReader {
134 /// The profile data file contents.
135 std::unique_ptr<MemoryBuffer> DataBuffer;
136 bool ShouldSwapBytes;
137 uint64_t CountersDelta;
139 const RawInstrProf::ProfileData<IntPtrT> *Data;
140 const RawInstrProf::ProfileData<IntPtrT> *DataEnd;
141 const uint64_t *CountersStart;
142 const char *NamesStart;
143 const uint8_t *ValueDataStart;
144 const char *ProfileEnd;
145 uint32_t ValueKindLast;
146 uint32_t CurValueDataSize;
148 // String table for holding a unique copy of all the strings in the profile.
149 InstrProfStringTable StringTable;
150 InstrProfRecord::ValueMapType FunctionPtrToNameMap;
152 RawInstrProfReader(const RawInstrProfReader &) = delete;
153 RawInstrProfReader &operator=(const RawInstrProfReader &) = delete;
155 RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
156 : DataBuffer(std::move(DataBuffer)) { }
158 static bool hasFormat(const MemoryBuffer &DataBuffer);
159 std::error_code readHeader() override;
160 std::error_code readNextRecord(InstrProfRecord &Record) override;
163 std::error_code readNextHeader(const char *CurrentPos);
164 std::error_code readHeader(const RawInstrProf::Header &Header);
165 template <class IntT> IntT swap(IntT Int) const {
166 return ShouldSwapBytes ? sys::getSwappedBytes(Int) : Int;
168 support::endianness getDataEndianness() const {
169 support::endianness HostEndian = getHostEndianness();
170 if (!ShouldSwapBytes)
172 if (HostEndian == support::little)
175 return support::little;
178 inline uint8_t getNumPaddingBytes(uint64_t SizeInBytes) {
179 return 7 & (sizeof(uint64_t) - SizeInBytes % sizeof(uint64_t));
181 std::error_code readName(InstrProfRecord &Record);
182 std::error_code readFuncHash(InstrProfRecord &Record);
183 std::error_code readRawCounts(InstrProfRecord &Record);
184 std::error_code readValueProfilingData(InstrProfRecord &Record);
185 bool atEnd() const { return Data == DataEnd; }
188 ValueDataStart += CurValueDataSize;
191 const uint64_t *getCounter(IntPtrT CounterPtr) const {
192 ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t);
193 return CountersStart + Offset;
195 const char *getName(IntPtrT NamePtr) const {
196 ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char);
197 return NamesStart + Offset;
201 typedef RawInstrProfReader<uint32_t> RawInstrProfReader32;
202 typedef RawInstrProfReader<uint64_t> RawInstrProfReader64;
204 namespace IndexedInstrProf {
205 enum class HashT : uint32_t;
208 /// Trait for lookups into the on-disk hash table for the binary instrprof
210 class InstrProfLookupTrait {
211 std::vector<InstrProfRecord> DataBuffer;
212 IndexedInstrProf::HashT HashType;
213 unsigned FormatVersion;
214 // Endianness of the input value profile data.
215 // It should be LE by default, but can be changed
216 // for testing purpose.
217 support::endianness ValueProfDataEndianness;
218 std::vector<std::pair<uint64_t, const char *>> HashKeys;
221 InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion)
222 : HashType(HashType), FormatVersion(FormatVersion),
223 ValueProfDataEndianness(support::little) {}
225 typedef ArrayRef<InstrProfRecord> data_type;
227 typedef StringRef internal_key_type;
228 typedef StringRef external_key_type;
229 typedef uint64_t hash_value_type;
230 typedef uint64_t offset_type;
232 static bool EqualKey(StringRef A, StringRef B) { return A == B; }
233 static StringRef GetInternalKey(StringRef K) { return K; }
234 static StringRef GetExternalKey(StringRef K) { return K; }
236 hash_value_type ComputeHash(StringRef K);
238 void setHashKeys(std::vector<std::pair<uint64_t, const char *>> HashKeys) {
239 this->HashKeys = std::move(HashKeys);
241 static std::pair<offset_type, offset_type>
242 ReadKeyDataLength(const unsigned char *&D) {
243 using namespace support;
244 offset_type KeyLen = endian::readNext<offset_type, little, unaligned>(D);
245 offset_type DataLen = endian::readNext<offset_type, little, unaligned>(D);
246 return std::make_pair(KeyLen, DataLen);
249 StringRef ReadKey(const unsigned char *D, offset_type N) {
250 return StringRef((const char *)D, N);
253 bool readValueProfilingData(const unsigned char *&D,
254 const unsigned char *const End);
255 data_type ReadData(StringRef K, const unsigned char *D, offset_type N);
257 // Used for testing purpose only.
258 void setValueProfDataEndianness(support::endianness Endianness) {
259 ValueProfDataEndianness = Endianness;
263 struct InstrProfReaderIndexBase {
264 // Read all the profile records with the same key pointed to the current
266 virtual std::error_code getRecords(ArrayRef<InstrProfRecord> &Data) = 0;
267 // Read all the profile records with the key equal to FuncName
268 virtual std::error_code getRecords(StringRef FuncName,
269 ArrayRef<InstrProfRecord> &Data) = 0;
270 virtual void advanceToNextKey() = 0;
271 virtual bool atEnd() const = 0;
272 virtual void setValueProfDataEndianness(support::endianness Endianness) = 0;
273 virtual ~InstrProfReaderIndexBase() {}
274 virtual uint64_t getVersion() const = 0;
277 typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait>
278 OnDiskHashTableImplV3;
280 template <typename HashTableImpl>
281 class InstrProfReaderIndex : public InstrProfReaderIndexBase {
284 std::unique_ptr<HashTableImpl> HashTable;
285 typename HashTableImpl::data_iterator RecordIterator;
286 uint64_t FormatVersion;
288 // String table for holding a unique copy of all the strings in the profile.
289 InstrProfStringTable StringTable;
292 InstrProfReaderIndex(const unsigned char *Buckets,
293 const unsigned char *const Payload,
294 const unsigned char *const Base,
295 IndexedInstrProf::HashT HashType, uint64_t Version);
297 std::error_code getRecords(ArrayRef<InstrProfRecord> &Data) override;
298 std::error_code getRecords(StringRef FuncName,
299 ArrayRef<InstrProfRecord> &Data) override;
300 void advanceToNextKey() override { RecordIterator++; }
301 bool atEnd() const override {
302 return RecordIterator == HashTable->data_end();
304 void setValueProfDataEndianness(support::endianness Endianness) override {
305 HashTable->getInfoObj().setValueProfDataEndianness(Endianness);
307 ~InstrProfReaderIndex() override {}
308 uint64_t getVersion() const override { return FormatVersion; }
311 /// Reader for the indexed binary instrprof format.
312 class IndexedInstrProfReader : public InstrProfReader {
314 /// The profile data file contents.
315 std::unique_ptr<MemoryBuffer> DataBuffer;
316 /// The index into the profile data.
317 std::unique_ptr<InstrProfReaderIndexBase> Index;
318 /// The maximal execution count among all functions.
319 uint64_t MaxFunctionCount;
321 IndexedInstrProfReader(const IndexedInstrProfReader &) = delete;
322 IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete;
325 uint64_t getVersion() const { return Index->getVersion(); }
326 IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer)
327 : DataBuffer(std::move(DataBuffer)), Index(nullptr) {}
329 /// Return true if the given buffer is in an indexed instrprof format.
330 static bool hasFormat(const MemoryBuffer &DataBuffer);
332 /// Read the file header.
333 std::error_code readHeader() override;
334 /// Read a single record.
335 std::error_code readNextRecord(InstrProfRecord &Record) override;
337 /// Return the pointer to InstrProfRecord associated with FuncName
339 ErrorOr<InstrProfRecord> getInstrProfRecord(StringRef FuncName,
342 /// Fill Counts with the profile data for the given function name.
343 std::error_code getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
344 std::vector<uint64_t> &Counts);
346 /// Return the maximum of all known function counts.
347 uint64_t getMaximumFunctionCount() { return MaxFunctionCount; }
349 /// Factory method to create an indexed reader.
350 static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
351 create(std::string Path);
353 static ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
354 create(std::unique_ptr<MemoryBuffer> Buffer);
356 // Used for testing purpose only.
357 void setValueProfDataEndianness(support::endianness Endianness) {
358 Index->setValueProfDataEndianness(Endianness);
362 } // end namespace llvm