LLVM 24.0.0git
InstrProfReader.cpp
Go to the documentation of this file.
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.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/StringRef.h"
21// #include "llvm/ProfileData/MemProf.h"
25#include "llvm/Support/Endian.h"
26#include "llvm/Support/Error.h"
31#include <algorithm>
32#include <cstddef>
33#include <cstdint>
34#include <limits>
35#include <memory>
36#include <optional>
37#include <system_error>
38#include <utility>
39#include <vector>
40
41using namespace llvm;
42
43// Extracts the variant information from the top 32 bits in the version and
44// returns an enum specifying the variants present.
47 if (Version & VARIANT_MASK_IR_PROF) {
49 }
50 if (Version & VARIANT_MASK_CSIR_PROF) {
52 }
53 if (Version & VARIANT_MASK_INSTR_ENTRY) {
55 }
56 if (Version & VARIANT_MASK_INSTR_LOOP_ENTRIES) {
58 }
59 if (Version & VARIANT_MASK_BYTE_COVERAGE) {
61 }
64 }
65 if (Version & VARIANT_MASK_MEMPROF) {
66 ProfileKind |= InstrProfKind::MemProf;
67 }
68 if (Version & VARIANT_MASK_TEMPORAL_PROF) {
69 ProfileKind |= InstrProfKind::TemporalProfile;
70 }
71 return ProfileKind;
72}
73
76 auto BufferOrErr = Filename.str() == "-" ? MemoryBuffer::getSTDIN()
77 : FS.getBufferForFile(Filename);
78 if (std::error_code EC = BufferOrErr.getError())
79 return errorCodeToError(EC);
80 return std::move(BufferOrErr.get());
81}
82
84 return Reader.readHeader();
85}
86
87/// Read a list of binary ids from a profile that consist of
88/// a. uint64_t binary id length
89/// b. uint8_t binary id data
90/// c. uint8_t padding (if necessary)
91/// This function is shared between raw and indexed profiles.
92/// Raw profiles are in host-endian format, and indexed profiles are in
93/// little-endian format. So, this function takes an argument indicating the
94/// associated endian format to read the binary ids correctly.
95static Error
97 ArrayRef<uint8_t> BinaryIdsBuffer,
98 std::vector<llvm::object::BuildID> &BinaryIds,
99 const llvm::endianness Endian) {
100 using namespace support;
101
102 const uint64_t BinaryIdsSize = BinaryIdsBuffer.size();
103 const uint8_t *BinaryIdsStart = BinaryIdsBuffer.data();
104
105 if (BinaryIdsSize == 0)
106 return Error::success();
107
108 const uint8_t *BI = BinaryIdsStart;
109 const uint8_t *BIEnd = BinaryIdsStart + BinaryIdsSize;
110 const uint8_t *End =
111 reinterpret_cast<const uint8_t *>(DataBuffer.getBufferEnd());
112
113 while (BI < BIEnd) {
114 size_t Remaining = BIEnd - BI;
115 // There should be enough left to read the binary id length.
116 if (Remaining < sizeof(uint64_t))
119 "not enough data to read binary id length");
120
121 uint64_t BILen = endian::readNext<uint64_t>(BI, Endian);
122 if (BILen == 0)
124 "binary id length is 0");
125
126 Remaining = BIEnd - BI;
127 // There should be enough left to read the binary id data.
128 if (Remaining < alignToPowerOf2(BILen, sizeof(uint64_t)))
130 instrprof_error::malformed, "not enough data to read binary id data");
131
132 // Add binary id to the binary ids list.
133 BinaryIds.push_back(object::BuildID(BI, BI + BILen));
134
135 // Increment by binary id data length, which aligned to the size of uint64.
136 BI += alignToPowerOf2(BILen, sizeof(uint64_t));
137 if (BI > End)
140 "binary id section is greater than buffer size");
141 }
142
143 return Error::success();
144}
145
148 OS << "Binary IDs: \n";
149 for (const auto &BI : BinaryIds) {
150 for (auto I : BI)
151 OS << format("%02x", I);
152 OS << "\n";
153 }
154}
155
157 const Twine &Path, vfs::FileSystem &FS,
158 const InstrProfCorrelator *Correlator,
159 const object::BuildIDFetcher *BIDFetcher,
160 std::optional<ProfCorrelatorKind> BIDFetcherCorrelatorKind,
161 std::function<void(Error)> Warn) {
162 // Set up the buffer to read.
163 auto BufferOrError = setupMemoryBuffer(Path, FS);
164 if (Error E = BufferOrError.takeError())
165 return std::move(E);
166 return InstrProfReader::create(std::move(BufferOrError.get()), Correlator,
167 BIDFetcher, BIDFetcherCorrelatorKind, Warn);
168}
169
171 std::unique_ptr<MemoryBuffer> Buffer, const InstrProfCorrelator *Correlator,
172 const object::BuildIDFetcher *BIDFetcher,
173 std::optional<ProfCorrelatorKind> BIDFetcherCorrelatorKind,
174 std::function<void(Error)> Warn) {
175 if (Buffer->getBufferSize() == 0)
177
178 std::unique_ptr<InstrProfReader> Result;
179 // Create the reader.
181 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
182 else if (RawInstrProfReader64::hasFormat(*Buffer))
183 Result.reset(new RawInstrProfReader64(std::move(Buffer), Correlator,
184 BIDFetcher, BIDFetcherCorrelatorKind,
185 Warn));
186 else if (RawInstrProfReader32::hasFormat(*Buffer))
187 Result.reset(new RawInstrProfReader32(std::move(Buffer), Correlator,
188 BIDFetcher, BIDFetcherCorrelatorKind,
189 Warn));
190 else if (TextInstrProfReader::hasFormat(*Buffer))
191 Result.reset(new TextInstrProfReader(std::move(Buffer)));
192 else
194
195 // Initialize the reader and return the result.
196 if (Error E = initializeReader(*Result))
197 return std::move(E);
198
199 return std::move(Result);
200}
201
204 const Twine &RemappingPath) {
205 // Set up the buffer to read.
206 auto BufferOrError = setupMemoryBuffer(Path, FS);
207 if (Error E = BufferOrError.takeError())
208 return std::move(E);
209
210 // Set up the remapping buffer if requested.
211 std::unique_ptr<MemoryBuffer> RemappingBuffer;
212 std::string RemappingPathStr = RemappingPath.str();
213 if (!RemappingPathStr.empty()) {
214 auto RemappingBufferOrError = setupMemoryBuffer(RemappingPathStr, FS);
215 if (Error E = RemappingBufferOrError.takeError())
216 return std::move(E);
217 RemappingBuffer = std::move(RemappingBufferOrError.get());
218 }
219
220 return IndexedInstrProfReader::create(std::move(BufferOrError.get()),
221 std::move(RemappingBuffer));
222}
223
225IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,
226 std::unique_ptr<MemoryBuffer> RemappingBuffer) {
227 // Create the reader.
230 auto Result = std::make_unique<IndexedInstrProfReader>(
231 std::move(Buffer), std::move(RemappingBuffer));
232
233 // Initialize the reader and return the result.
234 if (Error E = initializeReader(*Result))
235 return std::move(E);
236
237 return std::move(Result);
238}
239
241 // Verify that this really looks like plain ASCII text by checking a
242 // 'reasonable' number of characters (up to profile magic size).
243 size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
244 StringRef buffer = Buffer.getBufferStart();
245 return count == 0 ||
246 std::all_of(buffer.begin(), buffer.begin() + count,
247 [](char c) { return isPrint(c) || isSpace(c); });
248}
249
250// Read the profile variant flag from the header: ":FE" means this is a FE
251// generated profile. ":IR" means this is an IR level profile. Other strings
252// with a leading ':' will be reported an error format.
254 Symtab.reset(new InstrProfSymtab());
255
256 while (Line->starts_with(":")) {
257 StringRef Str = Line->substr(1);
258 if (Str.equals_insensitive("ir"))
260 else if (Str.equals_insensitive("fe"))
262 else if (Str.equals_insensitive("csir")) {
264 ProfileKind |= InstrProfKind::ContextSensitive;
265 } else if (Str.equals_insensitive("entry_first"))
267 else if (Str.equals_insensitive("not_entry_first"))
269 else if (Str.equals_insensitive("instrument_loop_entries"))
271 else if (Str.equals_insensitive("single_byte_coverage"))
273 else if (Str.equals_insensitive("temporal_prof_traces")) {
274 ProfileKind |= InstrProfKind::TemporalProfile;
275 if (auto Err = readTemporalProfTraceData())
276 return error(std::move(Err));
277 } else
279 ++Line;
280 }
281 return success();
282}
283
284/// Temporal profile trace data is stored in the header immediately after
285/// ":temporal_prof_traces". The first integer is the number of traces, the
286/// second integer is the stream size, then the following lines are the actual
287/// traces which consist of a weight and a comma separated list of function
288/// names.
289Error TextInstrProfReader::readTemporalProfTraceData() {
290 if ((++Line).is_at_end())
292
293 uint32_t NumTraces;
294 if (Line->getAsInteger(0, NumTraces))
296
297 if ((++Line).is_at_end())
299
300 if (Line->getAsInteger(0, TemporalProfTraceStreamSize))
302
303 for (uint32_t i = 0; i < NumTraces; i++) {
304 if ((++Line).is_at_end())
306
308 if (Line->getAsInteger(0, Trace.Weight))
310
311 if ((++Line).is_at_end())
313
314 SmallVector<StringRef> FuncNames;
315 Line->split(FuncNames, ",", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
316 for (auto &FuncName : FuncNames)
317 Trace.FunctionNameRefs.push_back(
318 IndexedInstrProf::ComputeHash(FuncName.trim()));
319 TemporalProfTraces.push_back(std::move(Trace));
320 }
321 return success();
322}
323
324Error
325TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
326
327#define CHECK_LINE_END(Line) \
328 if (Line.is_at_end()) \
329 return error(instrprof_error::truncated);
330#define READ_NUM(Str, Dst) \
331 if ((Str).getAsInteger(10, (Dst))) \
332 return error(instrprof_error::malformed);
333#define VP_READ_ADVANCE(Val) \
334 CHECK_LINE_END(Line); \
335 uint32_t Val; \
336 READ_NUM((*Line), (Val)); \
337 Line++;
338
339 if (Line.is_at_end())
340 return success();
341
342 uint32_t NumValueKinds;
343 if (Line->getAsInteger(10, NumValueKinds)) {
344 // No value profile data
345 return success();
346 }
347 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
349 "number of value kinds is invalid");
350 Line++;
351
352 for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
353 VP_READ_ADVANCE(ValueKind);
354 if (ValueKind > IPVK_Last)
355 return error(instrprof_error::malformed, "value kind is invalid");
356 ;
358 if (!NumValueSites)
359 continue;
360
361 Record.reserveSites(VK, NumValueSites);
362 for (uint32_t S = 0; S < NumValueSites; S++) {
363 VP_READ_ADVANCE(NumValueData);
364
365 std::vector<InstrProfValueData> CurrentValues;
366 for (uint32_t V = 0; V < NumValueData; V++) {
367 CHECK_LINE_END(Line);
368 std::pair<StringRef, StringRef> VD = Line->rsplit(':');
369 uint64_t TakenCount, Value;
370 if (ValueKind == IPVK_IndirectCallTarget) {
371 if (InstrProfSymtab::isExternalSymbol(VD.first)) {
372 Value = 0;
373 } else {
374 if (Error E = Symtab->addFuncName(VD.first))
375 return E;
377 }
378 } else if (ValueKind == IPVK_VTableTarget) {
380 Value = 0;
381 else {
382 if (Error E = Symtab->addVTableName(VD.first))
383 return E;
385 }
386 } else {
387 READ_NUM(VD.first, Value);
388 }
389 READ_NUM(VD.second, TakenCount);
390 CurrentValues.push_back({Value, TakenCount});
391 Line++;
392 }
393 assert(CurrentValues.size() == NumValueData);
394 Record.addValueData(ValueKind, S, CurrentValues, nullptr);
395 }
396 }
397 return success();
398
399#undef CHECK_LINE_END
400#undef READ_NUM
401#undef VP_READ_ADVANCE
402}
403
405 // Skip empty lines and comments.
406 while (!Line.is_at_end() && (Line->empty() || Line->starts_with("#")))
407 ++Line;
408 // If we hit EOF while looking for a name, we're done.
409 if (Line.is_at_end()) {
411 }
412
413 // Read the function name.
414 Record.Name = *Line++;
415 if (Error E = Symtab->addFuncName(Record.Name))
416 return error(std::move(E));
417
418 // Read the function hash.
419 if (Line.is_at_end())
421 if ((Line++)->getAsInteger(0, Record.Hash))
423 "function hash is not a valid integer");
424
425 // Read the number of counters.
426 uint64_t NumCounters;
427 if (Line.is_at_end())
429 if ((Line++)->getAsInteger(10, NumCounters))
431 "number of counters is not a valid integer");
432 if (NumCounters == 0)
433 return error(instrprof_error::malformed, "number of counters is zero");
434
435 // Read each counter and fill our internal storage with the values.
436 Record.Clear();
437 Record.Counts.reserve(NumCounters);
438 for (uint64_t I = 0; I < NumCounters; ++I) {
439 if (Line.is_at_end())
441 uint64_t Count;
442 if ((Line++)->getAsInteger(10, Count))
443 return error(instrprof_error::malformed, "count is invalid");
444 Record.Counts.push_back(Count);
445 }
446
447 // Bitmap byte information is indicated by '$' followed by an integer. Only
448 // treat numeric-looking lines as bitmap records so function names such as
449 // Swift manglings beginning with "$s" remain unambiguous.
450 StringRef BitmapSize =
451 Line->starts_with("$") ? Line->drop_front(1).trim() : StringRef();
452 if (!BitmapSize.empty() && isDigit(BitmapSize.front())) {
453 Record.BitmapBytes.clear();
454 // Read the number of bitmap bytes.
455 uint64_t NumBitmapBytes;
456 if ((Line++)->drop_front(1).trim().getAsInteger(0, NumBitmapBytes))
458 "number of bitmap bytes is not a valid integer");
459 if (NumBitmapBytes != 0) {
460 // Read each bitmap and fill our internal storage with the values.
461 Record.BitmapBytes.reserve(NumBitmapBytes);
462 for (uint64_t I = 0; I < NumBitmapBytes; ++I) {
463 if (Line.is_at_end())
465 uint8_t BitmapByte;
466 if ((Line++)->getAsInteger(0, BitmapByte))
468 "bitmap byte is not a valid integer");
469 Record.BitmapBytes.push_back(BitmapByte);
470 }
471 }
472 }
473
474 // Check if value profile data exists and read it if so.
475 if (Error E = readValueProfileData(Record))
476 return error(std::move(E));
477
478 return success();
479}
480
481template <class IntPtrT>
485
486template <class IntPtrT>
489 std::optional<uint64_t> Weight) {
490 if (TemporalProfTimestamps.empty()) {
491 assert(TemporalProfTraces.empty());
492 return TemporalProfTraces;
493 }
494 // Sort functions by their timestamps to build the trace.
495 std::sort(TemporalProfTimestamps.begin(), TemporalProfTimestamps.end());
497 if (Weight)
498 Trace.Weight = *Weight;
499 for (auto &[TimestampValue, NameRef] : TemporalProfTimestamps)
500 Trace.FunctionNameRefs.push_back(NameRef);
501 TemporalProfTraces = {std::move(Trace)};
502 return TemporalProfTraces;
503}
504
505template <class IntPtrT>
507 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
508 return false;
509 uint64_t Magic =
510 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
511 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
513}
514
515template <class IntPtrT>
517 if (!hasFormat(*DataBuffer))
519 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
521 std::string("profile file header is truncated"));
522 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
523 DataBuffer->getBufferStart());
524 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
525 return readHeader(*Header);
526}
527
528template <class IntPtrT>
529Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
530 const char *End = DataBuffer->getBufferEnd();
531 // Skip zero padding between profiles.
532 while (CurrentPos != End && *CurrentPos == 0)
533 ++CurrentPos;
534 // If there's nothing left, we're done.
535 if (CurrentPos == End)
537 // If there isn't enough space for another header, this is probably just
538 // garbage at the end of the file.
539 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
541 "not enough space for another header");
542 // The writer ensures each profile is padded to start at an aligned address.
543 if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))
545 "insufficient padding");
546 // The magic should have the same byte order as in the previous header.
547 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
548 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
550
551 // There's another profile to read, so we need to process the header.
552 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
553 return readHeader(*Header);
554}
555
556template <class IntPtrT>
557Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
558 if (Error E = Symtab.create(StringRef(NamesStart, NamesEnd - NamesStart),
559 StringRef(VNamesStart, VNamesEnd - VNamesStart)))
560 return error(std::move(E));
561 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
562 const IntPtrT FPtr = swap(I->FunctionPointer);
563 if (!FPtr)
564 continue;
565 Symtab.mapAddress(FPtr, swap(I->NameRef));
566 }
567
568 if (VTableBegin != nullptr && VTableEnd != nullptr) {
569 for (const RawInstrProf::VTableProfileData<IntPtrT> *I = VTableBegin;
570 I != VTableEnd; ++I) {
571 const IntPtrT VPtr = swap(I->VTablePointer);
572 if (!VPtr)
573 continue;
574 // Map both begin and end address to the name hash, since the instrumented
575 // address could be somewhere in the middle.
576 // VPtr is of type uint32_t or uint64_t so 'VPtr + I->VTableSize' marks
577 // the end of vtable address.
578 Symtab.mapVTableAddress(VPtr, VPtr + swap(I->VTableSize),
579 swap(I->VTableNameHash));
580 }
581 }
582 return success();
583}
584
585template <class IntPtrT>
587 const RawInstrProf::Header &Header) {
588 Version = swap(Header.Version);
591 ("Profile uses raw profile format version = " +
593 "; expected version = " + Twine(RawInstrProf::Version) +
594 "\nPLEASE update this tool to version in the raw profile, or "
595 "regenerate raw profile with expected version.")
596 .str());
597 uint64_t BinaryIdSize = swap(Header.BinaryIdsSize);
598 // Binary id start just after the header if exists.
599 const uint8_t *BinaryIdStart =
600 reinterpret_cast<const uint8_t *>(&Header) + sizeof(RawInstrProf::Header);
601 const uint8_t *BinaryIdEnd = BinaryIdStart + BinaryIdSize;
602 const uint8_t *BufferEnd = (const uint8_t *)DataBuffer->getBufferEnd();
603 if (BinaryIdSize % sizeof(uint64_t))
604 return error(
606 ("BinaryIdSize (" + Twine(BinaryIdSize) + ") is not a multiple of 8")
607 .str());
608 if (BinaryIdEnd > BufferEnd)
610 ("Header.BinaryIdSize = " + Twine(BinaryIdSize) + " bytes; " +
611 Twine(BufferEnd - BinaryIdStart) + " bytes available")
612 .str());
613
614 ArrayRef<uint8_t> BinaryIdsBuffer(BinaryIdStart, BinaryIdSize);
615 if (!BinaryIdsBuffer.empty()) {
616 if (Error Err = readBinaryIdsInternal(*DataBuffer, BinaryIdsBuffer,
617 BinaryIds, getDataEndianness()))
618 return Err;
619 }
620
621 CountersDelta = swap(Header.CountersDelta);
622 BitmapDelta = swap(Header.BitmapDelta);
623 UniformCountersDelta = swap(Header.UniformCountersDelta);
624 NamesDelta = swap(Header.NamesDelta);
625 auto NumData = swap(Header.NumData);
626 auto PaddingBytesBeforeCounters = swap(Header.PaddingBytesBeforeCounters);
627 auto CountersSize = swap(Header.NumCounters) * getCounterTypeSize();
628 auto PaddingBytesAfterCounters = swap(Header.PaddingBytesAfterCounters);
629 auto NumBitmapBytes = swap(Header.NumBitmapBytes);
630 auto PaddingBytesAfterBitmapBytes = swap(Header.PaddingBytesAfterBitmapBytes);
631 auto NumUniformCounters = swap(Header.NumUniformCounters);
632 auto PaddingBytesAfterUniformCounters =
633 swap(Header.PaddingBytesAfterUniformCounters);
634 auto NamesSize = swap(Header.NamesSize);
635 auto VTableNameSize = swap(Header.VNamesSize);
636 auto NumVTables = swap(Header.NumVTables);
637
638 auto DataSize = NumData * sizeof(RawInstrProf::ProfileData<IntPtrT>);
639 auto PaddingBytesAfterNames = getNumPaddingBytes(NamesSize);
640 auto PaddingBytesAfterVTableNames = getNumPaddingBytes(VTableNameSize);
641
642 auto VTableSectionSize =
643 NumVTables * sizeof(RawInstrProf::VTableProfileData<IntPtrT>);
644 auto PaddingBytesAfterVTableProfData = getNumPaddingBytes(VTableSectionSize);
645 auto UniformCountersSectionSize = NumUniformCounters * sizeof(uint64_t);
646
647 // Profile data starts after profile header and binary ids if exist.
648 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header) + BinaryIdSize;
649 ptrdiff_t CountersOffset = DataOffset + DataSize + PaddingBytesBeforeCounters;
650 ptrdiff_t BitmapOffset =
651 CountersOffset + CountersSize + PaddingBytesAfterCounters;
652 ptrdiff_t UniformCountersOffset =
653 BitmapOffset + NumBitmapBytes + PaddingBytesAfterBitmapBytes;
654 ptrdiff_t NamesOffset = UniformCountersOffset + UniformCountersSectionSize +
655 PaddingBytesAfterUniformCounters;
656 ptrdiff_t VTableProfDataOffset =
657 NamesOffset + NamesSize + PaddingBytesAfterNames;
658 ptrdiff_t VTableNameOffset = VTableProfDataOffset + VTableSectionSize +
659 PaddingBytesAfterVTableProfData;
660 ptrdiff_t ValueDataOffset =
661 VTableNameOffset + VTableNameSize + PaddingBytesAfterVTableNames;
662
663 auto *Start = reinterpret_cast<const char *>(&Header);
664 if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
665 // clang-format off
666 return error(
668 ("profile file size (" + Twine(DataBuffer->getBufferSize()) +
669 " bytes) smaller than expected (at least " + Twine(ValueDataOffset) +
670 " bytes: " +
671 Twine(sizeof(RawInstrProf::Header)) + "(Header) + " +
672 Twine(BinaryIdSize) + "(BinaryIdSize) + " +
673 Twine(DataSize) + "(DataSize) + " +
674 Twine(CountersSize) + "(CountersSize) + " +
675 Twine(NumBitmapBytes) + "(NumBitmapBytes) + " +
676 Twine(UniformCountersSectionSize) + "(UniformCountersSectionSize) + " +
677 Twine(NamesSize) + "(NamesSize) + " +
678 Twine(VTableSectionSize) + "(VTableSectionSize) + " +
679 Twine(VTableNameSize) + "(VTableNameSize) + " +
680 Twine(PaddingBytesBeforeCounters + PaddingBytesAfterCounters +
681 PaddingBytesAfterBitmapBytes + PaddingBytesAfterUniformCounters +
682 PaddingBytesAfterNames + PaddingBytesAfterVTableProfData +
683 PaddingBytesAfterVTableNames) +
684 "(Padding))")
685 .str());
686 // clang-format on
687
688 if (BIDFetcher) {
689 std::vector<object::BuildID> BinaryIDs;
690 if (Error E = readBinaryIds(BinaryIDs))
691 return E;
692 if (auto E = InstrProfCorrelator::get("", *BIDFetcherCorrelatorKind,
693 BIDFetcher, BinaryIDs)
694 .moveInto(BIDFetcherCorrelator)) {
695 return E;
696 }
697 if (auto Err = BIDFetcherCorrelator->correlateProfileData(0))
698 return Err;
699 }
700
701 if (Correlator) {
702 // These sizes in the raw file are zero because we constructed them in the
703 // Correlator.
704 if (!(DataSize == 0 && NamesSize == 0 && CountersDelta == 0 &&
705 BitmapDelta == 0 && NamesDelta == 0))
707 Data = Correlator->getDataPointer();
708 DataEnd = Data + Correlator->getDataSize();
709 NamesStart = Correlator->getNamesPointer();
710 NamesEnd = NamesStart + Correlator->getNamesSize();
711 } else if (BIDFetcherCorrelator) {
712 InstrProfCorrelatorImpl<IntPtrT> *BIDFetcherCorrelatorImpl =
714 BIDFetcherCorrelator.get());
715 Data = BIDFetcherCorrelatorImpl->getDataPointer();
716 DataEnd = Data + BIDFetcherCorrelatorImpl->getDataSize();
717 NamesStart = BIDFetcherCorrelatorImpl->getNamesPointer();
718 NamesEnd = NamesStart + BIDFetcherCorrelatorImpl->getNamesSize();
719 } else {
720 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
721 Start + DataOffset);
722 DataEnd = Data + NumData;
723 VTableBegin =
724 reinterpret_cast<const RawInstrProf::VTableProfileData<IntPtrT> *>(
725 Start + VTableProfDataOffset);
726 VTableEnd = VTableBegin + NumVTables;
727 NamesStart = Start + NamesOffset;
728 NamesEnd = NamesStart + NamesSize;
729 VNamesStart = Start + VTableNameOffset;
730 VNamesEnd = VNamesStart + VTableNameSize;
731 }
732
733 CountersStart = Start + CountersOffset;
734 CountersEnd = CountersStart + CountersSize;
735 BitmapStart = Start + BitmapOffset;
736 BitmapEnd = BitmapStart + NumBitmapBytes;
737 UniformCountersStart = Start + UniformCountersOffset;
738 UniformCountersEnd = UniformCountersStart + UniformCountersSectionSize;
739 ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
740
741 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
742 if (Error E = createSymtab(*NewSymtab))
743 return E;
744
745 Symtab = std::move(NewSymtab);
746 return success();
747}
748
749template <class IntPtrT>
750Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) {
751 Record.Name = getName(Data->NameRef);
752 return success();
753}
754
755template <class IntPtrT>
756Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) {
757 Record.Hash = swap(Data->FuncHash);
758 return success();
759}
760
761template <class IntPtrT>
762Error RawInstrProfReader<IntPtrT>::readRawCounts(
764 uint32_t NumCounters = swap(Data->NumCounters);
765 if (NumCounters == 0)
766 return error(instrprof_error::malformed, "number of counters is zero");
767
768 ptrdiff_t CounterBaseOffset = swap(Data->CounterPtr) - CountersDelta;
769 if (CounterBaseOffset < 0)
770 return error(
772 ("counter offset " + Twine(CounterBaseOffset) + " is negative").str());
773
774 if (CounterBaseOffset >= CountersEnd - CountersStart)
776 ("counter offset " + Twine(CounterBaseOffset) +
777 " is greater than the maximum counter offset " +
778 Twine(CountersEnd - CountersStart - 1))
779 .str());
780
781 uint64_t MaxNumCounters =
782 (CountersEnd - (CountersStart + CounterBaseOffset)) /
783 getCounterTypeSize();
784 if (NumCounters > MaxNumCounters)
786 ("number of counters " + Twine(NumCounters) +
787 " is greater than the maximum number of counters " +
788 Twine(MaxNumCounters))
789 .str());
790
791 Record.Counts.clear();
792 Record.Counts.reserve(NumCounters);
793 for (uint32_t I = 0; I < NumCounters; I++) {
794 const char *Ptr =
795 CountersStart + CounterBaseOffset + I * getCounterTypeSize();
796 if (I == 0 && hasTemporalProfile()) {
797 uint64_t TimestampValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
798 if (TimestampValue != 0 &&
799 TimestampValue != std::numeric_limits<uint64_t>::max()) {
800 TemporalProfTimestamps.emplace_back(TimestampValue,
801 swap(Data->NameRef));
802 TemporalProfTraceStreamSize = 1;
803 }
804 if (hasSingleByteCoverage()) {
805 // In coverage mode, getCounterTypeSize() returns 1 byte but our
806 // timestamp field has size uint64_t. Increment I so that the next
807 // iteration of this for loop points to the byte after the timestamp
808 // field, i.e., I += 8.
809 I += 7;
810 }
811 continue;
812 }
813 if (hasSingleByteCoverage()) {
814 // A value of zero signifies the block is covered.
815 Record.Counts.push_back(*Ptr == 0 ? 1 : 0);
816 } else {
817 uint64_t CounterValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
818 if (CounterValue > MaxCounterValue && Warn)
821
822 Record.Counts.push_back(CounterValue);
823 }
824 }
825
826 return success();
827}
828
829template <class IntPtrT>
830Error RawInstrProfReader<IntPtrT>::readRawBitmapBytes(InstrProfRecord &Record) {
831 uint32_t NumBitmapBytes = swap(Data->NumBitmapBytes);
832
833 Record.BitmapBytes.clear();
834 Record.BitmapBytes.reserve(NumBitmapBytes);
835
836 // It's possible MCDC is either not enabled or only used for some functions
837 // and not others. So if we record 0 bytes, just move on.
838 if (NumBitmapBytes == 0)
839 return success();
840
841 // BitmapDelta decreases as we advance to the next data record.
842 ptrdiff_t BitmapOffset = swap(Data->BitmapPtr) - BitmapDelta;
843 if (BitmapOffset < 0)
844 return error(
846 ("bitmap offset " + Twine(BitmapOffset) + " is negative").str());
847
848 if (BitmapOffset >= BitmapEnd - BitmapStart)
850 ("bitmap offset " + Twine(BitmapOffset) +
851 " is greater than the maximum bitmap offset " +
852 Twine(BitmapEnd - BitmapStart - 1))
853 .str());
854
855 uint64_t MaxNumBitmapBytes =
856 (BitmapEnd - (BitmapStart + BitmapOffset)) / sizeof(uint8_t);
857 if (NumBitmapBytes > MaxNumBitmapBytes)
859 ("number of bitmap bytes " + Twine(NumBitmapBytes) +
860 " is greater than the maximum number of bitmap bytes " +
861 Twine(MaxNumBitmapBytes))
862 .str());
863
864 for (uint32_t I = 0; I < NumBitmapBytes; I++) {
865 const char *Ptr = BitmapStart + BitmapOffset + I;
866 Record.BitmapBytes.push_back(swap(*Ptr));
867 }
868
869 return success();
870}
871
872template <class IntPtrT>
873Error RawInstrProfReader<IntPtrT>::readRawUniformCounters(
875 Record.UniformCounts.clear();
876
877 if (UniformCountersStart == UniformCountersEnd)
878 return success();
879
880 uint32_t NumCounters = swap(Data->NumCounters);
881
882 ptrdiff_t UniformCounterOffset =
883 swap(Data->UniformCounterPtr) - UniformCountersDelta;
884 if (UniformCounterOffset < 0)
886 ("uniform counter offset " + Twine(UniformCounterOffset) +
887 " is negative")
888 .str());
889
890 if (UniformCounterOffset >= UniformCountersEnd - UniformCountersStart)
892 ("uniform counter offset " + Twine(UniformCounterOffset) +
893 " is greater than the maximum uniform counter offset " +
894 Twine(UniformCountersEnd - UniformCountersStart - 1))
895 .str());
896
897 uint64_t MaxNumCounters =
898 (UniformCountersEnd - (UniformCountersStart + UniformCounterOffset)) /
899 sizeof(uint64_t);
900 if (NumCounters > MaxNumCounters)
902 ("number of uniform counters " + Twine(NumCounters) +
903 " is greater than the maximum number of uniform counters " +
904 Twine(MaxNumCounters))
905 .str());
906
907 Record.UniformCounts.reserve(NumCounters);
908 for (uint32_t I = 0; I < NumCounters; I++) {
909 const char *Ptr =
910 UniformCountersStart + UniformCounterOffset + I * sizeof(uint64_t);
911 uint64_t CounterValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
912 Record.UniformCounts.push_back(CounterValue);
913 }
914
915 return success();
916}
917
918template <class IntPtrT>
919Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
921 Record.clearValueData();
922 CurValueDataSize = 0;
923 // Need to match the logic in value profile dumper code in compiler-rt:
924 uint32_t NumValueKinds = 0;
925 for (uint32_t I = 0; I < IPVK_Last + 1; I++)
926 NumValueKinds += (Data->NumValueSites[I] != 0);
927
928 if (!NumValueKinds)
929 return success();
930
932 ValueProfData::getValueProfData(
933 ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
934 getDataEndianness());
935
936 if (Error E = VDataPtrOrErr.takeError())
937 return E;
938
939 // Note that besides deserialization, this also performs the conversion for
940 // indirect call targets. The function pointers from the raw profile are
941 // remapped into function name hashes.
942 VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get());
943 CurValueDataSize = VDataPtrOrErr.get()->getSize();
944 return success();
945}
946
947template <class IntPtrT>
949 // Keep reading profiles that consist of only headers and no profile data and
950 // counters.
951 while (atEnd())
952 // At this point, ValueDataStart field points to the next header.
953 if (Error E = readNextHeader(getNextHeaderPos()))
954 return error(std::move(E));
955
956 // Read name and set it in Record.
957 if (Error E = readName(Record))
958 return error(std::move(E));
959
960 // Read FuncHash and set it in Record.
961 if (Error E = readFuncHash(Record))
962 return error(std::move(E));
963
964 Record.OffloadDeviceWaveSize = swap(Data->OffloadDeviceWaveSize);
965
966 // Read raw counts and set Record.
967 if (Error E = readRawCounts(Record))
968 return error(std::move(E));
969
970 // Read raw bitmap bytes and set Record.
971 if (Error E = readRawBitmapBytes(Record))
972 return error(std::move(E));
973
974 // Read raw uniform counters and set Record.
975 if (Error E = readRawUniformCounters(Record))
976 return error(std::move(E));
977
978 // Read value data and set Record.
979 if (Error E = readValueProfilingData(Record))
980 return error(std::move(E));
981
982 // Iterate.
983 advanceData();
984 return success();
985}
986
987template <class IntPtrT>
989 std::vector<llvm::object::BuildID> &BinaryIds) {
990 BinaryIds.insert(BinaryIds.begin(), this->BinaryIds.begin(),
991 this->BinaryIds.end());
992 return Error::success();
993}
994
995template <class IntPtrT>
997 if (!BinaryIds.empty())
998 printBinaryIdsInternal(OS, BinaryIds);
999 return Error::success();
1000}
1001
1002namespace llvm {
1003
1004template class RawInstrProfReader<uint32_t>;
1005template class RawInstrProfReader<uint64_t>;
1006
1007} // end namespace llvm
1008
1013
1016
1018 const unsigned char *&D, const unsigned char *const End) {
1020 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
1021
1022 if (VDataPtrOrErr.takeError())
1023 return false;
1024
1025 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
1026 D += VDataPtrOrErr.get()->TotalSize;
1027
1028 return true;
1029}
1030
1032 offset_type N) {
1033 using namespace support;
1034
1035 // Check if the data is corrupt. If so, don't try to read it.
1036 if (N % sizeof(uint64_t))
1037 return data_type();
1038
1039 DataBuffer.clear();
1040 std::vector<uint64_t> CounterBuffer;
1041 std::vector<uint8_t> BitmapByteBuffer;
1042 std::vector<uint8_t> UniformityBitsBuffer;
1043
1044 const unsigned char *End = D + N;
1045 while (D < End) {
1046 // Read hash.
1047 if (D + sizeof(uint64_t) > End)
1048 return data_type();
1050
1051 // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
1052 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
1053 // If format version is different then read the number of counters.
1055 if (D + sizeof(uint64_t) > End)
1056 return data_type();
1058 }
1059 // Read counter values.
1060 if (D + CountsSize * sizeof(uint64_t) > End)
1061 return data_type();
1062
1063 CounterBuffer.clear();
1064 CounterBuffer.reserve(CountsSize);
1065 for (uint64_t J = 0; J < CountsSize; ++J)
1066 CounterBuffer.push_back(
1068
1069 // Read bitmap bytes for GET_VERSION(FormatVersion) > 10.
1071 uint64_t BitmapBytes = 0;
1072 if (D + sizeof(uint64_t) > End)
1073 return data_type();
1075 BitmapByteBuffer.clear();
1076 BitmapByteBuffer.reserve(BitmapBytes);
1077
1078 if (GET_VERSION(FormatVersion) >=
1080 // Version 14+: bitmap bytes stored as uint8_t with padding.
1081 uint64_t PaddedSize = alignTo(BitmapBytes, sizeof(uint64_t));
1082 if (D + PaddedSize > End)
1083 return data_type();
1084 for (uint64_t J = 0; J < BitmapBytes; ++J)
1085 BitmapByteBuffer.push_back(
1087 for (uint64_t J = BitmapBytes; J < PaddedSize; ++J)
1089
1090 // Read uniformity bits (AMDGPU offload profiling).
1091 uint64_t UniformityBitsSize = 0;
1092 if (D + sizeof(uint64_t) > End)
1093 return data_type();
1094 UniformityBitsSize =
1096 uint64_t PaddedUniformitySize =
1097 alignTo(UniformityBitsSize, sizeof(uint64_t));
1098 if (D + PaddedUniformitySize > End)
1099 return data_type();
1100 UniformityBitsBuffer.clear();
1101 UniformityBitsBuffer.reserve(UniformityBitsSize);
1102 for (uint64_t J = 0; J < UniformityBitsSize; ++J)
1103 UniformityBitsBuffer.push_back(
1105 for (uint64_t J = UniformityBitsSize; J < PaddedUniformitySize; ++J)
1107 } else {
1108 // Version 11-13: each bitmap byte stored as a uint64_t.
1109 if (D + BitmapBytes * sizeof(uint64_t) > End)
1110 return data_type();
1111 for (uint64_t J = 0; J < BitmapBytes; ++J)
1112 BitmapByteBuffer.push_back(static_cast<uint8_t>(
1114 }
1115 }
1116
1117 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer),
1118 std::move(BitmapByteBuffer),
1119 std::move(UniformityBitsBuffer));
1120
1121 // Read value profiling data.
1124 DataBuffer.clear();
1125 return data_type();
1126 }
1127 }
1128 return DataBuffer;
1129}
1130
1131template <typename HashTableImpl>
1134 auto Iter = HashTable->find(FuncName);
1135 if (Iter == HashTable->end())
1137
1138 Data = (*Iter);
1139 if (Data.empty())
1141 "profile data is empty");
1142
1143 return Error::success();
1144}
1145
1146template <typename HashTableImpl>
1149 if (atEnd())
1151
1152 Data = *RecordIterator;
1153
1154 if (Data.empty())
1156 "profile data is empty");
1157
1158 return Error::success();
1159}
1160
1161template <typename HashTableImpl>
1163 const unsigned char *Buckets, const unsigned char *const Payload,
1164 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
1165 uint64_t Version) {
1166 FormatVersion = Version;
1167 HashTable.reset(HashTableImpl::Create(
1168 Buckets, Payload, Base,
1169 typename HashTableImpl::InfoType(HashType, Version)));
1170 RecordIterator = HashTable->data_begin();
1171}
1172
1173template <typename HashTableImpl>
1177
1178namespace {
1179/// A remapper that does not apply any remappings.
1180class InstrProfReaderNullRemapper : public InstrProfReaderRemapper {
1181 InstrProfReaderIndexBase &Underlying;
1182
1183public:
1184 InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying)
1185 : Underlying(Underlying) {}
1186
1187 Error getRecords(StringRef FuncName,
1189 return Underlying.getRecords(FuncName, Data);
1190 }
1191};
1192} // namespace
1193
1194/// A remapper that applies remappings based on a symbol remapping file.
1195template <typename HashTableImpl>
1197 : public InstrProfReaderRemapper {
1198public:
1200 std::unique_ptr<MemoryBuffer> RemapBuffer,
1202 : RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) {
1203 }
1204
1205 /// Extract the original function name from a PGO function name.
1207 // We can have multiple pieces separated by kGlobalIdentifierDelimiter (
1208 // semicolon now and colon in older profiles); there can be pieces both
1209 // before and after the mangled name. Find the first part that starts with
1210 // '_Z'; we'll assume that's the mangled name we want.
1211 std::pair<StringRef, StringRef> Parts = {StringRef(), Name};
1212 while (true) {
1213 Parts = Parts.second.split(GlobalIdentifierDelimiter);
1214 if (Parts.first.starts_with("_Z"))
1215 return Parts.first;
1216 if (Parts.second.empty())
1217 return Name;
1218 }
1219 }
1220
1221 /// Given a mangled name extracted from a PGO function name, and a new
1222 /// form for that mangled name, reconstitute the name.
1223 static void reconstituteName(StringRef OrigName, StringRef ExtractedName,
1224 StringRef Replacement,
1225 SmallVectorImpl<char> &Out) {
1226 Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size());
1227 Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin());
1228 llvm::append_range(Out, Replacement);
1229 Out.insert(Out.end(), ExtractedName.end(), OrigName.end());
1230 }
1231
1233 if (Error E = Remappings.read(*RemapBuffer))
1234 return E;
1235 for (StringRef Name : Underlying.HashTable->keys()) {
1236 StringRef RealName = extractName(Name);
1237 if (auto Key = Remappings.insert(RealName)) {
1238 // FIXME: We could theoretically map the same equivalence class to
1239 // multiple names in the profile data. If that happens, we should
1240 // return NamedInstrProfRecords from all of them.
1241 MappedNames.insert({Key, RealName});
1242 }
1243 }
1244 return Error::success();
1245 }
1246
1249 StringRef RealName = extractName(FuncName);
1250 if (auto Key = Remappings.lookup(RealName)) {
1251 StringRef Remapped = MappedNames.lookup(Key);
1252 if (!Remapped.empty()) {
1253 if (RealName.begin() == FuncName.begin() &&
1254 RealName.end() == FuncName.end())
1255 FuncName = Remapped;
1256 else {
1257 // Try rebuilding the name from the given remapping.
1258 SmallString<256> Reconstituted;
1259 reconstituteName(FuncName, RealName, Remapped, Reconstituted);
1260 Error E = Underlying.getRecords(Reconstituted, Data);
1261 if (!E)
1262 return E;
1263
1264 // If we failed because the name doesn't exist, fall back to asking
1265 // about the original name.
1266 if (Error Unhandled = handleErrors(
1267 std::move(E), [](std::unique_ptr<InstrProfError> Err) {
1268 return Err->get() == instrprof_error::unknown_function
1269 ? Error::success()
1270 : Error(std::move(Err));
1271 }))
1272 return Unhandled;
1273 }
1274 }
1275 }
1276 return Underlying.getRecords(FuncName, Data);
1277 }
1278
1279private:
1280 /// The memory buffer containing the remapping configuration. Remappings
1281 /// holds pointers into this buffer.
1282 std::unique_ptr<MemoryBuffer> RemapBuffer;
1283
1284 /// The mangling remapper.
1285 SymbolRemappingReader Remappings;
1286
1287 /// Mapping from mangled name keys to the name used for the key in the
1288 /// profile data.
1289 /// FIXME: Can we store a location within the on-disk hash table instead of
1290 /// redoing lookup?
1292
1293 /// The real profile data reader.
1295};
1296
1298 using namespace support;
1299
1300 if (DataBuffer.getBufferSize() < 8)
1301 return false;
1302 uint64_t Magic = endian::read<uint64_t, aligned>(DataBuffer.getBufferStart(),
1304 // Verify that it's magical.
1305 return Magic == IndexedInstrProf::Magic;
1306}
1307
1308const unsigned char *
1309IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
1310 const unsigned char *Cur, bool UseCS) {
1311 using namespace IndexedInstrProf;
1312 using namespace support;
1313
1315 const IndexedInstrProf::Summary *SummaryInLE =
1316 reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
1317 uint64_t NFields = endian::byte_swap<uint64_t>(
1319 uint64_t NEntries = endian::byte_swap<uint64_t>(
1321 uint32_t SummarySize =
1322 IndexedInstrProf::Summary::getSize(NFields, NEntries);
1323 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
1324 IndexedInstrProf::allocSummary(SummarySize);
1325
1326 const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
1327 uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
1328 for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
1330
1331 SummaryEntryVector DetailedSummary;
1332 for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
1333 const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
1334 DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
1335 Ent.NumBlocks);
1336 }
1337 std::unique_ptr<llvm::ProfileSummary> &Summary =
1338 UseCS ? this->CS_Summary : this->Summary;
1339
1340 // initialize InstrProfSummary using the SummaryData from disk.
1341 Summary = std::make_unique<ProfileSummary>(
1343 DetailedSummary, SummaryData->get(Summary::TotalBlockCount),
1344 SummaryData->get(Summary::MaxBlockCount),
1345 SummaryData->get(Summary::MaxInternalBlockCount),
1346 SummaryData->get(Summary::MaxFunctionCount),
1347 SummaryData->get(Summary::TotalNumBlocks),
1348 SummaryData->get(Summary::TotalNumFunctions));
1349 return Cur + SummarySize;
1350 } else {
1351 // The older versions do not support a profile summary. This just computes
1352 // an empty summary, which will not result in accurate hot/cold detection.
1353 // We would need to call addRecord for all NamedInstrProfRecords to get the
1354 // correct summary. However, this version is old (prior to early 2016) and
1355 // has not been supporting an accurate summary for several years.
1356 InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1357 Summary = Builder.getSummary();
1358 return Cur;
1359 }
1360}
1361
1363 using namespace support;
1364
1365 const unsigned char *Start =
1366 (const unsigned char *)DataBuffer->getBufferStart();
1367 const unsigned char *Cur = Start;
1368 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
1370
1371 auto HeaderOr = IndexedInstrProf::Header::readFromBuffer(Start);
1372 if (!HeaderOr)
1373 return HeaderOr.takeError();
1374
1375 const IndexedInstrProf::Header *Header = &HeaderOr.get();
1376 Cur += Header->size();
1377
1378 Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,
1379 /* UseCS */ false);
1380 if (Header->Version & VARIANT_MASK_CSIR_PROF)
1381 Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,
1382 /* UseCS */ true);
1383 // Read the hash type and start offset.
1384 IndexedInstrProf::HashT HashType =
1385 static_cast<IndexedInstrProf::HashT>(Header->HashType);
1386 if (HashType > IndexedInstrProf::HashT::Last)
1388
1389 // The hash table with profile counts comes next.
1390 auto IndexPtr = std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(
1391 Start + Header->HashOffset, Cur, Start, HashType, Header->Version);
1392
1393 // The MemProfOffset field in the header is only valid when the format
1394 // version is higher than 8 (when it was introduced).
1395 if (Header->getIndexedProfileVersion() >= 8 &&
1396 Header->Version & VARIANT_MASK_MEMPROF) {
1397 if (Error E = MemProfReader.deserialize(Start, Header->MemProfOffset))
1398 return E;
1399 }
1400
1401 // BinaryIdOffset field in the header is only valid when the format version
1402 // is higher than 9 (when it was introduced).
1403 if (Header->getIndexedProfileVersion() >= 9) {
1404 const unsigned char *Ptr = Start + Header->BinaryIdOffset;
1405 // Read binary ids size.
1406 uint64_t BinaryIdsSize =
1408 if (BinaryIdsSize % sizeof(uint64_t))
1409 return error(
1411 ("BinaryIdSize (" + Twine(BinaryIdsSize) + ") is not a multiple of 8")
1412 .str());
1413 // Set the binary ids start.
1414 BinaryIdsBuffer = ArrayRef<uint8_t>(Ptr, BinaryIdsSize);
1415 if (Ptr > (const unsigned char *)DataBuffer->getBufferEnd())
1417 "corrupted binary ids");
1418 }
1419
1420 if (Header->getIndexedProfileVersion() >= 12) {
1421 const unsigned char *Ptr = Start + Header->VTableNamesOffset;
1422
1423 uint64_t CompressedVTableNamesLen =
1425
1426 // Writer first writes the length of compressed string, and then the actual
1427 // content.
1428 const char *VTableNamePtr = (const char *)Ptr;
1429 if (VTableNamePtr > DataBuffer->getBufferEnd())
1431
1432 VTableName = StringRef(VTableNamePtr, CompressedVTableNamesLen);
1433 }
1434
1435 if (Header->getIndexedProfileVersion() >= 10 &&
1436 Header->Version & VARIANT_MASK_TEMPORAL_PROF) {
1437 const unsigned char *Ptr = Start + Header->TemporalProfTracesOffset;
1438 const auto *PtrEnd = (const unsigned char *)DataBuffer->getBufferEnd();
1439 // Expect at least two 64 bit fields: NumTraces, and TraceStreamSize
1440 if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)
1442 const uint64_t NumTraces =
1446 for (unsigned i = 0; i < NumTraces; i++) {
1447 // Expect at least two 64 bit fields: Weight and NumFunctions
1448 if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)
1451 Trace.Weight =
1453 const uint64_t NumFunctions =
1455 // Expect at least NumFunctions 64 bit fields
1456 if (Ptr + NumFunctions * sizeof(uint64_t) > PtrEnd)
1458 for (unsigned j = 0; j < NumFunctions; j++) {
1459 const uint64_t NameRef =
1461 Trace.FunctionNameRefs.push_back(NameRef);
1462 }
1463 TemporalProfTraces.push_back(std::move(Trace));
1464 }
1465 }
1466
1467 // Load the remapping table now if requested.
1468 if (RemappingBuffer) {
1469 Remapper =
1470 std::make_unique<InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>(
1471 std::move(RemappingBuffer), *IndexPtr);
1472 if (Error E = Remapper->populateRemappings())
1473 return E;
1474 } else {
1475 Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);
1476 }
1477 Index = std::move(IndexPtr);
1478
1479 return success();
1480}
1481
1483 if (Symtab)
1484 return *Symtab;
1485
1486 auto NewSymtab = std::make_unique<InstrProfSymtab>();
1487
1488 if (Error E = NewSymtab->initVTableNamesFromCompressedStrings(VTableName)) {
1489 auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
1490 consumeError(error(ErrCode, Msg));
1491 }
1492
1493 // finalizeSymtab is called inside populateSymtab.
1494 if (Error E = Index->populateSymtab(*NewSymtab)) {
1495 auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
1496 consumeError(error(ErrCode, Msg));
1497 }
1498
1499 Symtab = std::move(NewSymtab);
1500 return *Symtab;
1501}
1502
1504 StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName,
1505 uint64_t *MismatchedFuncSum) {
1507 uint64_t FuncSum = 0;
1508 auto Err = Remapper->getRecords(FuncName, Data);
1509 if (Err) {
1510 // If we don't find FuncName, try DeprecatedFuncName to handle profiles
1511 // built by older compilers.
1512 auto Err2 =
1513 handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {
1514 if (IE.get() != instrprof_error::unknown_function)
1515 return make_error<InstrProfError>(IE);
1516 if (auto Err = Remapper->getRecords(DeprecatedFuncName, Data))
1517 return Err;
1518 return Error::success();
1519 });
1520 if (Err2)
1521 return std::move(Err2);
1522 }
1523 // Found it. Look for counters with the right hash.
1524
1525 // A flag to indicate if the records are from the same type
1526 // of profile (i.e cs vs nocs).
1527 bool CSBitMatch = false;
1528 auto getFuncSum = [](ArrayRef<uint64_t> Counts) {
1529 uint64_t ValueSum = 0;
1530 for (uint64_t CountValue : Counts) {
1531 if (CountValue == (uint64_t)-1)
1532 continue;
1533 // Handle overflow -- if that happens, return max.
1534 if (std::numeric_limits<uint64_t>::max() - CountValue <= ValueSum)
1535 return std::numeric_limits<uint64_t>::max();
1536 ValueSum += CountValue;
1537 }
1538 return ValueSum;
1539 };
1540
1541 for (const NamedInstrProfRecord &I : Data) {
1542 // Check for a match and fill the vector if there is one.
1543 if (I.Hash == FuncHash)
1544 return std::move(I);
1547 CSBitMatch = true;
1548 if (MismatchedFuncSum == nullptr)
1549 continue;
1550 FuncSum = std::max(FuncSum, getFuncSum(I.Counts));
1551 }
1552 }
1553 if (CSBitMatch) {
1554 if (MismatchedFuncSum != nullptr)
1555 *MismatchedFuncSum = FuncSum;
1557 }
1559}
1560
1562IndexedMemProfReader::getMemProfRecord(const uint64_t FuncNameHash) const {
1563 // TODO: Add memprof specific errors.
1564 if (MemProfRecordTable == nullptr)
1566 "no memprof data available in profile");
1567 auto Iter = MemProfRecordTable->find(FuncNameHash);
1568 if (Iter == MemProfRecordTable->end())
1571 "memprof record not found for function hash " + Twine(FuncNameHash));
1572
1573 const memprof::IndexedMemProfRecord &IndexedRecord = *Iter;
1574 switch (Version) {
1575 // Combine V3 and V4 cases as the record conversion logic is the same.
1576 case memprof::Version3:
1577 case memprof::Version4:
1578 assert(FrameBase && "FrameBase must be available");
1579 assert(CallStackBase && "CallStackBase must be available");
1580 {
1581 memprof::LinearFrameIdConverter FrameIdConv(FrameBase);
1582 memprof::LinearCallStackIdConverter CSIdConv(CallStackBase, FrameIdConv);
1583 memprof::MemProfRecord Record = IndexedRecord.toMemProfRecord(CSIdConv);
1584 return Record;
1585 }
1586 }
1587
1590 formatv("MemProf version {} not supported; "
1591 "requires version between {} and {}, inclusive",
1594}
1595
1598 assert(MemProfRecordTable);
1599 assert(Version == memprof::Version3 || Version == memprof::Version4);
1600
1601 memprof::LinearFrameIdConverter FrameIdConv(FrameBase);
1602 memprof::CallerCalleePairExtractor Extractor(CallStackBase, FrameIdConv,
1603 RadixTreeSize);
1604
1605 // The set of linear call stack IDs that we need to traverse from. We expect
1606 // the set to be dense, so we use a BitVector.
1607 BitVector Worklist(RadixTreeSize);
1608
1609 // Collect the set of linear call stack IDs. Since we expect a lot of
1610 // duplicates, we first collect them in the form of a bit vector before
1611 // processing them.
1612 for (const memprof::IndexedMemProfRecord &IndexedRecord :
1613 MemProfRecordTable->data()) {
1614 for (const memprof::IndexedAllocationInfo &IndexedAI :
1615 IndexedRecord.AllocSites)
1616 Worklist.set(IndexedAI.CSId);
1617 }
1618
1619 // Collect caller-callee pairs for each linear call stack ID in Worklist.
1620 for (unsigned CS : Worklist.set_bits())
1621 Extractor(CS);
1622
1624 std::move(Extractor.CallerCalleePairs);
1625
1626 // Sort each call list by the source location.
1627 for (auto &[CallerGUID, CallList] : Pairs) {
1628 llvm::sort(CallList);
1629 CallList.erase(llvm::unique(CallList), CallList.end());
1630 }
1631
1632 return Pairs;
1633}
1634
1636 memprof::AllMemProfData AllMemProfData;
1637 AllMemProfData.HeapProfileRecords.reserve(
1638 MemProfRecordTable->getNumEntries());
1639 for (uint64_t Key : MemProfRecordTable->keys()) {
1640 auto Record = getMemProfRecord(Key);
1641 if (Record.takeError())
1642 continue;
1644 Pair.GUID = Key;
1645 Pair.Record = std::move(*Record);
1646 AllMemProfData.HeapProfileRecords.push_back(std::move(Pair));
1647 }
1648 // Populate the data access profiles for yaml output.
1649 if (DataAccessProfileData != nullptr) {
1650 AllMemProfData.YamlifiedDataAccessProfiles.Records.reserve(
1651 DataAccessProfileData->getRecords().size());
1652 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdSymbols.reserve(
1653 DataAccessProfileData->getKnownColdSymbols().size());
1654 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdStrHashes.reserve(
1655 DataAccessProfileData->getKnownColdHashes().size());
1656 for (const auto &[SymHandleRef, RecordRef] :
1657 DataAccessProfileData->getRecords())
1658 AllMemProfData.YamlifiedDataAccessProfiles.Records.push_back(
1659 memprof::DataAccessProfRecord(SymHandleRef, RecordRef.AccessCount,
1660 RecordRef.Locations));
1661 for (StringRef ColdSymbol : DataAccessProfileData->getKnownColdSymbols())
1662 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdSymbols.push_back(
1663 ColdSymbol.str());
1664 for (uint64_t Hash : DataAccessProfileData->getKnownColdHashes())
1665 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdStrHashes.push_back(
1666 Hash);
1670 return lhs.AccessCount > rhs.AccessCount;
1671 });
1674 [](const std::string &lhs, const std::string &rhs) {
1675 return lhs < rhs;
1676 });
1679 [](const uint64_t &lhs, const uint64_t &rhs) { return lhs < rhs; });
1680 }
1681 return AllMemProfData;
1682}
1683
1685 uint64_t FuncHash,
1686 std::vector<uint64_t> &Counts) {
1687 auto Record = getInstrProfRecord(FuncName, FuncHash);
1688 if (Error E = Record.takeError())
1689 return error(std::move(E));
1690
1691 Counts = Record.get().Counts;
1692 return success();
1693}
1694
1696 uint64_t FuncHash,
1697 BitVector &Bitmap) {
1698 auto Record = getInstrProfRecord(FuncName, FuncHash);
1699 if (Error E = Record.takeError())
1700 return error(std::move(E));
1701
1702 const auto &BitmapBytes = Record.get().BitmapBytes;
1703 size_t I = 0, E = BitmapBytes.size();
1704 Bitmap.resize(E * CHAR_BIT);
1706 [&](auto X) {
1707 using XTy = decltype(X);
1708 alignas(XTy) uint8_t W[sizeof(X)];
1709 size_t N = std::min(E - I, sizeof(W));
1710 std::memset(W, 0, sizeof(W));
1711 std::memcpy(W, &BitmapBytes[I], N);
1712 I += N;
1715 },
1716 Bitmap, Bitmap);
1717 assert(I == E);
1718
1719 return success();
1720}
1721
1724
1725 Error E = Index->getRecords(Data);
1726 if (E)
1727 return error(std::move(E));
1728
1729 Record = Data[RecordIndex++];
1730 if (RecordIndex >= Data.size()) {
1731 Index->advanceToNextKey();
1732 RecordIndex = 0;
1733 }
1734 return success();
1735}
1736
1738 std::vector<llvm::object::BuildID> &BinaryIds) {
1739 return readBinaryIdsInternal(*DataBuffer, BinaryIdsBuffer, BinaryIds,
1741}
1742
1744 std::vector<llvm::object::BuildID> BinaryIds;
1745 if (Error E = readBinaryIds(BinaryIds))
1746 return E;
1747 printBinaryIdsInternal(OS, BinaryIds);
1748 return Error::success();
1749}
1750
1752 uint64_t NumFuncs = 0;
1753 for (const auto &Func : *this) {
1754 if (isIRLevelProfile()) {
1755 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
1756 if (FuncIsCS != IsCS)
1757 continue;
1758 }
1759 Func.accumulateCounts(Sum);
1760 ++NumFuncs;
1761 }
1762 Sum.NumEntries = NumFuncs;
1763}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
InstrProfLookupTrait::offset_type offset_type
static Error initializeReader(InstrProfReader &Reader)
#define READ_NUM(Str, Dst)
#define CHECK_LINE_END(Line)
static Error readBinaryIdsInternal(const MemoryBuffer &DataBuffer, ArrayRef< uint8_t > BinaryIdsBuffer, std::vector< llvm::object::BuildID > &BinaryIds, const llvm::endianness Endian)
Read a list of binary ids from a profile that consist of a.
#define VP_READ_ADVANCE(Val)
InstrProfLookupTrait::data_type data_type
static InstrProfKind getProfileKindFromVersion(uint64_t Version)
static void printBinaryIdsInternal(raw_ostream &OS, ArrayRef< llvm::object::BuildID > BinaryIds)
#define GET_VERSION(V)
#define VARIANT_MASK_CSIR_PROF
#define VARIANT_MASK_MEMPROF
#define VARIANT_MASK_TEMPORAL_PROF
#define VARIANT_MASK_IR_PROF
#define VARIANT_MASK_BYTE_COVERAGE
#define VARIANT_MASK_INSTR_ENTRY
#define VARIANT_MASK_FUNCTION_ENTRY_ONLY
#define VARIANT_MASK_INSTR_LOOP_ENTRIES
#define I(x, y, z)
Definition MD5.cpp:57
static constexpr StringLiteral Filename
static StringRef getName(Value *V)
const char * Msg
This file contains some functions that are useful when dealing with strings.
#define error(X)
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
static BitVector & apply(F &&f, BitVector &Out, BitVector const &Arg, ArgTys const &...Args)
Definition BitVector.h:595
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
Reader for the indexed binary instrprof format.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
Error readHeader() override
Read the file header.
Error printBinaryIds(raw_ostream &OS) override
Print binary ids.
Error getFunctionBitmap(StringRef FuncName, uint64_t FuncHash, BitVector &Bitmap)
Fill Bitmap with the profile data for the given function name.
InstrProfSymtab & getSymtab() override
Return the PGO symtab.
static bool hasFormat(const MemoryBuffer &DataBuffer)
Return true if the given buffer is in an indexed instrprof format.
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
Expected< NamedInstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName="", uint64_t *MismatchedFuncSum=nullptr)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
Error readBinaryIds(std::vector< llvm::object::BuildID > &BinaryIds) override
Read a list of binary ids.
LLVM_ABI memprof::AllMemProfData getAllMemProfData() const
LLVM_ABI Expected< memprof::MemProfRecord > getMemProfRecord(const uint64_t FuncNameHash) const
LLVM_ABI DenseMap< uint64_t, SmallVector< memprof::CallEdgeTy, 0 > > getMemProfCallerCalleePairs() const
InstrProfCorrelatorImpl - A child of InstrProfCorrelator with a template pointer type so that the Pro...
const RawInstrProf::ProfileData< IntPtrT > * getDataPointer() const
Return a pointer to the underlying ProfileData vector that this class constructs.
size_t getDataSize() const
Return the number of ProfileData elements.
InstrProfCorrelator - A base class used to create raw instrumentation data to their functions.
const char * getNamesPointer() const
Return a pointer to the names string that this class constructs.
LLVM_ABI std::optional< size_t > getDataSize() const
Return the number of ProfileData elements.
static LLVM_ABI llvm::Expected< std::unique_ptr< InstrProfCorrelator > > get(StringRef Filename, ProfCorrelatorKind FileKind, const object::BuildIDFetcher *BIDFetcher=nullptr, const ArrayRef< llvm::object::BuildID > BIs={})
size_t getNamesSize() const
Return the number of bytes in the names string.
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition InstrProf.h:465
LLVM_ABI data_type ReadData(StringRef K, const unsigned char *D, offset_type N)
LLVM_ABI bool readValueProfilingData(const unsigned char *&D, const unsigned char *const End)
LLVM_ABI hash_value_type ComputeHash(StringRef K)
ArrayRef< NamedInstrProfRecord > data_type
InstrProfKind getProfileKind() const override
Error getRecords(ArrayRef< NamedInstrProfRecord > &Data) override
InstrProfReaderIndex(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, IndexedInstrProf::HashT HashType, uint64_t Version)
bool atEnd() const override
A remapper that applies remappings based on a symbol remapping file.
static StringRef extractName(StringRef Name)
Extract the original function name from a PGO function name.
InstrProfReaderItaniumRemapper(std::unique_ptr< MemoryBuffer > RemapBuffer, InstrProfReaderIndex< HashTableImpl > &Underlying)
static void reconstituteName(StringRef OrigName, StringRef ExtractedName, StringRef Replacement, SmallVectorImpl< char > &Out)
Given a mangled name extracted from a PGO function name, and a new form for that mangled name,...
Error getRecords(StringRef FuncName, ArrayRef< NamedInstrProfRecord > &Data) override
Name matcher supporting fuzzy matching of symbol names to names in profiles.
Base class and interface for reading profiling data of any known instrprof format.
std::unique_ptr< InstrProfSymtab > Symtab
Error success()
Clear the current error and return a successful one.
static LLVM_ABI Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr, const object::BuildIDFetcher *BIDFetcher=nullptr, std::optional< ProfCorrelatorKind > BIDFetcherCorrelatorKind=std::nullopt, std::function< void(Error)> Warn=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
SmallVector< TemporalProfTraceTy > TemporalProfTraces
A list of temporal profile traces.
uint64_t TemporalProfTraceStreamSize
The total number of temporal profile traces seen.
virtual bool isIRLevelProfile() const =0
virtual Error readHeader()=0
Read the header. Required before reading first record.
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum, bool IsCS)
Compute the sum of counts and return in Sum.
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:500
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Definition InstrProf.h:721
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition InstrProf.h:688
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val)
Map the address range (i.e., [start_address, end_address)) of a variable to its names' MD5 hash.
Definition InstrProf.h:695
This interface provides simple read-only access to a block of memory, and provides simple methods for...
size_t getBufferSize() const
const char * getBufferEnd() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getSTDIN()
Read all of stdin into a file buffer, and return it.
const char * getBufferStart() const
static LLVM_ABI const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
Reader for the raw instrprof binary format from runtime.
Error readHeader() override
Read the header. Required before reading first record.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
Error printBinaryIds(raw_ostream &OS) override
Print binary ids.
static bool hasFormat(const MemoryBuffer &DataBuffer)
InstrProfKind getProfileKind() const override
Returns a BitsetEnum describing the attributes of the raw instr profile.
Error readBinaryIds(std::vector< llvm::object::BuildID > &BinaryIds) override
Read a list of binary ids.
SmallVector< TemporalProfTraceTy > & getTemporalProfTraces(std::optional< uint64_t > Weight={}) override
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
char front() const
Get the first character in the string.
Definition StringRef.h:147
iterator end() const
Definition StringRef.h:116
Reader for symbol remapping files.
Reader for the simple text based instrprof format.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if the given buffer is in text instrprof format.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
Error readHeader() override
Read the header.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
BuildIDFetcher searches local cache directories for debug info.
Definition BuildID.h:41
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
The virtual file system interface.
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
Definition InstrProf.h:1359
uint64_t ComputeHash(StringRef K)
Definition InstrProf.h:1240
const uint64_t Magic
Definition InstrProf.h:1193
uint64_t getMagic()
const uint64_t Version
Definition InstrProf.h:1382
constexpr uint64_t MaximumSupportedVersion
Definition MemProf.h:51
constexpr uint64_t MinimumSupportedVersion
Definition MemProf.h:50
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
Definition BuildID.h:27
value_type byte_swap(value_type value, endianness endian)
Swap the bytes of value to match the given endianness.
Definition Endian.h:45
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:53
value_type readNext(const CharT *&memory, endianness endian)
Read a value of a particular endianness from a buffer, and increment the buffer past that value.
Definition Endian.h:67
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
RawInstrProfReader< uint64_t > RawInstrProfReader64
static Expected< std::unique_ptr< MemoryBuffer > > setupMemoryBuffer(const Twine &Filename, vfs::FileSystem &FS)
RelativeUniformCounterPtr ValuesPtrExpr NumBitmapBytes
Definition InstrProf.h:101
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:95
constexpr T byteswap(T V) noexcept
Reverses the bytes in the given integer value V.
Definition bit.h:102
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr UniformCountersDelta
Definition InstrProf.h:210
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr UniformCountersStart
Definition InstrProf.h:179
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
FuncHash
Definition InstrProf.h:78
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition MathExtras.h:493
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
bool isDigit(char C)
Checks if character C is one of the 10 decimal digits.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr CountersStart
Definition InstrProf.h:167
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr NamesStart
Definition InstrProf.h:161
constexpr char GlobalIdentifierDelimiter
Definition GlobalValue.h:47
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
std::vector< ProfileSummaryEntry > SummaryEntryVector
endianness
Definition bit.h:71
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition InstrProf.h:366
RawInstrProfReader< uint32_t > RawInstrProfReader32
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
LLVM_ABI size_t size() const
static LLVM_ABI Expected< Header > readFromBuffer(const unsigned char *Buffer)
uint64_t Cutoff
The required percentile of total execution count.
Definition InstrProf.h:1283
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition InstrProf.h:1286
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition InstrProf.h:1285
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition InstrProf.h:1319
Profiling information for a single function.
Definition InstrProf.h:907
static bool hasCSFlagInHash(uint64_t FuncHash)
Definition InstrProf.h:1126
An ordered list of functions identified by their NameRef found in INSTR_PROF_DATA.
Definition InstrProf.h:424
YamlDataAccessProfData YamlifiedDataAccessProfiles
Definition MemProfYAML.h:41
std::vector< GUIDMemProfRecordPair > HeapProfileRecords
Definition MemProfYAML.h:40
The data access profiles for a symbol.
LLVM_ABI MemProfRecord toMemProfRecord(llvm::function_ref< std::vector< Frame >(const CallStackId)> Callback) const
Definition MemProf.cpp:241
std::vector< memprof::DataAccessProfRecord > Records
Definition MemProfYAML.h:28
std::vector< uint64_t > KnownColdStrHashes
Definition MemProfYAML.h:29
std::vector< std::string > KnownColdSymbols
Definition MemProfYAML.h:30