Don't use 'using std::error_code' in include/llvm.
[oota-llvm.git] / lib / ProfileData / InstrProfReader.cpp
1 //=-- InstrProfReader.cpp - Instrumented profiling reader -------------------=//
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 clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ProfileData/InstrProfReader.h"
16 #include "llvm/ProfileData/InstrProf.h"
17
18 #include "InstrProfIndexed.h"
19
20 #include <cassert>
21
22 using namespace llvm;
23 using std::error_code;
24
25 static error_code setupMemoryBuffer(std::string Path,
26                                     std::unique_ptr<MemoryBuffer> &Buffer) {
27   if (error_code EC = MemoryBuffer::getFileOrSTDIN(Path, Buffer))
28     return EC;
29
30   // Sanity check the file.
31   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
32     return instrprof_error::too_large;
33   return instrprof_error::success;
34 }
35
36 static error_code initializeReader(InstrProfReader &Reader) {
37   return Reader.readHeader();
38 }
39
40 error_code InstrProfReader::create(std::string Path,
41                                    std::unique_ptr<InstrProfReader> &Result) {
42   // Set up the buffer to read.
43   std::unique_ptr<MemoryBuffer> Buffer;
44   if (error_code EC = setupMemoryBuffer(Path, Buffer))
45     return EC;
46
47   // Create the reader.
48   if (IndexedInstrProfReader::hasFormat(*Buffer))
49     Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
50   else if (RawInstrProfReader64::hasFormat(*Buffer))
51     Result.reset(new RawInstrProfReader64(std::move(Buffer)));
52   else if (RawInstrProfReader32::hasFormat(*Buffer))
53     Result.reset(new RawInstrProfReader32(std::move(Buffer)));
54   else
55     Result.reset(new TextInstrProfReader(std::move(Buffer)));
56
57   // Initialize the reader and return the result.
58   return initializeReader(*Result);
59 }
60
61 error_code IndexedInstrProfReader::create(
62     std::string Path, std::unique_ptr<IndexedInstrProfReader> &Result) {
63   // Set up the buffer to read.
64   std::unique_ptr<MemoryBuffer> Buffer;
65   if (error_code EC = setupMemoryBuffer(Path, Buffer))
66     return EC;
67
68   // Create the reader.
69   if (!IndexedInstrProfReader::hasFormat(*Buffer))
70     return instrprof_error::bad_magic;
71   Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
72
73   // Initialize the reader and return the result.
74   return initializeReader(*Result);
75 }
76
77 void InstrProfIterator::Increment() {
78   if (Reader->readNextRecord(Record))
79     *this = InstrProfIterator();
80 }
81
82 error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
83   // Skip empty lines.
84   while (!Line.is_at_end() && Line->empty())
85     ++Line;
86   // If we hit EOF while looking for a name, we're done.
87   if (Line.is_at_end())
88     return error(instrprof_error::eof);
89
90   // Read the function name.
91   Record.Name = *Line++;
92
93   // Read the function hash.
94   if (Line.is_at_end())
95     return error(instrprof_error::truncated);
96   if ((Line++)->getAsInteger(10, Record.Hash))
97     return error(instrprof_error::malformed);
98
99   // Read the number of counters.
100   uint64_t NumCounters;
101   if (Line.is_at_end())
102     return error(instrprof_error::truncated);
103   if ((Line++)->getAsInteger(10, NumCounters))
104     return error(instrprof_error::malformed);
105   if (NumCounters == 0)
106     return error(instrprof_error::malformed);
107
108   // Read each counter and fill our internal storage with the values.
109   Counts.clear();
110   Counts.reserve(NumCounters);
111   for (uint64_t I = 0; I < NumCounters; ++I) {
112     if (Line.is_at_end())
113       return error(instrprof_error::truncated);
114     uint64_t Count;
115     if ((Line++)->getAsInteger(10, Count))
116       return error(instrprof_error::malformed);
117     Counts.push_back(Count);
118   }
119   // Give the record a reference to our internal counter storage.
120   Record.Counts = Counts;
121
122   return success();
123 }
124
125 template <class IntPtrT>
126 static uint64_t getRawMagic();
127
128 template <>
129 uint64_t getRawMagic<uint64_t>() {
130   return
131     uint64_t(255) << 56 |
132     uint64_t('l') << 48 |
133     uint64_t('p') << 40 |
134     uint64_t('r') << 32 |
135     uint64_t('o') << 24 |
136     uint64_t('f') << 16 |
137     uint64_t('r') <<  8 |
138     uint64_t(129);
139 }
140
141 template <>
142 uint64_t getRawMagic<uint32_t>() {
143   return
144     uint64_t(255) << 56 |
145     uint64_t('l') << 48 |
146     uint64_t('p') << 40 |
147     uint64_t('r') << 32 |
148     uint64_t('o') << 24 |
149     uint64_t('f') << 16 |
150     uint64_t('R') <<  8 |
151     uint64_t(129);
152 }
153
154 template <class IntPtrT>
155 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
156   if (DataBuffer.getBufferSize() < sizeof(uint64_t))
157     return false;
158   uint64_t Magic =
159     *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
160   return getRawMagic<IntPtrT>() == Magic ||
161     sys::SwapByteOrder(getRawMagic<IntPtrT>()) == Magic;
162 }
163
164 template <class IntPtrT>
165 error_code RawInstrProfReader<IntPtrT>::readHeader() {
166   if (!hasFormat(*DataBuffer))
167     return error(instrprof_error::bad_magic);
168   if (DataBuffer->getBufferSize() < sizeof(RawHeader))
169     return error(instrprof_error::bad_header);
170   auto *Header =
171     reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
172   ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
173   return readHeader(*Header);
174 }
175
176 template <class IntPtrT>
177 error_code RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
178   const char *End = DataBuffer->getBufferEnd();
179   // Skip zero padding between profiles.
180   while (CurrentPos != End && *CurrentPos == 0)
181     ++CurrentPos;
182   // If there's nothing left, we're done.
183   if (CurrentPos == End)
184     return instrprof_error::eof;
185   // If there isn't enough space for another header, this is probably just
186   // garbage at the end of the file.
187   if (CurrentPos + sizeof(RawHeader) > End)
188     return instrprof_error::malformed;
189   // The magic should have the same byte order as in the previous header.
190   uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
191   if (Magic != swap(getRawMagic<IntPtrT>()))
192     return instrprof_error::bad_magic;
193
194   // There's another profile to read, so we need to process the header.
195   auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
196   return readHeader(*Header);
197 }
198
199 static uint64_t getRawVersion() {
200   return 1;
201 }
202
203 template <class IntPtrT>
204 error_code RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
205   if (swap(Header.Version) != getRawVersion())
206     return error(instrprof_error::unsupported_version);
207
208   CountersDelta = swap(Header.CountersDelta);
209   NamesDelta = swap(Header.NamesDelta);
210   auto DataSize = swap(Header.DataSize);
211   auto CountersSize = swap(Header.CountersSize);
212   auto NamesSize = swap(Header.NamesSize);
213
214   ptrdiff_t DataOffset = sizeof(RawHeader);
215   ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
216   ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
217   size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
218
219   auto *Start = reinterpret_cast<const char *>(&Header);
220   if (Start + ProfileSize > DataBuffer->getBufferEnd())
221     return error(instrprof_error::bad_header);
222
223   Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
224   DataEnd = Data + DataSize;
225   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
226   NamesStart = Start + NamesOffset;
227   ProfileEnd = Start + ProfileSize;
228
229   return success();
230 }
231
232 template <class IntPtrT>
233 error_code
234 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
235   if (Data == DataEnd)
236     if (error_code EC = readNextHeader(ProfileEnd))
237       return EC;
238
239   // Get the raw data.
240   StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
241   uint32_t NumCounters = swap(Data->NumCounters);
242   if (NumCounters == 0)
243     return error(instrprof_error::malformed);
244   auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
245
246   // Check bounds.
247   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
248   if (RawName.data() < NamesStart ||
249       RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
250       RawCounts.data() < CountersStart ||
251       RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
252     return error(instrprof_error::malformed);
253
254   // Store the data in Record, byte-swapping as necessary.
255   Record.Hash = swap(Data->FuncHash);
256   Record.Name = RawName;
257   if (ShouldSwapBytes) {
258     Counts.clear();
259     Counts.reserve(RawCounts.size());
260     for (uint64_t Count : RawCounts)
261       Counts.push_back(swap(Count));
262     Record.Counts = Counts;
263   } else
264     Record.Counts = RawCounts;
265
266   // Iterate.
267   ++Data;
268   return success();
269 }
270
271 namespace llvm {
272 template class RawInstrProfReader<uint32_t>;
273 template class RawInstrProfReader<uint64_t>;
274 }
275
276 InstrProfLookupTrait::hash_value_type
277 InstrProfLookupTrait::ComputeHash(StringRef K) {
278   return IndexedInstrProf::ComputeHash(HashType, K);
279 }
280
281 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
282   if (DataBuffer.getBufferSize() < 8)
283     return false;
284   using namespace support;
285   uint64_t Magic =
286       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
287   return Magic == IndexedInstrProf::Magic;
288 }
289
290 error_code IndexedInstrProfReader::readHeader() {
291   const unsigned char *Start =
292       (const unsigned char *)DataBuffer->getBufferStart();
293   const unsigned char *Cur = Start;
294   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
295     return error(instrprof_error::truncated);
296
297   using namespace support;
298
299   // Check the magic number.
300   uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
301   if (Magic != IndexedInstrProf::Magic)
302     return error(instrprof_error::bad_magic);
303
304   // Read the version.
305   uint64_t Version = endian::readNext<uint64_t, little, unaligned>(Cur);
306   if (Version != IndexedInstrProf::Version)
307     return error(instrprof_error::unsupported_version);
308
309   // Read the maximal function count.
310   MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
311
312   // Read the hash type and start offset.
313   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
314       endian::readNext<uint64_t, little, unaligned>(Cur));
315   if (HashType > IndexedInstrProf::HashT::Last)
316     return error(instrprof_error::unsupported_hash_type);
317   uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
318
319   // The rest of the file is an on disk hash table.
320   Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
321                                            InstrProfLookupTrait(HashType)));
322   // Set up our iterator for readNextRecord.
323   RecordIterator = Index->data_begin();
324
325   return success();
326 }
327
328 error_code IndexedInstrProfReader::getFunctionCounts(
329     StringRef FuncName, uint64_t &FuncHash, std::vector<uint64_t> &Counts) {
330   const auto &Iter = Index->find(FuncName);
331   if (Iter == Index->end())
332     return error(instrprof_error::unknown_function);
333
334   // Found it. Make sure it's valid before giving back a result.
335   const InstrProfRecord &Record = *Iter;
336   if (Record.Name.empty())
337     return error(instrprof_error::malformed);
338   FuncHash = Record.Hash;
339   Counts = Record.Counts;
340   return success();
341 }
342
343 error_code IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
344   // Are we out of records?
345   if (RecordIterator == Index->data_end())
346     return error(instrprof_error::eof);
347
348   // Read the next one.
349   Record = *RecordIterator;
350   ++RecordIterator;
351   if (Record.Name.empty())
352     return error(instrprof_error::malformed);
353   return success();
354 }