blob: 27142e0533f5c844c7b9c13b3697bbcee806ba4b [file] [log] [blame]
Justin Bognerf8d79192014-03-21 17:24:48 +00001//=-- 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"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000017#include <cassert>
18
19using namespace llvm;
20
Diego Novillofcd55602014-11-03 00:51:45 +000021static ErrorOr<std::unique_ptr<MemoryBuffer>>
22setupMemoryBuffer(std::string Path) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +000023 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
24 MemoryBuffer::getFileOrSTDIN(Path);
25 if (std::error_code EC = BufferOrErr.getError())
Justin Bognerf8d79192014-03-21 17:24:48 +000026 return EC;
Justin Bogner2b6c5372015-02-18 01:58:17 +000027 return std::move(BufferOrErr.get());
Justin Bognerb7aa2632014-04-18 21:48:40 +000028}
29
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000030static std::error_code initializeReader(InstrProfReader &Reader) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000031 return Reader.readHeader();
32}
33
Diego Novillofcd55602014-11-03 00:51:45 +000034ErrorOr<std::unique_ptr<InstrProfReader>>
35InstrProfReader::create(std::string Path) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000036 // Set up the buffer to read.
Diego Novillofcd55602014-11-03 00:51:45 +000037 auto BufferOrError = setupMemoryBuffer(Path);
38 if (std::error_code EC = BufferOrError.getError())
Justin Bognerb7aa2632014-04-18 21:48:40 +000039 return EC;
Justin Bogner2b6c5372015-02-18 01:58:17 +000040 return InstrProfReader::create(std::move(BufferOrError.get()));
41}
Justin Bognerf8d79192014-03-21 17:24:48 +000042
Justin Bogner2b6c5372015-02-18 01:58:17 +000043ErrorOr<std::unique_ptr<InstrProfReader>>
44InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
45 // Sanity check the buffer.
46 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
47 return instrprof_error::too_large;
48
Diego Novillofcd55602014-11-03 00:51:45 +000049 std::unique_ptr<InstrProfReader> Result;
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +000050 // Create the reader.
Justin Bognerb7aa2632014-04-18 21:48:40 +000051 if (IndexedInstrProfReader::hasFormat(*Buffer))
52 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
53 else if (RawInstrProfReader64::hasFormat(*Buffer))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +000054 Result.reset(new RawInstrProfReader64(std::move(Buffer)));
55 else if (RawInstrProfReader32::hasFormat(*Buffer))
56 Result.reset(new RawInstrProfReader32(std::move(Buffer)));
Nathan Slingerland4f823662015-11-13 03:47:58 +000057 else if (TextInstrProfReader::hasFormat(*Buffer))
Nathan Slingerland911ced62015-11-12 18:39:26 +000058 Result.reset(new TextInstrProfReader(std::move(Buffer)));
Nathan Slingerland4f823662015-11-13 03:47:58 +000059 else
60 return instrprof_error::unrecognized_format;
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +000061
Justin Bognerb7aa2632014-04-18 21:48:40 +000062 // Initialize the reader and return the result.
Diego Novillofcd55602014-11-03 00:51:45 +000063 if (std::error_code EC = initializeReader(*Result))
64 return EC;
65
66 return std::move(Result);
Justin Bognerb7aa2632014-04-18 21:48:40 +000067}
68
Justin Bognerab89ed72015-02-16 21:28:58 +000069ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
70IndexedInstrProfReader::create(std::string Path) {
Justin Bognerb7aa2632014-04-18 21:48:40 +000071 // Set up the buffer to read.
Diego Novillofcd55602014-11-03 00:51:45 +000072 auto BufferOrError = setupMemoryBuffer(Path);
73 if (std::error_code EC = BufferOrError.getError())
Justin Bognerb7aa2632014-04-18 21:48:40 +000074 return EC;
Justin Bogner2b6c5372015-02-18 01:58:17 +000075 return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
76}
Justin Bognerb7aa2632014-04-18 21:48:40 +000077
Justin Bogner2b6c5372015-02-18 01:58:17 +000078
79ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
80IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
81 // Sanity check the buffer.
82 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
83 return instrprof_error::too_large;
Justin Bognerab89ed72015-02-16 21:28:58 +000084
Justin Bognerb7aa2632014-04-18 21:48:40 +000085 // Create the reader.
86 if (!IndexedInstrProfReader::hasFormat(*Buffer))
87 return instrprof_error::bad_magic;
Justin Bogner2b6c5372015-02-18 01:58:17 +000088 auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
Justin Bognerb7aa2632014-04-18 21:48:40 +000089
90 // Initialize the reader and return the result.
Justin Bognerab89ed72015-02-16 21:28:58 +000091 if (std::error_code EC = initializeReader(*Result))
92 return EC;
93
94 return std::move(Result);
Justin Bognerf8d79192014-03-21 17:24:48 +000095}
96
97void InstrProfIterator::Increment() {
98 if (Reader->readNextRecord(Record))
99 *this = InstrProfIterator();
100}
101
Nathan Slingerland4f823662015-11-13 03:47:58 +0000102bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {
103 // Verify that this really looks like plain ASCII text by checking a
104 // 'reasonable' number of characters (up to profile magic size).
105 size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
106 StringRef buffer = Buffer.getBufferStart();
Vedant Kumar2491dd12015-12-11 00:40:05 +0000107 return count == 0 ||
108 std::all_of(buffer.begin(), buffer.begin() + count,
109 [](char c) { return ::isprint(c) || ::isspace(c); });
Nathan Slingerland4f823662015-11-13 03:47:58 +0000110}
111
Rong Xu33c76c02016-02-10 17:18:30 +0000112// Read the profile variant flag from the header: ":FE" means this is a FE
113// generated profile. ":IR" means this is an IR level profile. Other strings
114// with a leading ':' will be reported an error format.
Xinliang David Lia716cc52015-12-20 06:22:13 +0000115std::error_code TextInstrProfReader::readHeader() {
116 Symtab.reset(new InstrProfSymtab());
Rong Xu33c76c02016-02-10 17:18:30 +0000117 bool IsIRInstr = false;
118 if (!Line->startswith(":")) {
119 IsIRLevelProfile = false;
120 return success();
121 }
122 StringRef Str = (Line)->substr(1);
123 if (Str.equals_lower("ir"))
124 IsIRInstr = true;
125 else if (Str.equals_lower("fe"))
126 IsIRInstr = false;
127 else
128 return instrprof_error::bad_header;
129
130 ++Line;
131 IsIRLevelProfile = IsIRInstr;
Xinliang David Lia716cc52015-12-20 06:22:13 +0000132 return success();
133}
134
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000135std::error_code
136TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
137
138#define CHECK_LINE_END(Line) \
139 if (Line.is_at_end()) \
140 return error(instrprof_error::truncated);
141#define READ_NUM(Str, Dst) \
142 if ((Str).getAsInteger(10, (Dst))) \
143 return error(instrprof_error::malformed);
144#define VP_READ_ADVANCE(Val) \
145 CHECK_LINE_END(Line); \
146 uint32_t Val; \
147 READ_NUM((*Line), (Val)); \
148 Line++;
149
150 if (Line.is_at_end())
151 return success();
Xinliang David Lia716cc52015-12-20 06:22:13 +0000152
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000153 uint32_t NumValueKinds;
154 if (Line->getAsInteger(10, NumValueKinds)) {
155 // No value profile data
156 return success();
157 }
158 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
159 return error(instrprof_error::malformed);
160 Line++;
161
162 for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
163 VP_READ_ADVANCE(ValueKind);
164 if (ValueKind > IPVK_Last)
165 return error(instrprof_error::malformed);
166 VP_READ_ADVANCE(NumValueSites);
167 if (!NumValueSites)
168 continue;
169
170 Record.reserveSites(VK, NumValueSites);
171 for (uint32_t S = 0; S < NumValueSites; S++) {
172 VP_READ_ADVANCE(NumValueData);
173
174 std::vector<InstrProfValueData> CurrentValues;
175 for (uint32_t V = 0; V < NumValueData; V++) {
176 CHECK_LINE_END(Line);
177 std::pair<StringRef, StringRef> VD = Line->split(':');
178 uint64_t TakenCount, Value;
Xinliang David Lia716cc52015-12-20 06:22:13 +0000179 if (VK == IPVK_IndirectCallTarget) {
180 Symtab->addFuncName(VD.first);
181 Value = IndexedInstrProf::ComputeHash(VD.first);
182 } else {
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000183 READ_NUM(VD.first, Value);
184 }
Xinliang David Lia716cc52015-12-20 06:22:13 +0000185 READ_NUM(VD.second, TakenCount);
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000186 CurrentValues.push_back({Value, TakenCount});
187 Line++;
188 }
189 Record.addValueData(VK, S, CurrentValues.data(), NumValueData, nullptr);
190 }
191 }
192 return success();
193
194#undef CHECK_LINE_END
195#undef READ_NUM
196#undef VP_READ_ADVANCE
197}
198
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000199std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
Justin Bognercf36a362014-07-29 22:29:23 +0000200 // Skip empty lines and comments.
201 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
Justin Bognerf8d79192014-03-21 17:24:48 +0000202 ++Line;
203 // If we hit EOF while looking for a name, we're done.
Xinliang David Lia716cc52015-12-20 06:22:13 +0000204 if (Line.is_at_end()) {
205 Symtab->finalizeSymtab();
Justin Bognerf8d79192014-03-21 17:24:48 +0000206 return error(instrprof_error::eof);
Xinliang David Lia716cc52015-12-20 06:22:13 +0000207 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000208
209 // Read the function name.
210 Record.Name = *Line++;
Xinliang David Lia716cc52015-12-20 06:22:13 +0000211 Symtab->addFuncName(Record.Name);
Justin Bognerf8d79192014-03-21 17:24:48 +0000212
213 // Read the function hash.
214 if (Line.is_at_end())
215 return error(instrprof_error::truncated);
Justin Bognerf95ca072015-03-09 18:54:49 +0000216 if ((Line++)->getAsInteger(0, Record.Hash))
Justin Bognerf8d79192014-03-21 17:24:48 +0000217 return error(instrprof_error::malformed);
218
219 // Read the number of counters.
220 uint64_t NumCounters;
221 if (Line.is_at_end())
222 return error(instrprof_error::truncated);
223 if ((Line++)->getAsInteger(10, NumCounters))
224 return error(instrprof_error::malformed);
Justin Bognerb59d7c72014-04-25 02:45:33 +0000225 if (NumCounters == 0)
226 return error(instrprof_error::malformed);
Justin Bognerf8d79192014-03-21 17:24:48 +0000227
228 // Read each counter and fill our internal storage with the values.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000229 Record.Counts.clear();
230 Record.Counts.reserve(NumCounters);
Justin Bognerf8d79192014-03-21 17:24:48 +0000231 for (uint64_t I = 0; I < NumCounters; ++I) {
232 if (Line.is_at_end())
233 return error(instrprof_error::truncated);
234 uint64_t Count;
235 if ((Line++)->getAsInteger(10, Count))
236 return error(instrprof_error::malformed);
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000237 Record.Counts.push_back(Count);
Justin Bognerf8d79192014-03-21 17:24:48 +0000238 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000239
Xinliang David Lie3bf4fd32015-12-14 18:44:01 +0000240 // Check if value profile data exists and read it if so.
241 if (std::error_code EC = readValueProfileData(Record))
242 return EC;
243
Xinliang David Lia716cc52015-12-20 06:22:13 +0000244 // This is needed to avoid two pass parsing because llvm-profdata
245 // does dumping while reading.
246 Symtab->finalizeSymtab();
Justin Bognerf8d79192014-03-21 17:24:48 +0000247 return success();
248}
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000249
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000250template <class IntPtrT>
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000251bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000252 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000253 return false;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000254 uint64_t Magic =
255 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000256 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
257 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000258}
259
260template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000261std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
Duncan P. N. Exon Smith09a67f42014-03-21 20:42:31 +0000262 if (!hasFormat(*DataBuffer))
263 return error(instrprof_error::bad_magic);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000264 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000265 return error(instrprof_error::bad_header);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000266 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
267 DataBuffer->getBufferStart());
268 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000269 return readHeader(*Header);
270}
271
Justin Bognera119f322014-05-16 00:38:00 +0000272template <class IntPtrT>
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000273std::error_code
274RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
Justin Bognera119f322014-05-16 00:38:00 +0000275 const char *End = DataBuffer->getBufferEnd();
276 // Skip zero padding between profiles.
277 while (CurrentPos != End && *CurrentPos == 0)
278 ++CurrentPos;
279 // If there's nothing left, we're done.
280 if (CurrentPos == End)
281 return instrprof_error::eof;
282 // If there isn't enough space for another header, this is probably just
283 // garbage at the end of the file.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000284 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
Justin Bognera119f322014-05-16 00:38:00 +0000285 return instrprof_error::malformed;
Justin Bogner54b11282014-09-12 21:22:55 +0000286 // The writer ensures each profile is padded to start at an aligned address.
287 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
288 return instrprof_error::malformed;
Justin Bognera119f322014-05-16 00:38:00 +0000289 // The magic should have the same byte order as in the previous header.
290 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000291 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
Justin Bognera119f322014-05-16 00:38:00 +0000292 return instrprof_error::bad_magic;
293
294 // There's another profile to read, so we need to process the header.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000295 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
Justin Bognera119f322014-05-16 00:38:00 +0000296 return readHeader(*Header);
297}
298
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000299template <class IntPtrT>
Xinliang David Lia716cc52015-12-20 06:22:13 +0000300void RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000301 Symtab.create(StringRef(NamesStart, NamesSize));
Xinliang David Lia716cc52015-12-20 06:22:13 +0000302 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000303 const IntPtrT FPtr = swap(I->FunctionPointer);
304 if (!FPtr)
305 continue;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000306 Symtab.mapAddress(FPtr, I->NameRef);
Xinliang David Lia716cc52015-12-20 06:22:13 +0000307 }
308 Symtab.finalizeSymtab();
309}
310
311template <class IntPtrT>
312std::error_code
313RawInstrProfReader<IntPtrT>::readHeader(const RawInstrProf::Header &Header) {
Rong Xu33c76c02016-02-10 17:18:30 +0000314 Version = swap(Header.Version);
315 if (GET_VERSION(Version) != RawInstrProf::Version)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000316 return error(instrprof_error::unsupported_version);
317
318 CountersDelta = swap(Header.CountersDelta);
319 NamesDelta = swap(Header.NamesDelta);
320 auto DataSize = swap(Header.DataSize);
321 auto CountersSize = swap(Header.CountersSize);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000322 NamesSize = swap(Header.NamesSize);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000323 auto ValueDataSize = swap(Header.ValueDataSize);
324 ValueKindLast = swap(Header.ValueKindLast);
325
326 auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
327 auto PaddingSize = getNumPaddingBytes(NamesSize);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000328
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000329 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000330 ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000331 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000332 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
333 size_t ProfileSize = ValueDataOffset + ValueDataSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000334
Justin Bognera119f322014-05-16 00:38:00 +0000335 auto *Start = reinterpret_cast<const char *>(&Header);
336 if (Start + ProfileSize > DataBuffer->getBufferEnd())
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +0000337 return error(instrprof_error::bad_header);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000338
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000339 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
340 Start + DataOffset);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000341 DataEnd = Data + DataSize;
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000342 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
343 NamesStart = Start + NamesOffset;
Xinliang David Lia716cc52015-12-20 06:22:13 +0000344 ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
Justin Bognera119f322014-05-16 00:38:00 +0000345 ProfileEnd = Start + ProfileSize;
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000346
Xinliang David Lia716cc52015-12-20 06:22:13 +0000347 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
348 createSymtab(*NewSymtab.get());
349 Symtab = std::move(NewSymtab);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000350 return success();
351}
352
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000353template <class IntPtrT>
Xinliang David Licf4a1282015-10-28 19:34:04 +0000354std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000355 Record.Name = getName(Data->NameRef);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000356 return success();
357}
358
359template <class IntPtrT>
360std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
361 InstrProfRecord &Record) {
362 Record.Hash = swap(Data->FuncHash);
363 return success();
364}
365
366template <class IntPtrT>
367std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
368 InstrProfRecord &Record) {
Justin Bognerb59d7c72014-04-25 02:45:33 +0000369 uint32_t NumCounters = swap(Data->NumCounters);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000370 IntPtrT CounterPtr = Data->CounterPtr;
Justin Bognerb59d7c72014-04-25 02:45:33 +0000371 if (NumCounters == 0)
372 return error(instrprof_error::malformed);
Xinliang David Licf4a1282015-10-28 19:34:04 +0000373
374 auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
375 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000376
377 // Check bounds.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000378 if (RawCounts.data() < CountersStart ||
Duncan P. N. Exon Smithd7d83472014-03-24 00:47:18 +0000379 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000380 return error(instrprof_error::malformed);
381
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000382 if (ShouldSwapBytes) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000383 Record.Counts.clear();
384 Record.Counts.reserve(RawCounts.size());
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000385 for (uint64_t Count : RawCounts)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000386 Record.Counts.push_back(swap(Count));
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000387 } else
388 Record.Counts = RawCounts;
389
Xinliang David Licf4a1282015-10-28 19:34:04 +0000390 return success();
391}
392
393template <class IntPtrT>
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000394std::error_code
395RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000396
397 Record.clearValueData();
Xinliang David Lid922c262015-12-11 06:53:53 +0000398 CurValueDataSize = 0;
399 // Need to match the logic in value profile dumper code in compiler-rt:
400 uint32_t NumValueKinds = 0;
401 for (uint32_t I = 0; I < IPVK_Last + 1; I++)
402 NumValueKinds += (Data->NumValueSites[I] != 0);
403
404 if (!NumValueKinds)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000405 return success();
406
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000407 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
Xinliang David Lid922c262015-12-11 06:53:53 +0000408 ValueProfData::getValueProfData(ValueDataStart,
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000409 (const unsigned char *)ProfileEnd,
410 getDataEndianness());
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000411
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000412 if (VDataPtrOrErr.getError())
413 return VDataPtrOrErr.getError();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000414
Adam Nemet2f36f052016-03-28 18:27:44 +0000415 // Note that besides deserialization, this also performs the conversion for
416 // indirect call targets. The function pointers from the raw profile are
417 // remapped into function name hashes.
Xinliang David Lia716cc52015-12-20 06:22:13 +0000418 VDataPtrOrErr.get()->deserializeTo(Record, &Symtab->getAddrHashMap());
Xinliang David Lid922c262015-12-11 06:53:53 +0000419 CurValueDataSize = VDataPtrOrErr.get()->getSize();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000420 return success();
421}
422
423template <class IntPtrT>
Xinliang David Li01cb9bd2015-12-04 01:02:10 +0000424std::error_code
425RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
Xinliang David Licf4a1282015-10-28 19:34:04 +0000426 if (atEnd())
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000427 if (std::error_code EC = readNextHeader(ProfileEnd))
428 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000429
430 // Read name ad set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000431 if (std::error_code EC = readName(Record))
432 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000433
434 // Read FuncHash and set it in Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000435 if (std::error_code EC = readFuncHash(Record))
436 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000437
438 // Read raw counts and set Record.
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000439 if (std::error_code EC = readRawCounts(Record))
440 return EC;
Xinliang David Licf4a1282015-10-28 19:34:04 +0000441
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000442 // Read value data and set Record.
Xinliang David Li2d4803e2015-12-10 23:48:05 +0000443 if (std::error_code EC = readValueProfilingData(Record))
444 return EC;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000445
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000446 // Iterate.
Xinliang David Licf4a1282015-10-28 19:34:04 +0000447 advanceData();
Duncan P. N. Exon Smith24b4b652014-03-21 18:26:05 +0000448 return success();
449}
Duncan P. N. Exon Smith46803612014-03-23 03:38:12 +0000450
451namespace llvm {
452template class RawInstrProfReader<uint32_t>;
453template class RawInstrProfReader<uint64_t>;
454}
Justin Bognerb7aa2632014-04-18 21:48:40 +0000455
Justin Bognerb5d368e2014-04-18 22:00:22 +0000456InstrProfLookupTrait::hash_value_type
457InstrProfLookupTrait::ComputeHash(StringRef K) {
458 return IndexedInstrProf::ComputeHash(HashType, K);
459}
460
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000461typedef InstrProfLookupTrait::data_type data_type;
462typedef InstrProfLookupTrait::offset_type offset_type;
463
Xinliang David Libe969c22015-11-28 05:06:00 +0000464bool InstrProfLookupTrait::readValueProfilingData(
Justin Bogner9e9a0572015-09-29 22:13:58 +0000465 const unsigned char *&D, const unsigned char *const End) {
Xinliang David Li99556872015-11-17 23:00:40 +0000466 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
467 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000468
Xinliang David Liee415892015-11-10 00:24:45 +0000469 if (VDataPtrOrErr.getError())
Justin Bogner9e9a0572015-09-29 22:13:58 +0000470 return false;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000471
Xinliang David Lia716cc52015-12-20 06:22:13 +0000472 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
Xinliang David Liee415892015-11-10 00:24:45 +0000473 D += VDataPtrOrErr.get()->TotalSize;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000474
Justin Bogner9e9a0572015-09-29 22:13:58 +0000475 return true;
476}
477
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000478data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
479 offset_type N) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000480 // Check if the data is corrupt. If so, don't try to read it.
481 if (N % sizeof(uint64_t))
482 return data_type();
483
484 DataBuffer.clear();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000485 std::vector<uint64_t> CounterBuffer;
Justin Bogner9e9a0572015-09-29 22:13:58 +0000486
487 using namespace support;
488 const unsigned char *End = D + N;
489 while (D < End) {
Xinliang David Lic7583872015-10-13 16:35:59 +0000490 // Read hash.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000491 if (D + sizeof(uint64_t) >= End)
492 return data_type();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000493 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
494
Rong Xu33c76c02016-02-10 17:18:30 +0000495 // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000496 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
Xinliang David Lic7583872015-10-13 16:35:59 +0000497 // If format version is different then read the number of counters.
Rong Xu33c76c02016-02-10 17:18:30 +0000498 if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) {
Justin Bogner9e9a0572015-09-29 22:13:58 +0000499 if (D + sizeof(uint64_t) > End)
500 return data_type();
501 CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
502 }
Xinliang David Lic7583872015-10-13 16:35:59 +0000503 // Read counter values.
Justin Bogner9e9a0572015-09-29 22:13:58 +0000504 if (D + CountsSize * sizeof(uint64_t) > End)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000505 return data_type();
506
507 CounterBuffer.clear();
Justin Bogner9e9a0572015-09-29 22:13:58 +0000508 CounterBuffer.reserve(CountsSize);
509 for (uint64_t J = 0; J < CountsSize; ++J)
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000510 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
511
Xinliang David Li2004f002015-11-02 05:08:23 +0000512 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
Justin Bogner9e9a0572015-09-29 22:13:58 +0000513
Xinliang David Lic7583872015-10-13 16:35:59 +0000514 // Read value profiling data.
Rong Xu33c76c02016-02-10 17:18:30 +0000515 if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 &&
Xinliang David Lia6b2c4f2016-01-14 02:47:01 +0000516 !readValueProfilingData(D, End)) {
Justin Bogner9e9a0572015-09-29 22:13:58 +0000517 DataBuffer.clear();
518 return data_type();
519 }
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000520 }
521 return DataBuffer;
522}
523
Xinliang David Lia28306d2015-12-01 20:26:26 +0000524template <typename HashTableImpl>
525std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
526 StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
527 auto Iter = HashTable->find(FuncName);
528 if (Iter == HashTable->end())
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000529 return instrprof_error::unknown_function;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000530
531 Data = (*Iter);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000532 if (Data.empty())
533 return instrprof_error::malformed;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000534
535 return instrprof_error::success;
536}
537
Xinliang David Lia28306d2015-12-01 20:26:26 +0000538template <typename HashTableImpl>
539std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
Xinliang David Li140f4c42015-10-28 04:20:31 +0000540 ArrayRef<InstrProfRecord> &Data) {
Xinliang David Lia28306d2015-12-01 20:26:26 +0000541 if (atEnd())
542 return instrprof_error::eof;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000543
544 Data = *RecordIterator;
545
Xinliang David Li2d4803e2015-12-10 23:48:05 +0000546 if (Data.empty())
547 return instrprof_error::malformed;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000548
549 return instrprof_error::success;
550}
551
Xinliang David Lia28306d2015-12-01 20:26:26 +0000552template <typename HashTableImpl>
553InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
554 const unsigned char *Buckets, const unsigned char *const Payload,
555 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
556 uint64_t Version) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000557 FormatVersion = Version;
Xinliang David Lia28306d2015-12-01 20:26:26 +0000558 HashTable.reset(HashTableImpl::Create(
559 Buckets, Payload, Base,
560 typename HashTableImpl::InfoType(HashType, Version)));
Xinliang David Lia28306d2015-12-01 20:26:26 +0000561 RecordIterator = HashTable->data_begin();
Xinliang David Li140f4c42015-10-28 04:20:31 +0000562}
563
Justin Bognerb7aa2632014-04-18 21:48:40 +0000564bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000565 if (DataBuffer.getBufferSize() < 8)
566 return false;
Justin Bognerb7aa2632014-04-18 21:48:40 +0000567 using namespace support;
568 uint64_t Magic =
569 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
Xinliang David Lic7583872015-10-13 16:35:59 +0000570 // Verify that it's magical.
Justin Bognerb7aa2632014-04-18 21:48:40 +0000571 return Magic == IndexedInstrProf::Magic;
572}
573
Xinliang David Li6c93ee82016-02-03 04:08:18 +0000574const unsigned char *
575IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
576 const unsigned char *Cur) {
577 using namespace support;
578 if (Version >= IndexedInstrProf::Version4) {
579 const IndexedInstrProf::Summary *SummaryInLE =
580 reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
581 uint64_t NFields =
582 endian::byte_swap<uint64_t, little>(SummaryInLE->NumSummaryFields);
583 uint64_t NEntries =
584 endian::byte_swap<uint64_t, little>(SummaryInLE->NumCutoffEntries);
585 uint32_t SummarySize =
586 IndexedInstrProf::Summary::getSize(NFields, NEntries);
587 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
588 IndexedInstrProf::allocSummary(SummarySize);
589
590 const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
591 uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
592 for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
593 Dst[I] = endian::byte_swap<uint64_t, little>(Src[I]);
594
Easwaran Raman43095702016-02-17 18:18:47 +0000595 // initialize InstrProfSummary using the SummaryData from disk.
596 this->Summary = llvm::make_unique<InstrProfSummary>(*(SummaryData.get()));
Xinliang David Li6c93ee82016-02-03 04:08:18 +0000597 return Cur + SummarySize;
598 } else {
599 // For older version of profile data, we need to compute on the fly:
600 using namespace IndexedInstrProf;
Easwaran Raman40ee23d2016-02-19 03:15:33 +0000601 this->Summary =
602 llvm::make_unique<InstrProfSummary>(ProfileSummary::DefaultCutoffs);
Xinliang David Li6c93ee82016-02-03 04:08:18 +0000603 this->Summary->computeDetailedSummary();
604 return Cur;
605 }
606}
607
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000608std::error_code IndexedInstrProfReader::readHeader() {
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000609 const unsigned char *Start =
610 (const unsigned char *)DataBuffer->getBufferStart();
Justin Bognerb7aa2632014-04-18 21:48:40 +0000611 const unsigned char *Cur = Start;
Aaron Ballmana7c9ed52014-05-01 17:16:24 +0000612 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000613 return error(instrprof_error::truncated);
614
615 using namespace support;
616
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000617 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
618 Cur += sizeof(IndexedInstrProf::Header);
619
Justin Bognerb7aa2632014-04-18 21:48:40 +0000620 // Check the magic number.
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000621 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000622 if (Magic != IndexedInstrProf::Magic)
623 return error(instrprof_error::bad_magic);
624
625 // Read the version.
Xinliang David Li140f4c42015-10-28 04:20:31 +0000626 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
Rong Xu33c76c02016-02-10 17:18:30 +0000627 if (GET_VERSION(FormatVersion) >
628 IndexedInstrProf::ProfVersion::CurrentVersion)
Justin Bognerb7aa2632014-04-18 21:48:40 +0000629 return error(instrprof_error::unsupported_version);
630
Xinliang David Li6c93ee82016-02-03 04:08:18 +0000631 Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000632
633 // Read the hash type and start offset.
634 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000635 endian::byte_swap<uint64_t, little>(Header->HashType));
Justin Bognerb7aa2632014-04-18 21:48:40 +0000636 if (HashType > IndexedInstrProf::HashT::Last)
637 return error(instrprof_error::unsupported_hash_type);
Xinliang David Lidab183ed2015-10-18 01:02:29 +0000638
639 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000640
641 // The rest of the file is an on disk hash table.
Xinliang David Lia28306d2015-12-01 20:26:26 +0000642 InstrProfReaderIndexBase *IndexPtr = nullptr;
643 IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
644 Start + HashOffset, Cur, Start, HashType, FormatVersion);
645 Index.reset(IndexPtr);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000646 return success();
647}
648
Xinliang David Lia716cc52015-12-20 06:22:13 +0000649InstrProfSymtab &IndexedInstrProfReader::getSymtab() {
650 if (Symtab.get())
651 return *Symtab.get();
652
653 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
654 Index->populateSymtab(*NewSymtab.get());
655
656 Symtab = std::move(NewSymtab);
657 return *Symtab.get();
658}
659
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000660ErrorOr<InstrProfRecord>
661IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
662 uint64_t FuncHash) {
Xinliang David Li140f4c42015-10-28 04:20:31 +0000663 ArrayRef<InstrProfRecord> Data;
Xinliang David Lia28306d2015-12-01 20:26:26 +0000664 std::error_code EC = Index->getRecords(FuncName, Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000665 if (EC != instrprof_error::success)
666 return EC;
Justin Bogner821d7472014-08-01 22:50:07 +0000667 // Found it. Look for counters with the right hash.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000668 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
Justin Bogner821d7472014-08-01 22:50:07 +0000669 // Check for a match and fill the vector if there is one.
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000670 if (Data[I].Hash == FuncHash) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000671 return std::move(Data[I]);
Justin Bogner821d7472014-08-01 22:50:07 +0000672 }
673 }
674 return error(instrprof_error::hash_mismatch);
Justin Bognerb7aa2632014-04-18 21:48:40 +0000675}
676
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000677std::error_code
678IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
679 std::vector<uint64_t> &Counts) {
Xinliang David Li2004f002015-11-02 05:08:23 +0000680 ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
Xinliang David Li6aa216c2015-11-06 07:54:21 +0000681 if (std::error_code EC = Record.getError())
682 return EC;
Xinliang David Li2004f002015-11-02 05:08:23 +0000683
684 Counts = Record.get().Counts;
685 return success();
686}
687
Xinliang David Li140f4c42015-10-28 04:20:31 +0000688std::error_code IndexedInstrProfReader::readNextRecord(
689 InstrProfRecord &Record) {
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000690 static unsigned RecordIndex = 0;
Xinliang David Li140f4c42015-10-28 04:20:31 +0000691
692 ArrayRef<InstrProfRecord> Data;
693
Xinliang David Lia28306d2015-12-01 20:26:26 +0000694 std::error_code EC = Index->getRecords(Data);
Xinliang David Li4c3ab812015-11-12 00:32:17 +0000695 if (EC != instrprof_error::success)
696 return error(EC);
Xinliang David Li140f4c42015-10-28 04:20:31 +0000697
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000698 Record = Data[RecordIndex++];
699 if (RecordIndex >= Data.size()) {
Xinliang David Lia28306d2015-12-01 20:26:26 +0000700 Index->advanceToNextKey();
Justin Bogner3a7d44c2015-06-22 23:58:05 +0000701 RecordIndex = 0;
Justin Bogner821d7472014-08-01 22:50:07 +0000702 }
Justin Bognerb7aa2632014-04-18 21:48:40 +0000703 return success();
704}