[sanitizer] Improve FreeBSD ASLR detection
[llvm-project.git] / llvm / lib / ProfileData / InstrProfReader.cpp
blob9ee859bfb7629962a6c78d826a112172756ead4a
1 //===- InstrProfReader.cpp - Instrumented profiling reader ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for reading profiling data for clang's
10 // instrumentation based PGO and coverage.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ProfileData/InstrProfReader.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/IR/ProfileSummary.h"
21 #include "llvm/ProfileData/InstrProf.h"
22 #include "llvm/ProfileData/ProfileCommon.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/ErrorOr.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/SwapByteOrder.h"
28 #include "llvm/Support/SymbolRemappingReader.h"
29 #include <algorithm>
30 #include <cctype>
31 #include <cstddef>
32 #include <cstdint>
33 #include <limits>
34 #include <memory>
35 #include <system_error>
36 #include <utility>
37 #include <vector>
39 using namespace llvm;
41 static Expected<std::unique_ptr<MemoryBuffer>>
42 setupMemoryBuffer(const Twine &Path) {
43 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
44 MemoryBuffer::getFileOrSTDIN(Path, /*IsText=*/true);
45 if (std::error_code EC = BufferOrErr.getError())
46 return errorCodeToError(EC);
47 return std::move(BufferOrErr.get());
50 static Error initializeReader(InstrProfReader &Reader) {
51 return Reader.readHeader();
54 Expected<std::unique_ptr<InstrProfReader>>
55 InstrProfReader::create(const Twine &Path,
56 const InstrProfCorrelator *Correlator) {
57 // Set up the buffer to read.
58 auto BufferOrError = setupMemoryBuffer(Path);
59 if (Error E = BufferOrError.takeError())
60 return std::move(E);
61 return InstrProfReader::create(std::move(BufferOrError.get()), Correlator);
64 Expected<std::unique_ptr<InstrProfReader>>
65 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,
66 const InstrProfCorrelator *Correlator) {
67 // Sanity check the buffer.
68 if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint64_t>::max())
69 return make_error<InstrProfError>(instrprof_error::too_large);
71 if (Buffer->getBufferSize() == 0)
72 return make_error<InstrProfError>(instrprof_error::empty_raw_profile);
74 std::unique_ptr<InstrProfReader> Result;
75 // Create the reader.
76 if (IndexedInstrProfReader::hasFormat(*Buffer))
77 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
78 else if (RawInstrProfReader64::hasFormat(*Buffer))
79 Result.reset(new RawInstrProfReader64(std::move(Buffer), Correlator));
80 else if (RawInstrProfReader32::hasFormat(*Buffer))
81 Result.reset(new RawInstrProfReader32(std::move(Buffer), Correlator));
82 else if (TextInstrProfReader::hasFormat(*Buffer))
83 Result.reset(new TextInstrProfReader(std::move(Buffer)));
84 else
85 return make_error<InstrProfError>(instrprof_error::unrecognized_format);
87 // Initialize the reader and return the result.
88 if (Error E = initializeReader(*Result))
89 return std::move(E);
91 return std::move(Result);
94 Expected<std::unique_ptr<IndexedInstrProfReader>>
95 IndexedInstrProfReader::create(const Twine &Path, const Twine &RemappingPath) {
96 // Set up the buffer to read.
97 auto BufferOrError = setupMemoryBuffer(Path);
98 if (Error E = BufferOrError.takeError())
99 return std::move(E);
101 // Set up the remapping buffer if requested.
102 std::unique_ptr<MemoryBuffer> RemappingBuffer;
103 std::string RemappingPathStr = RemappingPath.str();
104 if (!RemappingPathStr.empty()) {
105 auto RemappingBufferOrError = setupMemoryBuffer(RemappingPathStr);
106 if (Error E = RemappingBufferOrError.takeError())
107 return std::move(E);
108 RemappingBuffer = std::move(RemappingBufferOrError.get());
111 return IndexedInstrProfReader::create(std::move(BufferOrError.get()),
112 std::move(RemappingBuffer));
115 Expected<std::unique_ptr<IndexedInstrProfReader>>
116 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,
117 std::unique_ptr<MemoryBuffer> RemappingBuffer) {
118 if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint64_t>::max())
119 return make_error<InstrProfError>(instrprof_error::too_large);
121 // Create the reader.
122 if (!IndexedInstrProfReader::hasFormat(*Buffer))
123 return make_error<InstrProfError>(instrprof_error::bad_magic);
124 auto Result = std::make_unique<IndexedInstrProfReader>(
125 std::move(Buffer), std::move(RemappingBuffer));
127 // Initialize the reader and return the result.
128 if (Error E = initializeReader(*Result))
129 return std::move(E);
131 return std::move(Result);
134 void InstrProfIterator::Increment() {
135 if (auto E = Reader->readNextRecord(Record)) {
136 // Handle errors in the reader.
137 InstrProfError::take(std::move(E));
138 *this = InstrProfIterator();
142 bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {
143 // Verify that this really looks like plain ASCII text by checking a
144 // 'reasonable' number of characters (up to profile magic size).
145 size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
146 StringRef buffer = Buffer.getBufferStart();
147 return count == 0 ||
148 std::all_of(buffer.begin(), buffer.begin() + count,
149 [](char c) { return isPrint(c) || isSpace(c); });
152 // Read the profile variant flag from the header: ":FE" means this is a FE
153 // generated profile. ":IR" means this is an IR level profile. Other strings
154 // with a leading ':' will be reported an error format.
155 Error TextInstrProfReader::readHeader() {
156 Symtab.reset(new InstrProfSymtab());
157 bool IsIRInstr = false;
158 bool IsEntryFirst = false;
159 bool IsCS = false;
161 while (Line->startswith(":")) {
162 StringRef Str = Line->substr(1);
163 if (Str.equals_insensitive("ir"))
164 IsIRInstr = true;
165 else if (Str.equals_insensitive("fe"))
166 IsIRInstr = false;
167 else if (Str.equals_insensitive("csir")) {
168 IsIRInstr = true;
169 IsCS = true;
170 } else if (Str.equals_insensitive("entry_first"))
171 IsEntryFirst = true;
172 else if (Str.equals_insensitive("not_entry_first"))
173 IsEntryFirst = false;
174 else
175 return error(instrprof_error::bad_header);
176 ++Line;
178 IsIRLevelProfile = IsIRInstr;
179 InstrEntryBBEnabled = IsEntryFirst;
180 HasCSIRLevelProfile = IsCS;
181 return success();
184 Error
185 TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
187 #define CHECK_LINE_END(Line) \
188 if (Line.is_at_end()) \
189 return error(instrprof_error::truncated);
190 #define READ_NUM(Str, Dst) \
191 if ((Str).getAsInteger(10, (Dst))) \
192 return error(instrprof_error::malformed);
193 #define VP_READ_ADVANCE(Val) \
194 CHECK_LINE_END(Line); \
195 uint32_t Val; \
196 READ_NUM((*Line), (Val)); \
197 Line++;
199 if (Line.is_at_end())
200 return success();
202 uint32_t NumValueKinds;
203 if (Line->getAsInteger(10, NumValueKinds)) {
204 // No value profile data
205 return success();
207 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
208 return error(instrprof_error::malformed,
209 "number of value kinds is invalid");
210 Line++;
212 for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
213 VP_READ_ADVANCE(ValueKind);
214 if (ValueKind > IPVK_Last)
215 return error(instrprof_error::malformed, "value kind is invalid");
217 VP_READ_ADVANCE(NumValueSites);
218 if (!NumValueSites)
219 continue;
221 Record.reserveSites(VK, NumValueSites);
222 for (uint32_t S = 0; S < NumValueSites; S++) {
223 VP_READ_ADVANCE(NumValueData);
225 std::vector<InstrProfValueData> CurrentValues;
226 for (uint32_t V = 0; V < NumValueData; V++) {
227 CHECK_LINE_END(Line);
228 std::pair<StringRef, StringRef> VD = Line->rsplit(':');
229 uint64_t TakenCount, Value;
230 if (ValueKind == IPVK_IndirectCallTarget) {
231 if (InstrProfSymtab::isExternalSymbol(VD.first)) {
232 Value = 0;
233 } else {
234 if (Error E = Symtab->addFuncName(VD.first))
235 return E;
236 Value = IndexedInstrProf::ComputeHash(VD.first);
238 } else {
239 READ_NUM(VD.first, Value);
241 READ_NUM(VD.second, TakenCount);
242 CurrentValues.push_back({Value, TakenCount});
243 Line++;
245 Record.addValueData(ValueKind, S, CurrentValues.data(), NumValueData,
246 nullptr);
249 return success();
251 #undef CHECK_LINE_END
252 #undef READ_NUM
253 #undef VP_READ_ADVANCE
256 Error TextInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {
257 // Skip empty lines and comments.
258 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
259 ++Line;
260 // If we hit EOF while looking for a name, we're done.
261 if (Line.is_at_end()) {
262 return error(instrprof_error::eof);
265 // Read the function name.
266 Record.Name = *Line++;
267 if (Error E = Symtab->addFuncName(Record.Name))
268 return error(std::move(E));
270 // Read the function hash.
271 if (Line.is_at_end())
272 return error(instrprof_error::truncated);
273 if ((Line++)->getAsInteger(0, Record.Hash))
274 return error(instrprof_error::malformed,
275 "function hash is not a valid integer");
277 // Read the number of counters.
278 uint64_t NumCounters;
279 if (Line.is_at_end())
280 return error(instrprof_error::truncated);
281 if ((Line++)->getAsInteger(10, NumCounters))
282 return error(instrprof_error::malformed,
283 "number of counters is not a valid integer");
284 if (NumCounters == 0)
285 return error(instrprof_error::malformed, "number of counters is zero");
287 // Read each counter and fill our internal storage with the values.
288 Record.Clear();
289 Record.Counts.reserve(NumCounters);
290 for (uint64_t I = 0; I < NumCounters; ++I) {
291 if (Line.is_at_end())
292 return error(instrprof_error::truncated);
293 uint64_t Count;
294 if ((Line++)->getAsInteger(10, Count))
295 return error(instrprof_error::malformed, "count is invalid");
296 Record.Counts.push_back(Count);
299 // Check if value profile data exists and read it if so.
300 if (Error E = readValueProfileData(Record))
301 return error(std::move(E));
303 return success();
306 template <class IntPtrT>
307 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
308 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
309 return false;
310 uint64_t Magic =
311 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
312 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
313 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
316 template <class IntPtrT>
317 Error RawInstrProfReader<IntPtrT>::readHeader() {
318 if (!hasFormat(*DataBuffer))
319 return error(instrprof_error::bad_magic);
320 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
321 return error(instrprof_error::bad_header);
322 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
323 DataBuffer->getBufferStart());
324 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
325 return readHeader(*Header);
328 template <class IntPtrT>
329 Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
330 const char *End = DataBuffer->getBufferEnd();
331 // Skip zero padding between profiles.
332 while (CurrentPos != End && *CurrentPos == 0)
333 ++CurrentPos;
334 // If there's nothing left, we're done.
335 if (CurrentPos == End)
336 return make_error<InstrProfError>(instrprof_error::eof);
337 // If there isn't enough space for another header, this is probably just
338 // garbage at the end of the file.
339 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
340 return make_error<InstrProfError>(instrprof_error::malformed,
341 "not enough space for another header");
342 // The writer ensures each profile is padded to start at an aligned address.
343 if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))
344 return make_error<InstrProfError>(instrprof_error::malformed,
345 "insufficient padding");
346 // The magic should have the same byte order as in the previous header.
347 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
348 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
349 return make_error<InstrProfError>(instrprof_error::bad_magic);
351 // There's another profile to read, so we need to process the header.
352 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
353 return readHeader(*Header);
356 template <class IntPtrT>
357 Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
358 if (Error E = Symtab.create(StringRef(NamesStart, NamesEnd - NamesStart)))
359 return error(std::move(E));
360 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
361 const IntPtrT FPtr = swap(I->FunctionPointer);
362 if (!FPtr)
363 continue;
364 Symtab.mapAddress(FPtr, I->NameRef);
366 return success();
369 template <class IntPtrT>
370 Error RawInstrProfReader<IntPtrT>::readHeader(
371 const RawInstrProf::Header &Header) {
372 Version = swap(Header.Version);
373 if (GET_VERSION(Version) != RawInstrProf::Version)
374 return error(instrprof_error::unsupported_version);
375 if (useDebugInfoCorrelate() && !Correlator)
376 return error(instrprof_error::missing_debug_info_for_correlation);
377 if (!useDebugInfoCorrelate() && Correlator)
378 return error(instrprof_error::unexpected_debug_info_for_correlation);
380 BinaryIdsSize = swap(Header.BinaryIdsSize);
381 if (BinaryIdsSize % sizeof(uint64_t))
382 return error(instrprof_error::bad_header);
384 CountersDelta = swap(Header.CountersDelta);
385 NamesDelta = swap(Header.NamesDelta);
386 auto NumData = swap(Header.NumData);
387 auto PaddingBytesBeforeCounters = swap(Header.PaddingBytesBeforeCounters);
388 auto CountersSize = swap(Header.NumCounters) * getCounterTypeSize();
389 auto PaddingBytesAfterCounters = swap(Header.PaddingBytesAfterCounters);
390 auto NamesSize = swap(Header.NamesSize);
391 ValueKindLast = swap(Header.ValueKindLast);
393 auto DataSize = NumData * sizeof(RawInstrProf::ProfileData<IntPtrT>);
394 auto PaddingSize = getNumPaddingBytes(NamesSize);
396 // Profile data starts after profile header and binary ids if exist.
397 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header) + BinaryIdsSize;
398 ptrdiff_t CountersOffset = DataOffset + DataSize + PaddingBytesBeforeCounters;
399 ptrdiff_t NamesOffset =
400 CountersOffset + CountersSize + PaddingBytesAfterCounters;
401 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
403 auto *Start = reinterpret_cast<const char *>(&Header);
404 if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
405 return error(instrprof_error::bad_header);
407 if (Correlator) {
408 // These sizes in the raw file are zero because we constructed them in the
409 // Correlator.
410 assert(DataSize == 0 && NamesSize == 0);
411 assert(CountersDelta == 0 && NamesDelta == 0);
412 Data = Correlator->getDataPointer();
413 DataEnd = Data + Correlator->getDataSize();
414 NamesStart = Correlator->getCompressedNamesPointer();
415 NamesEnd = NamesStart + Correlator->getCompressedNamesSize();
416 } else {
417 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
418 Start + DataOffset);
419 DataEnd = Data + NumData;
420 NamesStart = Start + NamesOffset;
421 NamesEnd = NamesStart + NamesSize;
424 // Binary ids start just after the header.
425 BinaryIdsStart =
426 reinterpret_cast<const uint8_t *>(&Header) + sizeof(RawInstrProf::Header);
427 CountersStart = Start + CountersOffset;
428 CountersEnd = CountersStart + CountersSize;
429 ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
431 const uint8_t *BufferEnd = (const uint8_t *)DataBuffer->getBufferEnd();
432 if (BinaryIdsStart + BinaryIdsSize > BufferEnd)
433 return error(instrprof_error::bad_header);
435 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
436 if (Error E = createSymtab(*NewSymtab.get()))
437 return E;
439 Symtab = std::move(NewSymtab);
440 return success();
443 template <class IntPtrT>
444 Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) {
445 Record.Name = getName(Data->NameRef);
446 return success();
449 template <class IntPtrT>
450 Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) {
451 Record.Hash = swap(Data->FuncHash);
452 return success();
455 template <class IntPtrT>
456 Error RawInstrProfReader<IntPtrT>::readRawCounts(
457 InstrProfRecord &Record) {
458 uint32_t NumCounters = swap(Data->NumCounters);
459 if (NumCounters == 0)
460 return error(instrprof_error::malformed, "number of counters is zero");
462 ptrdiff_t CounterBaseOffset = swap(Data->CounterPtr) - CountersDelta;
463 if (CounterBaseOffset < 0)
464 return error(
465 instrprof_error::malformed,
466 ("counter offset " + Twine(CounterBaseOffset) + " is negative").str());
468 if (CounterBaseOffset >= CountersEnd - CountersStart)
469 return error(instrprof_error::malformed,
470 ("counter offset " + Twine(CounterBaseOffset) +
471 " is greater than the maximum counter offset " +
472 Twine(CountersEnd - CountersStart - 1))
473 .str());
475 uint64_t MaxNumCounters =
476 (CountersEnd - (CountersStart + CounterBaseOffset)) /
477 getCounterTypeSize();
478 if (NumCounters > MaxNumCounters)
479 return error(instrprof_error::malformed,
480 ("number of counters " + Twine(NumCounters) +
481 " is greater than the maximum number of counters " +
482 Twine(MaxNumCounters))
483 .str());
485 Record.Counts.clear();
486 Record.Counts.reserve(NumCounters);
487 for (uint32_t I = 0; I < NumCounters; I++) {
488 const auto *CounterValue = reinterpret_cast<const uint64_t *>(
489 CountersStart + CounterBaseOffset + I * getCounterTypeSize());
490 Record.Counts.push_back(swap(*CounterValue));
493 return success();
496 template <class IntPtrT>
497 Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
498 InstrProfRecord &Record) {
499 Record.clearValueData();
500 CurValueDataSize = 0;
501 // Need to match the logic in value profile dumper code in compiler-rt:
502 uint32_t NumValueKinds = 0;
503 for (uint32_t I = 0; I < IPVK_Last + 1; I++)
504 NumValueKinds += (Data->NumValueSites[I] != 0);
506 if (!NumValueKinds)
507 return success();
509 Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
510 ValueProfData::getValueProfData(
511 ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
512 getDataEndianness());
514 if (Error E = VDataPtrOrErr.takeError())
515 return E;
517 // Note that besides deserialization, this also performs the conversion for
518 // indirect call targets. The function pointers from the raw profile are
519 // remapped into function name hashes.
520 VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get());
521 CurValueDataSize = VDataPtrOrErr.get()->getSize();
522 return success();
525 template <class IntPtrT>
526 Error RawInstrProfReader<IntPtrT>::readNextRecord(NamedInstrProfRecord &Record) {
527 if (atEnd())
528 // At this point, ValueDataStart field points to the next header.
529 if (Error E = readNextHeader(getNextHeaderPos()))
530 return error(std::move(E));
532 // Read name ad set it in Record.
533 if (Error E = readName(Record))
534 return error(std::move(E));
536 // Read FuncHash and set it in Record.
537 if (Error E = readFuncHash(Record))
538 return error(std::move(E));
540 // Read raw counts and set Record.
541 if (Error E = readRawCounts(Record))
542 return error(std::move(E));
544 // Read value data and set Record.
545 if (Error E = readValueProfilingData(Record))
546 return error(std::move(E));
548 // Iterate.
549 advanceData();
550 return success();
553 static size_t RoundUp(size_t size, size_t align) {
554 return (size + align - 1) & ~(align - 1);
557 template <class IntPtrT>
558 Error RawInstrProfReader<IntPtrT>::printBinaryIds(raw_ostream &OS) {
559 if (BinaryIdsSize == 0)
560 return success();
562 OS << "Binary IDs: \n";
563 const uint8_t *BI = BinaryIdsStart;
564 const uint8_t *BIEnd = BinaryIdsStart + BinaryIdsSize;
565 while (BI < BIEnd) {
566 size_t Remaining = BIEnd - BI;
568 // There should be enough left to read the binary ID size field.
569 if (Remaining < sizeof(uint64_t))
570 return make_error<InstrProfError>(
571 instrprof_error::malformed,
572 "not enough data to read binary id length");
574 uint64_t BinaryIdLen = swap(*reinterpret_cast<const uint64_t *>(BI));
576 // There should be enough left to read the binary ID size field, and the
577 // binary ID.
578 if (Remaining < sizeof(BinaryIdLen) + BinaryIdLen)
579 return make_error<InstrProfError>(
580 instrprof_error::malformed, "not enough data to read binary id data");
582 // Increment by binary id length data type size.
583 BI += sizeof(BinaryIdLen);
584 if (BI > (const uint8_t *)DataBuffer->getBufferEnd())
585 return make_error<InstrProfError>(
586 instrprof_error::malformed,
587 "binary id that is read is bigger than buffer size");
589 for (uint64_t I = 0; I < BinaryIdLen; I++)
590 OS << format("%02x", BI[I]);
591 OS << "\n";
593 // Increment by binary id data length, rounded to the next 8 bytes. This
594 // accounts for the zero-padding after each build ID.
595 BI += RoundUp(BinaryIdLen, sizeof(uint64_t));
596 if (BI > (const uint8_t *)DataBuffer->getBufferEnd())
597 return make_error<InstrProfError>(instrprof_error::malformed);
600 return success();
603 namespace llvm {
605 template class RawInstrProfReader<uint32_t>;
606 template class RawInstrProfReader<uint64_t>;
608 } // end namespace llvm
610 InstrProfLookupTrait::hash_value_type
611 InstrProfLookupTrait::ComputeHash(StringRef K) {
612 return IndexedInstrProf::ComputeHash(HashType, K);
615 using data_type = InstrProfLookupTrait::data_type;
616 using offset_type = InstrProfLookupTrait::offset_type;
618 bool InstrProfLookupTrait::readValueProfilingData(
619 const unsigned char *&D, const unsigned char *const End) {
620 Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
621 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
623 if (VDataPtrOrErr.takeError())
624 return false;
626 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
627 D += VDataPtrOrErr.get()->TotalSize;
629 return true;
632 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
633 offset_type N) {
634 using namespace support;
636 // Check if the data is corrupt. If so, don't try to read it.
637 if (N % sizeof(uint64_t))
638 return data_type();
640 DataBuffer.clear();
641 std::vector<uint64_t> CounterBuffer;
643 const unsigned char *End = D + N;
644 while (D < End) {
645 // Read hash.
646 if (D + sizeof(uint64_t) >= End)
647 return data_type();
648 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
650 // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
651 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
652 // If format version is different then read the number of counters.
653 if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) {
654 if (D + sizeof(uint64_t) > End)
655 return data_type();
656 CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
658 // Read counter values.
659 if (D + CountsSize * sizeof(uint64_t) > End)
660 return data_type();
662 CounterBuffer.clear();
663 CounterBuffer.reserve(CountsSize);
664 for (uint64_t J = 0; J < CountsSize; ++J)
665 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
667 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
669 // Read value profiling data.
670 if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 &&
671 !readValueProfilingData(D, End)) {
672 DataBuffer.clear();
673 return data_type();
676 return DataBuffer;
679 template <typename HashTableImpl>
680 Error InstrProfReaderIndex<HashTableImpl>::getRecords(
681 StringRef FuncName, ArrayRef<NamedInstrProfRecord> &Data) {
682 auto Iter = HashTable->find(FuncName);
683 if (Iter == HashTable->end())
684 return make_error<InstrProfError>(instrprof_error::unknown_function);
686 Data = (*Iter);
687 if (Data.empty())
688 return make_error<InstrProfError>(instrprof_error::malformed,
689 "profile data is empty");
691 return Error::success();
694 template <typename HashTableImpl>
695 Error InstrProfReaderIndex<HashTableImpl>::getRecords(
696 ArrayRef<NamedInstrProfRecord> &Data) {
697 if (atEnd())
698 return make_error<InstrProfError>(instrprof_error::eof);
700 Data = *RecordIterator;
702 if (Data.empty())
703 return make_error<InstrProfError>(instrprof_error::malformed,
704 "profile data is empty");
706 return Error::success();
709 template <typename HashTableImpl>
710 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
711 const unsigned char *Buckets, const unsigned char *const Payload,
712 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
713 uint64_t Version) {
714 FormatVersion = Version;
715 HashTable.reset(HashTableImpl::Create(
716 Buckets, Payload, Base,
717 typename HashTableImpl::InfoType(HashType, Version)));
718 RecordIterator = HashTable->data_begin();
721 namespace {
722 /// A remapper that does not apply any remappings.
723 class InstrProfReaderNullRemapper : public InstrProfReaderRemapper {
724 InstrProfReaderIndexBase &Underlying;
726 public:
727 InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying)
728 : Underlying(Underlying) {}
730 Error getRecords(StringRef FuncName,
731 ArrayRef<NamedInstrProfRecord> &Data) override {
732 return Underlying.getRecords(FuncName, Data);
735 } // namespace
737 /// A remapper that applies remappings based on a symbol remapping file.
738 template <typename HashTableImpl>
739 class llvm::InstrProfReaderItaniumRemapper
740 : public InstrProfReaderRemapper {
741 public:
742 InstrProfReaderItaniumRemapper(
743 std::unique_ptr<MemoryBuffer> RemapBuffer,
744 InstrProfReaderIndex<HashTableImpl> &Underlying)
745 : RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) {
748 /// Extract the original function name from a PGO function name.
749 static StringRef extractName(StringRef Name) {
750 // We can have multiple :-separated pieces; there can be pieces both
751 // before and after the mangled name. Find the first part that starts
752 // with '_Z'; we'll assume that's the mangled name we want.
753 std::pair<StringRef, StringRef> Parts = {StringRef(), Name};
754 while (true) {
755 Parts = Parts.second.split(':');
756 if (Parts.first.startswith("_Z"))
757 return Parts.first;
758 if (Parts.second.empty())
759 return Name;
763 /// Given a mangled name extracted from a PGO function name, and a new
764 /// form for that mangled name, reconstitute the name.
765 static void reconstituteName(StringRef OrigName, StringRef ExtractedName,
766 StringRef Replacement,
767 SmallVectorImpl<char> &Out) {
768 Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size());
769 Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin());
770 Out.insert(Out.end(), Replacement.begin(), Replacement.end());
771 Out.insert(Out.end(), ExtractedName.end(), OrigName.end());
774 Error populateRemappings() override {
775 if (Error E = Remappings.read(*RemapBuffer))
776 return E;
777 for (StringRef Name : Underlying.HashTable->keys()) {
778 StringRef RealName = extractName(Name);
779 if (auto Key = Remappings.insert(RealName)) {
780 // FIXME: We could theoretically map the same equivalence class to
781 // multiple names in the profile data. If that happens, we should
782 // return NamedInstrProfRecords from all of them.
783 MappedNames.insert({Key, RealName});
786 return Error::success();
789 Error getRecords(StringRef FuncName,
790 ArrayRef<NamedInstrProfRecord> &Data) override {
791 StringRef RealName = extractName(FuncName);
792 if (auto Key = Remappings.lookup(RealName)) {
793 StringRef Remapped = MappedNames.lookup(Key);
794 if (!Remapped.empty()) {
795 if (RealName.begin() == FuncName.begin() &&
796 RealName.end() == FuncName.end())
797 FuncName = Remapped;
798 else {
799 // Try rebuilding the name from the given remapping.
800 SmallString<256> Reconstituted;
801 reconstituteName(FuncName, RealName, Remapped, Reconstituted);
802 Error E = Underlying.getRecords(Reconstituted, Data);
803 if (!E)
804 return E;
806 // If we failed because the name doesn't exist, fall back to asking
807 // about the original name.
808 if (Error Unhandled = handleErrors(
809 std::move(E), [](std::unique_ptr<InstrProfError> Err) {
810 return Err->get() == instrprof_error::unknown_function
811 ? Error::success()
812 : Error(std::move(Err));
814 return Unhandled;
818 return Underlying.getRecords(FuncName, Data);
821 private:
822 /// The memory buffer containing the remapping configuration. Remappings
823 /// holds pointers into this buffer.
824 std::unique_ptr<MemoryBuffer> RemapBuffer;
826 /// The mangling remapper.
827 SymbolRemappingReader Remappings;
829 /// Mapping from mangled name keys to the name used for the key in the
830 /// profile data.
831 /// FIXME: Can we store a location within the on-disk hash table instead of
832 /// redoing lookup?
833 DenseMap<SymbolRemappingReader::Key, StringRef> MappedNames;
835 /// The real profile data reader.
836 InstrProfReaderIndex<HashTableImpl> &Underlying;
839 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
840 using namespace support;
842 if (DataBuffer.getBufferSize() < 8)
843 return false;
844 uint64_t Magic =
845 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
846 // Verify that it's magical.
847 return Magic == IndexedInstrProf::Magic;
850 const unsigned char *
851 IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
852 const unsigned char *Cur, bool UseCS) {
853 using namespace IndexedInstrProf;
854 using namespace support;
856 if (Version >= IndexedInstrProf::Version4) {
857 const IndexedInstrProf::Summary *SummaryInLE =
858 reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
859 uint64_t NFields =
860 endian::byte_swap<uint64_t, little>(SummaryInLE->NumSummaryFields);
861 uint64_t NEntries =
862 endian::byte_swap<uint64_t, little>(SummaryInLE->NumCutoffEntries);
863 uint32_t SummarySize =
864 IndexedInstrProf::Summary::getSize(NFields, NEntries);
865 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
866 IndexedInstrProf::allocSummary(SummarySize);
868 const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
869 uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
870 for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
871 Dst[I] = endian::byte_swap<uint64_t, little>(Src[I]);
873 SummaryEntryVector DetailedSummary;
874 for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
875 const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
876 DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
877 Ent.NumBlocks);
879 std::unique_ptr<llvm::ProfileSummary> &Summary =
880 UseCS ? this->CS_Summary : this->Summary;
882 // initialize InstrProfSummary using the SummaryData from disk.
883 Summary = std::make_unique<ProfileSummary>(
884 UseCS ? ProfileSummary::PSK_CSInstr : ProfileSummary::PSK_Instr,
885 DetailedSummary, SummaryData->get(Summary::TotalBlockCount),
886 SummaryData->get(Summary::MaxBlockCount),
887 SummaryData->get(Summary::MaxInternalBlockCount),
888 SummaryData->get(Summary::MaxFunctionCount),
889 SummaryData->get(Summary::TotalNumBlocks),
890 SummaryData->get(Summary::TotalNumFunctions));
891 return Cur + SummarySize;
892 } else {
893 // The older versions do not support a profile summary. This just computes
894 // an empty summary, which will not result in accurate hot/cold detection.
895 // We would need to call addRecord for all NamedInstrProfRecords to get the
896 // correct summary. However, this version is old (prior to early 2016) and
897 // has not been supporting an accurate summary for several years.
898 InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
899 Summary = Builder.getSummary();
900 return Cur;
904 Error IndexedInstrProfReader::readHeader() {
905 using namespace support;
907 const unsigned char *Start =
908 (const unsigned char *)DataBuffer->getBufferStart();
909 const unsigned char *Cur = Start;
910 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
911 return error(instrprof_error::truncated);
913 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
914 Cur += sizeof(IndexedInstrProf::Header);
916 // Check the magic number.
917 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
918 if (Magic != IndexedInstrProf::Magic)
919 return error(instrprof_error::bad_magic);
921 // Read the version.
922 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
923 if (GET_VERSION(FormatVersion) >
924 IndexedInstrProf::ProfVersion::CurrentVersion)
925 return error(instrprof_error::unsupported_version);
927 Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur,
928 /* UseCS */ false);
929 if (FormatVersion & VARIANT_MASK_CSIR_PROF)
930 Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur,
931 /* UseCS */ true);
933 // Read the hash type and start offset.
934 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
935 endian::byte_swap<uint64_t, little>(Header->HashType));
936 if (HashType > IndexedInstrProf::HashT::Last)
937 return error(instrprof_error::unsupported_hash_type);
939 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
941 // The rest of the file is an on disk hash table.
942 auto IndexPtr =
943 std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(
944 Start + HashOffset, Cur, Start, HashType, FormatVersion);
946 // Load the remapping table now if requested.
947 if (RemappingBuffer) {
948 Remapper = std::make_unique<
949 InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>(
950 std::move(RemappingBuffer), *IndexPtr);
951 if (Error E = Remapper->populateRemappings())
952 return E;
953 } else {
954 Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);
956 Index = std::move(IndexPtr);
958 return success();
961 InstrProfSymtab &IndexedInstrProfReader::getSymtab() {
962 if (Symtab.get())
963 return *Symtab.get();
965 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
966 if (Error E = Index->populateSymtab(*NewSymtab.get())) {
967 consumeError(error(InstrProfError::take(std::move(E))));
970 Symtab = std::move(NewSymtab);
971 return *Symtab.get();
974 Expected<InstrProfRecord>
975 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
976 uint64_t FuncHash) {
977 ArrayRef<NamedInstrProfRecord> Data;
978 Error Err = Remapper->getRecords(FuncName, Data);
979 if (Err)
980 return std::move(Err);
981 // Found it. Look for counters with the right hash.
982 for (const NamedInstrProfRecord &I : Data) {
983 // Check for a match and fill the vector if there is one.
984 if (I.Hash == FuncHash)
985 return std::move(I);
987 return error(instrprof_error::hash_mismatch);
990 Error IndexedInstrProfReader::getFunctionCounts(StringRef FuncName,
991 uint64_t FuncHash,
992 std::vector<uint64_t> &Counts) {
993 Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
994 if (Error E = Record.takeError())
995 return error(std::move(E));
997 Counts = Record.get().Counts;
998 return success();
1001 Error IndexedInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {
1002 ArrayRef<NamedInstrProfRecord> Data;
1004 Error E = Index->getRecords(Data);
1005 if (E)
1006 return error(std::move(E));
1008 Record = Data[RecordIndex++];
1009 if (RecordIndex >= Data.size()) {
1010 Index->advanceToNextKey();
1011 RecordIndex = 0;
1013 return success();
1016 void InstrProfReader::accumulateCounts(CountSumOrPercent &Sum, bool IsCS) {
1017 uint64_t NumFuncs = 0;
1018 for (const auto &Func : *this) {
1019 if (isIRLevelProfile()) {
1020 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
1021 if (FuncIsCS != IsCS)
1022 continue;
1024 Func.accumulateCounts(Sum);
1025 ++NumFuncs;
1027 Sum.NumEntries = NumFuncs;