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 // Continuous mode currently does not write value profile data. We keep track
742 // of this so we don't try to decode a non-existent value profile section.
743 HasValueProfData =
744 ValueDataStart + sizeof(ValueProfData) <= BufferEnd &&
745 support::endian::read64(ValueDataStart, getDataEndianness()) !=
747 support::endian::read32(ValueDataStart, getDataEndianness()) != 0;
748
749 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
750 if (Error E = createSymtab(*NewSymtab))
751 return E;
752
753 Symtab = std::move(NewSymtab);
754 return success();
755}
756
757template <class IntPtrT>
758Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) {
759 Record.Name = getName(Data->NameRef);
760 return success();
761}
762
763template <class IntPtrT>
764Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) {
765 Record.Hash = swap(Data->FuncHash);
766 return success();
767}
768
769template <class IntPtrT>
770Error RawInstrProfReader<IntPtrT>::readRawCounts(
772 uint32_t NumCounters = swap(Data->NumCounters);
773 if (NumCounters == 0)
774 return error(instrprof_error::malformed, "number of counters is zero");
775
776 ptrdiff_t CounterBaseOffset = swap(Data->CounterPtr) - CountersDelta;
777 if (CounterBaseOffset < 0)
778 return error(
780 ("counter offset " + Twine(CounterBaseOffset) + " is negative").str());
781
782 if (CounterBaseOffset >= CountersEnd - CountersStart)
784 ("counter offset " + Twine(CounterBaseOffset) +
785 " is greater than the maximum counter offset " +
786 Twine(CountersEnd - CountersStart - 1))
787 .str());
788
789 uint64_t MaxNumCounters =
790 (CountersEnd - (CountersStart + CounterBaseOffset)) /
791 getCounterTypeSize();
792 if (NumCounters > MaxNumCounters)
794 ("number of counters " + Twine(NumCounters) +
795 " is greater than the maximum number of counters " +
796 Twine(MaxNumCounters))
797 .str());
798
799 Record.Counts.clear();
800 Record.Counts.reserve(NumCounters);
801 for (uint32_t I = 0; I < NumCounters; I++) {
802 const char *Ptr =
803 CountersStart + CounterBaseOffset + I * getCounterTypeSize();
804 if (I == 0 && hasTemporalProfile()) {
805 uint64_t TimestampValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
806 if (TimestampValue != 0 &&
807 TimestampValue != std::numeric_limits<uint64_t>::max()) {
808 TemporalProfTimestamps.emplace_back(TimestampValue,
809 swap(Data->NameRef));
810 TemporalProfTraceStreamSize = 1;
811 }
812 if (hasSingleByteCoverage()) {
813 // In coverage mode, getCounterTypeSize() returns 1 byte but our
814 // timestamp field has size uint64_t. Increment I so that the next
815 // iteration of this for loop points to the byte after the timestamp
816 // field, i.e., I += 8.
817 I += 7;
818 }
819 continue;
820 }
821 if (hasSingleByteCoverage()) {
822 // A value of zero signifies the block is covered.
823 Record.Counts.push_back(*Ptr == 0 ? 1 : 0);
824 } else {
825 uint64_t CounterValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
826 if (CounterValue > MaxCounterValue && Warn)
829
830 Record.Counts.push_back(CounterValue);
831 }
832 }
833
834 return success();
835}
836
837template <class IntPtrT>
838Error RawInstrProfReader<IntPtrT>::readRawBitmapBytes(InstrProfRecord &Record) {
839 uint32_t NumBitmapBytes = swap(Data->NumBitmapBytes);
840
841 Record.BitmapBytes.clear();
842 Record.BitmapBytes.reserve(NumBitmapBytes);
843
844 // It's possible MCDC is either not enabled or only used for some functions
845 // and not others. So if we record 0 bytes, just move on.
846 if (NumBitmapBytes == 0)
847 return success();
848
849 // BitmapDelta decreases as we advance to the next data record.
850 ptrdiff_t BitmapOffset = swap(Data->BitmapPtr) - BitmapDelta;
851 if (BitmapOffset < 0)
852 return error(
854 ("bitmap offset " + Twine(BitmapOffset) + " is negative").str());
855
856 if (BitmapOffset >= BitmapEnd - BitmapStart)
858 ("bitmap offset " + Twine(BitmapOffset) +
859 " is greater than the maximum bitmap offset " +
860 Twine(BitmapEnd - BitmapStart - 1))
861 .str());
862
863 uint64_t MaxNumBitmapBytes =
864 (BitmapEnd - (BitmapStart + BitmapOffset)) / sizeof(uint8_t);
865 if (NumBitmapBytes > MaxNumBitmapBytes)
867 ("number of bitmap bytes " + Twine(NumBitmapBytes) +
868 " is greater than the maximum number of bitmap bytes " +
869 Twine(MaxNumBitmapBytes))
870 .str());
871
872 for (uint32_t I = 0; I < NumBitmapBytes; I++) {
873 const char *Ptr = BitmapStart + BitmapOffset + I;
874 Record.BitmapBytes.push_back(swap(*Ptr));
875 }
876
877 return success();
878}
879
880template <class IntPtrT>
881Error RawInstrProfReader<IntPtrT>::readRawUniformCounters(
883 Record.UniformCounts.clear();
884
885 if (UniformCountersStart == UniformCountersEnd)
886 return success();
887
888 uint32_t NumCounters = swap(Data->NumCounters);
889
890 ptrdiff_t UniformCounterOffset =
891 swap(Data->UniformCounterPtr) - UniformCountersDelta;
892 if (UniformCounterOffset < 0)
894 ("uniform counter offset " + Twine(UniformCounterOffset) +
895 " is negative")
896 .str());
897
898 if (UniformCounterOffset >= UniformCountersEnd - UniformCountersStart)
900 ("uniform counter offset " + Twine(UniformCounterOffset) +
901 " is greater than the maximum uniform counter offset " +
902 Twine(UniformCountersEnd - UniformCountersStart - 1))
903 .str());
904
905 uint64_t MaxNumCounters =
906 (UniformCountersEnd - (UniformCountersStart + UniformCounterOffset)) /
907 sizeof(uint64_t);
908 if (NumCounters > MaxNumCounters)
910 ("number of uniform counters " + Twine(NumCounters) +
911 " is greater than the maximum number of uniform counters " +
912 Twine(MaxNumCounters))
913 .str());
914
915 Record.UniformCounts.reserve(NumCounters);
916 for (uint32_t I = 0; I < NumCounters; I++) {
917 const char *Ptr =
918 UniformCountersStart + UniformCounterOffset + I * sizeof(uint64_t);
919 uint64_t CounterValue = swap(*reinterpret_cast<const uint64_t *>(Ptr));
920 Record.UniformCounts.push_back(CounterValue);
921 }
922
923 return success();
924}
925
926template <class IntPtrT>
927Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
929 Record.clearValueData();
930 CurValueDataSize = 0;
931 // Need to match the logic in value profile dumper code in compiler-rt:
932 uint32_t NumValueKinds = 0;
933 for (uint32_t I = 0; I < IPVK_Last + 1; I++)
934 NumValueKinds += (Data->NumValueSites[I] != 0);
935
936 if (!NumValueKinds)
937 return success();
938
939 // Continuous mode currently does not write value profile data, so there is
940 // nothing to decode. Add the value sites with no values so the record still
941 // matches the site counts of the IR and of other profiles.
942 if (!HasValueProfData) {
943 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
944 uint16_t NumSites = swap(Data->NumValueSites[Kind]);
945 Record.reserveSites(Kind, NumSites);
946 for (uint32_t Site = 0; Site < NumSites; ++Site)
947 Record.addValueData(Kind, Site, {}, nullptr);
948 }
949 return success();
950 }
951
953 ValueProfData::getValueProfData(
954 ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
955 getDataEndianness());
956
957 if (Error E = VDataPtrOrErr.takeError())
958 return E;
959
960 // Note that besides deserialization, this also performs the conversion for
961 // indirect call targets. The function pointers from the raw profile are
962 // remapped into function name hashes.
963 VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get());
964 CurValueDataSize = VDataPtrOrErr.get()->getSize();
965 return success();
966}
967
968template <class IntPtrT>
970 // Keep reading profiles that consist of only headers and no profile data and
971 // counters.
972 while (atEnd())
973 // At this point, ValueDataStart field points to the next header.
974 if (Error E = readNextHeader(getNextHeaderPos()))
975 return error(std::move(E));
976
977 // Read name and set it in Record.
978 if (Error E = readName(Record))
979 return error(std::move(E));
980
981 // Read FuncHash and set it in Record.
982 if (Error E = readFuncHash(Record))
983 return error(std::move(E));
984
985 Record.OffloadDeviceWaveSize = swap(Data->OffloadDeviceWaveSize);
986
987 // Read raw counts and set Record.
988 if (Error E = readRawCounts(Record))
989 return error(std::move(E));
990
991 // Read raw bitmap bytes and set Record.
992 if (Error E = readRawBitmapBytes(Record))
993 return error(std::move(E));
994
995 // Read raw uniform counters and set Record.
996 if (Error E = readRawUniformCounters(Record))
997 return error(std::move(E));
998
999 // Read value data and set Record.
1000 if (Error E = readValueProfilingData(Record))
1001 return error(std::move(E));
1002
1003 // Iterate.
1004 advanceData();
1005 return success();
1006}
1007
1008template <class IntPtrT>
1010 std::vector<llvm::object::BuildID> &BinaryIds) {
1011 BinaryIds.insert(BinaryIds.begin(), this->BinaryIds.begin(),
1012 this->BinaryIds.end());
1013 return Error::success();
1014}
1015
1016template <class IntPtrT>
1018 if (!BinaryIds.empty())
1019 printBinaryIdsInternal(OS, BinaryIds);
1020 return Error::success();
1021}
1022
1023namespace llvm {
1024
1025template class RawInstrProfReader<uint32_t>;
1026template class RawInstrProfReader<uint64_t>;
1027
1028} // end namespace llvm
1029
1034
1037
1039 const unsigned char *&D, const unsigned char *const End) {
1041 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
1042
1043 if (VDataPtrOrErr.takeError())
1044 return false;
1045
1046 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
1047 D += VDataPtrOrErr.get()->TotalSize;
1048
1049 return true;
1050}
1051
1053 offset_type N) {
1054 using namespace support;
1055
1056 // Check if the data is corrupt. If so, don't try to read it.
1057 if (N % sizeof(uint64_t))
1058 return data_type();
1059
1060 DataBuffer.clear();
1061 std::vector<uint64_t> CounterBuffer;
1062 std::vector<uint8_t> BitmapByteBuffer;
1063 std::vector<uint8_t> UniformityBitsBuffer;
1064
1065 const unsigned char *End = D + N;
1066 while (D < End) {
1067 // Read hash.
1068 if (D + sizeof(uint64_t) > End)
1069 return data_type();
1071
1072 // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
1073 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
1074 // If format version is different then read the number of counters.
1076 if (D + sizeof(uint64_t) > End)
1077 return data_type();
1079 }
1080 // Read counter values.
1081 if (D + CountsSize * sizeof(uint64_t) > End)
1082 return data_type();
1083
1084 CounterBuffer.clear();
1085 CounterBuffer.reserve(CountsSize);
1086 for (uint64_t J = 0; J < CountsSize; ++J)
1087 CounterBuffer.push_back(
1089
1090 // Read bitmap bytes for GET_VERSION(FormatVersion) > 10.
1092 uint64_t BitmapBytes = 0;
1093 if (D + sizeof(uint64_t) > End)
1094 return data_type();
1096 BitmapByteBuffer.clear();
1097 BitmapByteBuffer.reserve(BitmapBytes);
1098
1099 if (GET_VERSION(FormatVersion) >=
1101 // Version 14+: bitmap bytes stored as uint8_t with padding.
1102 uint64_t PaddedSize = alignTo(BitmapBytes, sizeof(uint64_t));
1103 if (D + PaddedSize > End)
1104 return data_type();
1105 for (uint64_t J = 0; J < BitmapBytes; ++J)
1106 BitmapByteBuffer.push_back(
1108 for (uint64_t J = BitmapBytes; J < PaddedSize; ++J)
1110
1111 // Read uniformity bits (AMDGPU offload profiling).
1112 uint64_t UniformityBitsSize = 0;
1113 if (D + sizeof(uint64_t) > End)
1114 return data_type();
1115 UniformityBitsSize =
1117 uint64_t PaddedUniformitySize =
1118 alignTo(UniformityBitsSize, sizeof(uint64_t));
1119 if (D + PaddedUniformitySize > End)
1120 return data_type();
1121 UniformityBitsBuffer.clear();
1122 UniformityBitsBuffer.reserve(UniformityBitsSize);
1123 for (uint64_t J = 0; J < UniformityBitsSize; ++J)
1124 UniformityBitsBuffer.push_back(
1126 for (uint64_t J = UniformityBitsSize; J < PaddedUniformitySize; ++J)
1128 } else {
1129 // Version 11-13: each bitmap byte stored as a uint64_t.
1130 if (D + BitmapBytes * sizeof(uint64_t) > End)
1131 return data_type();
1132 for (uint64_t J = 0; J < BitmapBytes; ++J)
1133 BitmapByteBuffer.push_back(static_cast<uint8_t>(
1135 }
1136 }
1137
1138 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer),
1139 std::move(BitmapByteBuffer),
1140 std::move(UniformityBitsBuffer));
1141
1142 // Read value profiling data.
1145 DataBuffer.clear();
1146 return data_type();
1147 }
1148 }
1149 return DataBuffer;
1150}
1151
1152template <typename HashTableImpl>
1155 auto Iter = HashTable->find(FuncName);
1156 if (Iter == HashTable->end())
1158
1159 Data = (*Iter);
1160 if (Data.empty())
1162 "profile data is empty");
1163
1164 return Error::success();
1165}
1166
1167template <typename HashTableImpl>
1170 if (atEnd())
1172
1173 Data = *RecordIterator;
1174
1175 if (Data.empty())
1177 "profile data is empty");
1178
1179 return Error::success();
1180}
1181
1182template <typename HashTableImpl>
1184 const unsigned char *Buckets, const unsigned char *const Payload,
1185 const unsigned char *const Base, IndexedInstrProf::HashT HashType,
1186 uint64_t Version) {
1187 FormatVersion = Version;
1188 HashTable.reset(HashTableImpl::Create(
1189 Buckets, Payload, Base,
1190 typename HashTableImpl::InfoType(HashType, Version)));
1191 RecordIterator = HashTable->data_begin();
1192}
1193
1194template <typename HashTableImpl>
1198
1199namespace {
1200/// A remapper that does not apply any remappings.
1201class InstrProfReaderNullRemapper : public InstrProfReaderRemapper {
1202 InstrProfReaderIndexBase &Underlying;
1203
1204public:
1205 InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying)
1206 : Underlying(Underlying) {}
1207
1208 Error getRecords(StringRef FuncName,
1210 return Underlying.getRecords(FuncName, Data);
1211 }
1212};
1213} // namespace
1214
1215/// A remapper that applies remappings based on a symbol remapping file.
1216template <typename HashTableImpl>
1218 : public InstrProfReaderRemapper {
1219public:
1221 std::unique_ptr<MemoryBuffer> RemapBuffer,
1223 : RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) {
1224 }
1225
1226 /// Extract the original function name from a PGO function name.
1228 // We can have multiple pieces separated by kGlobalIdentifierDelimiter (
1229 // semicolon now and colon in older profiles); there can be pieces both
1230 // before and after the mangled name. Find the first part that starts with
1231 // '_Z'; we'll assume that's the mangled name we want.
1232 std::pair<StringRef, StringRef> Parts = {StringRef(), Name};
1233 while (true) {
1234 Parts = Parts.second.split(GlobalIdentifierDelimiter);
1235 if (Parts.first.starts_with("_Z"))
1236 return Parts.first;
1237 if (Parts.second.empty())
1238 return Name;
1239 }
1240 }
1241
1242 /// Given a mangled name extracted from a PGO function name, and a new
1243 /// form for that mangled name, reconstitute the name.
1244 static void reconstituteName(StringRef OrigName, StringRef ExtractedName,
1245 StringRef Replacement,
1246 SmallVectorImpl<char> &Out) {
1247 Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size());
1248 Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin());
1249 llvm::append_range(Out, Replacement);
1250 Out.insert(Out.end(), ExtractedName.end(), OrigName.end());
1251 }
1252
1254 if (Error E = Remappings.read(*RemapBuffer))
1255 return E;
1256 for (StringRef Name : Underlying.HashTable->keys()) {
1257 StringRef RealName = extractName(Name);
1258 if (auto Key = Remappings.insert(RealName)) {
1259 // FIXME: We could theoretically map the same equivalence class to
1260 // multiple names in the profile data. If that happens, we should
1261 // return NamedInstrProfRecords from all of them.
1262 MappedNames.insert({Key, RealName});
1263 }
1264 }
1265 return Error::success();
1266 }
1267
1270 StringRef RealName = extractName(FuncName);
1271 if (auto Key = Remappings.lookup(RealName)) {
1272 StringRef Remapped = MappedNames.lookup(Key);
1273 if (!Remapped.empty()) {
1274 if (RealName.begin() == FuncName.begin() &&
1275 RealName.end() == FuncName.end())
1276 FuncName = Remapped;
1277 else {
1278 // Try rebuilding the name from the given remapping.
1279 SmallString<256> Reconstituted;
1280 reconstituteName(FuncName, RealName, Remapped, Reconstituted);
1281 Error E = Underlying.getRecords(Reconstituted, Data);
1282 if (!E)
1283 return E;
1284
1285 // If we failed because the name doesn't exist, fall back to asking
1286 // about the original name.
1287 if (Error Unhandled = handleErrors(
1288 std::move(E), [](std::unique_ptr<InstrProfError> Err) {
1289 return Err->get() == instrprof_error::unknown_function
1290 ? Error::success()
1291 : Error(std::move(Err));
1292 }))
1293 return Unhandled;
1294 }
1295 }
1296 }
1297 return Underlying.getRecords(FuncName, Data);
1298 }
1299
1300private:
1301 /// The memory buffer containing the remapping configuration. Remappings
1302 /// holds pointers into this buffer.
1303 std::unique_ptr<MemoryBuffer> RemapBuffer;
1304
1305 /// The mangling remapper.
1306 SymbolRemappingReader Remappings;
1307
1308 /// Mapping from mangled name keys to the name used for the key in the
1309 /// profile data.
1310 /// FIXME: Can we store a location within the on-disk hash table instead of
1311 /// redoing lookup?
1313
1314 /// The real profile data reader.
1316};
1317
1319 using namespace support;
1320
1321 if (DataBuffer.getBufferSize() < 8)
1322 return false;
1323 uint64_t Magic = endian::read<uint64_t, aligned>(DataBuffer.getBufferStart(),
1325 // Verify that it's magical.
1326 return Magic == IndexedInstrProf::Magic;
1327}
1328
1329const unsigned char *
1330IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
1331 const unsigned char *Cur, bool UseCS) {
1332 using namespace IndexedInstrProf;
1333 using namespace support;
1334
1336 const IndexedInstrProf::Summary *SummaryInLE =
1337 reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
1338 uint64_t NFields = endian::byte_swap<uint64_t>(
1340 uint64_t NEntries = endian::byte_swap<uint64_t>(
1342 uint32_t SummarySize =
1343 IndexedInstrProf::Summary::getSize(NFields, NEntries);
1344 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
1345 IndexedInstrProf::allocSummary(SummarySize);
1346
1347 const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
1348 uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
1349 for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
1351
1352 SummaryEntryVector DetailedSummary;
1353 for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
1354 const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
1355 DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
1356 Ent.NumBlocks);
1357 }
1358 std::unique_ptr<llvm::ProfileSummary> &Summary =
1359 UseCS ? this->CS_Summary : this->Summary;
1360
1361 // initialize InstrProfSummary using the SummaryData from disk.
1362 Summary = std::make_unique<ProfileSummary>(
1364 DetailedSummary, SummaryData->get(Summary::TotalBlockCount),
1365 SummaryData->get(Summary::MaxBlockCount),
1366 SummaryData->get(Summary::MaxInternalBlockCount),
1367 SummaryData->get(Summary::MaxFunctionCount),
1368 SummaryData->get(Summary::TotalNumBlocks),
1369 SummaryData->get(Summary::TotalNumFunctions));
1370 return Cur + SummarySize;
1371 } else {
1372 // The older versions do not support a profile summary. This just computes
1373 // an empty summary, which will not result in accurate hot/cold detection.
1374 // We would need to call addRecord for all NamedInstrProfRecords to get the
1375 // correct summary. However, this version is old (prior to early 2016) and
1376 // has not been supporting an accurate summary for several years.
1377 InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1378 Summary = Builder.getSummary();
1379 return Cur;
1380 }
1381}
1382
1384 using namespace support;
1385
1386 const unsigned char *Start =
1387 (const unsigned char *)DataBuffer->getBufferStart();
1388 const unsigned char *Cur = Start;
1389 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
1391
1392 auto HeaderOr = IndexedInstrProf::Header::readFromBuffer(Start);
1393 if (!HeaderOr)
1394 return HeaderOr.takeError();
1395
1396 const IndexedInstrProf::Header *Header = &HeaderOr.get();
1397 Cur += Header->size();
1398
1399 Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,
1400 /* UseCS */ false);
1401 if (Header->Version & VARIANT_MASK_CSIR_PROF)
1402 Cur = readSummary((IndexedInstrProf::ProfVersion)Header->Version, Cur,
1403 /* UseCS */ true);
1404 // Read the hash type and start offset.
1405 IndexedInstrProf::HashT HashType =
1406 static_cast<IndexedInstrProf::HashT>(Header->HashType);
1407 if (HashType > IndexedInstrProf::HashT::Last)
1409
1410 // The hash table with profile counts comes next.
1411 auto IndexPtr = std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(
1412 Start + Header->HashOffset, Cur, Start, HashType, Header->Version);
1413
1414 // The MemProfOffset field in the header is only valid when the format
1415 // version is higher than 8 (when it was introduced).
1416 if (Header->getIndexedProfileVersion() >= 8 &&
1417 Header->Version & VARIANT_MASK_MEMPROF) {
1418 if (Error E = MemProfReader.deserialize(Start, Header->MemProfOffset))
1419 return E;
1420 }
1421
1422 // BinaryIdOffset field in the header is only valid when the format version
1423 // is higher than 9 (when it was introduced).
1424 if (Header->getIndexedProfileVersion() >= 9) {
1425 const unsigned char *Ptr = Start + Header->BinaryIdOffset;
1426 // Read binary ids size.
1427 uint64_t BinaryIdsSize =
1429 if (BinaryIdsSize % sizeof(uint64_t))
1430 return error(
1432 ("BinaryIdSize (" + Twine(BinaryIdsSize) + ") is not a multiple of 8")
1433 .str());
1434 // Set the binary ids start.
1435 BinaryIdsBuffer = ArrayRef<uint8_t>(Ptr, BinaryIdsSize);
1436 if (Ptr > (const unsigned char *)DataBuffer->getBufferEnd())
1438 "corrupted binary ids");
1439 }
1440
1441 if (Header->getIndexedProfileVersion() >= 12) {
1442 const unsigned char *Ptr = Start + Header->VTableNamesOffset;
1443
1444 uint64_t CompressedVTableNamesLen =
1446
1447 // Writer first writes the length of compressed string, and then the actual
1448 // content.
1449 const char *VTableNamePtr = (const char *)Ptr;
1450 if (VTableNamePtr > DataBuffer->getBufferEnd())
1452
1453 VTableName = StringRef(VTableNamePtr, CompressedVTableNamesLen);
1454 }
1455
1456 if (Header->getIndexedProfileVersion() >= 10 &&
1457 Header->Version & VARIANT_MASK_TEMPORAL_PROF) {
1458 const unsigned char *Ptr = Start + Header->TemporalProfTracesOffset;
1459 const auto *PtrEnd = (const unsigned char *)DataBuffer->getBufferEnd();
1460 // Expect at least two 64 bit fields: NumTraces, and TraceStreamSize
1461 if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)
1463 const uint64_t NumTraces =
1467 for (unsigned i = 0; i < NumTraces; i++) {
1468 // Expect at least two 64 bit fields: Weight and NumFunctions
1469 if (Ptr + 2 * sizeof(uint64_t) > PtrEnd)
1472 Trace.Weight =
1474 const uint64_t NumFunctions =
1476 // Expect at least NumFunctions 64 bit fields
1477 if (Ptr + NumFunctions * sizeof(uint64_t) > PtrEnd)
1479 for (unsigned j = 0; j < NumFunctions; j++) {
1480 const uint64_t NameRef =
1482 Trace.FunctionNameRefs.push_back(NameRef);
1483 }
1484 TemporalProfTraces.push_back(std::move(Trace));
1485 }
1486 }
1487
1488 // Load the remapping table now if requested.
1489 if (RemappingBuffer) {
1490 Remapper =
1491 std::make_unique<InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>(
1492 std::move(RemappingBuffer), *IndexPtr);
1493 if (Error E = Remapper->populateRemappings())
1494 return E;
1495 } else {
1496 Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);
1497 }
1498 Index = std::move(IndexPtr);
1499
1500 return success();
1501}
1502
1504 if (Symtab)
1505 return *Symtab;
1506
1507 auto NewSymtab = std::make_unique<InstrProfSymtab>();
1508
1509 if (Error E = NewSymtab->initVTableNamesFromCompressedStrings(VTableName)) {
1510 auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
1511 consumeError(error(ErrCode, Msg));
1512 }
1513
1514 // finalizeSymtab is called inside populateSymtab.
1515 if (Error E = Index->populateSymtab(*NewSymtab)) {
1516 auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
1517 consumeError(error(ErrCode, Msg));
1518 }
1519
1520 Symtab = std::move(NewSymtab);
1521 return *Symtab;
1522}
1523
1525 StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName,
1526 uint64_t *MismatchedFuncSum) {
1528 uint64_t FuncSum = 0;
1529 auto Err = Remapper->getRecords(FuncName, Data);
1530 if (Err) {
1531 // If we don't find FuncName, try DeprecatedFuncName to handle profiles
1532 // built by older compilers.
1533 auto Err2 =
1534 handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {
1535 if (IE.get() != instrprof_error::unknown_function)
1536 return make_error<InstrProfError>(IE);
1537 if (auto Err = Remapper->getRecords(DeprecatedFuncName, Data))
1538 return Err;
1539 return Error::success();
1540 });
1541 if (Err2)
1542 return std::move(Err2);
1543 }
1544 // Found it. Look for counters with the right hash.
1545
1546 // A flag to indicate if the records are from the same type
1547 // of profile (i.e cs vs nocs).
1548 bool CSBitMatch = false;
1549 auto getFuncSum = [](ArrayRef<uint64_t> Counts) {
1550 uint64_t ValueSum = 0;
1551 for (uint64_t CountValue : Counts) {
1552 if (CountValue == (uint64_t)-1)
1553 continue;
1554 // Handle overflow -- if that happens, return max.
1555 if (std::numeric_limits<uint64_t>::max() - CountValue <= ValueSum)
1556 return std::numeric_limits<uint64_t>::max();
1557 ValueSum += CountValue;
1558 }
1559 return ValueSum;
1560 };
1561
1562 for (const NamedInstrProfRecord &I : Data) {
1563 // Check for a match and fill the vector if there is one.
1564 if (I.Hash == FuncHash)
1565 return std::move(I);
1568 CSBitMatch = true;
1569 if (MismatchedFuncSum == nullptr)
1570 continue;
1571 FuncSum = std::max(FuncSum, getFuncSum(I.Counts));
1572 }
1573 }
1574 if (CSBitMatch) {
1575 if (MismatchedFuncSum != nullptr)
1576 *MismatchedFuncSum = FuncSum;
1578 }
1580}
1581
1583IndexedMemProfReader::getMemProfRecord(const uint64_t FuncNameHash) const {
1584 // TODO: Add memprof specific errors.
1585 if (MemProfRecordTable == nullptr)
1587 "no memprof data available in profile");
1588 auto Iter = MemProfRecordTable->find(FuncNameHash);
1589 if (Iter == MemProfRecordTable->end())
1592 "memprof record not found for function hash " + Twine(FuncNameHash));
1593
1594 const memprof::IndexedMemProfRecord &IndexedRecord = *Iter;
1595 switch (Version) {
1596 // Combine V3 and V4 cases as the record conversion logic is the same.
1597 case memprof::Version3:
1598 case memprof::Version4:
1599 assert(FrameBase && "FrameBase must be available");
1600 assert(CallStackBase && "CallStackBase must be available");
1601 {
1602 memprof::LinearFrameIdConverter FrameIdConv(FrameBase);
1603 memprof::LinearCallStackIdConverter CSIdConv(CallStackBase, FrameIdConv);
1604 memprof::MemProfRecord Record = IndexedRecord.toMemProfRecord(CSIdConv);
1605 return Record;
1606 }
1607 }
1608
1611 formatv("MemProf version {} not supported; "
1612 "requires version between {} and {}, inclusive",
1615}
1616
1619 assert(MemProfRecordTable);
1620 assert(Version == memprof::Version3 || Version == memprof::Version4);
1621
1622 memprof::LinearFrameIdConverter FrameIdConv(FrameBase);
1623 memprof::CallerCalleePairExtractor Extractor(CallStackBase, FrameIdConv,
1624 RadixTreeSize);
1625
1626 // The set of linear call stack IDs that we need to traverse from. We expect
1627 // the set to be dense, so we use a BitVector.
1628 BitVector Worklist(RadixTreeSize);
1629
1630 // Collect the set of linear call stack IDs. Since we expect a lot of
1631 // duplicates, we first collect them in the form of a bit vector before
1632 // processing them.
1633 for (const memprof::IndexedMemProfRecord &IndexedRecord :
1634 MemProfRecordTable->data()) {
1635 for (const memprof::IndexedAllocationInfo &IndexedAI :
1636 IndexedRecord.AllocSites)
1637 Worklist.set(IndexedAI.CSId);
1638 }
1639
1640 // Collect caller-callee pairs for each linear call stack ID in Worklist.
1641 for (unsigned CS : Worklist.set_bits())
1642 Extractor(CS);
1643
1645 std::move(Extractor.CallerCalleePairs);
1646
1647 // Sort each call list by the source location.
1648 for (auto &[CallerGUID, CallList] : Pairs) {
1649 llvm::sort(CallList);
1650 CallList.erase(llvm::unique(CallList), CallList.end());
1651 }
1652
1653 return Pairs;
1654}
1655
1657 memprof::AllMemProfData AllMemProfData;
1658 AllMemProfData.HeapProfileRecords.reserve(
1659 MemProfRecordTable->getNumEntries());
1660 for (uint64_t Key : MemProfRecordTable->keys()) {
1661 auto Record = getMemProfRecord(Key);
1662 if (Record.takeError())
1663 continue;
1665 Pair.GUID = Key;
1666 Pair.Record = std::move(*Record);
1667 AllMemProfData.HeapProfileRecords.push_back(std::move(Pair));
1668 }
1669 // Populate the data access profiles for yaml output.
1670 if (DataAccessProfileData != nullptr) {
1671 AllMemProfData.YamlifiedDataAccessProfiles.Records.reserve(
1672 DataAccessProfileData->getRecords().size());
1673 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdSymbols.reserve(
1674 DataAccessProfileData->getKnownColdSymbols().size());
1675 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdStrHashes.reserve(
1676 DataAccessProfileData->getKnownColdHashes().size());
1677 for (const auto &[SymHandleRef, RecordRef] :
1678 DataAccessProfileData->getRecords())
1679 AllMemProfData.YamlifiedDataAccessProfiles.Records.push_back(
1680 memprof::DataAccessProfRecord(SymHandleRef, RecordRef.AccessCount,
1681 RecordRef.Locations));
1682 for (StringRef ColdSymbol : DataAccessProfileData->getKnownColdSymbols())
1683 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdSymbols.push_back(
1684 ColdSymbol.str());
1685 for (uint64_t Hash : DataAccessProfileData->getKnownColdHashes())
1686 AllMemProfData.YamlifiedDataAccessProfiles.KnownColdStrHashes.push_back(
1687 Hash);
1691 return lhs.AccessCount > rhs.AccessCount;
1692 });
1695 [](const std::string &lhs, const std::string &rhs) {
1696 return lhs < rhs;
1697 });
1700 [](const uint64_t &lhs, const uint64_t &rhs) { return lhs < rhs; });
1701 }
1702 return AllMemProfData;
1703}
1704
1706 uint64_t FuncHash,
1707 std::vector<uint64_t> &Counts) {
1708 auto Record = getInstrProfRecord(FuncName, FuncHash);
1709 if (Error E = Record.takeError())
1710 return error(std::move(E));
1711
1712 Counts = Record.get().Counts;
1713 return success();
1714}
1715
1717 uint64_t FuncHash,
1718 BitVector &Bitmap) {
1719 auto Record = getInstrProfRecord(FuncName, FuncHash);
1720 if (Error E = Record.takeError())
1721 return error(std::move(E));
1722
1723 const auto &BitmapBytes = Record.get().BitmapBytes;
1724 size_t I = 0, E = BitmapBytes.size();
1725 Bitmap.resize(E * CHAR_BIT);
1727 [&](auto X) {
1728 using XTy = decltype(X);
1729 alignas(XTy) uint8_t W[sizeof(X)];
1730 size_t N = std::min(E - I, sizeof(W));
1731 std::memset(W, 0, sizeof(W));
1732 std::memcpy(W, &BitmapBytes[I], N);
1733 I += N;
1736 },
1737 Bitmap, Bitmap);
1738 assert(I == E);
1739
1740 return success();
1741}
1742
1745
1746 Error E = Index->getRecords(Data);
1747 if (E)
1748 return error(std::move(E));
1749
1750 Record = Data[RecordIndex++];
1751 if (RecordIndex >= Data.size()) {
1752 Index->advanceToNextKey();
1753 RecordIndex = 0;
1754 }
1755 return success();
1756}
1757
1759 std::vector<llvm::object::BuildID> &BinaryIds) {
1760 return readBinaryIdsInternal(*DataBuffer, BinaryIdsBuffer, BinaryIds,
1762}
1763
1765 std::vector<llvm::object::BuildID> BinaryIds;
1766 if (Error E = readBinaryIds(BinaryIds))
1767 return E;
1768 printBinaryIdsInternal(OS, BinaryIds);
1769 return Error::success();
1770}
1771
1773 uint64_t NumFuncs = 0;
1774 for (const auto &Func : *this) {
1775 if (isIRLevelProfile()) {
1776 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
1777 if (FuncIsCS != IsCS)
1778 continue;
1779 }
1780 Func.accumulateCounts(Sum);
1781 ++NumFuncs;
1782 }
1783 Sum.NumEntries = NumFuncs;
1784}
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:464
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:499
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Definition InstrProf.h:720
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition InstrProf.h:687
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:694
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:1358
uint64_t ComputeHash(StringRef K)
Definition InstrProf.h:1239
const uint64_t Magic
Definition InstrProf.h:1192
uint64_t getMagic()
const uint64_t Version
Definition InstrProf.h:1381
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
uint32_t read32(const void *P, endianness E)
Definition Endian.h:392
uint64_t read64(const void *P, endianness E)
Definition Endian.h:395
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:365
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:1282
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition InstrProf.h:1285
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition InstrProf.h:1284
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition InstrProf.h:1318
Profiling information for a single function.
Definition InstrProf.h:906
static bool hasCSFlagInHash(uint64_t FuncHash)
Definition InstrProf.h:1125
An ordered list of functions identified by their NameRef found in INSTR_PROF_DATA.
Definition InstrProf.h:423
This is the header of the data structure that defines the on-disk layout of the value profile data of...
Definition InstrProf.h:477
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