33 #include <system_error>
43 if (std::error_code EC = BufferOrErr.
getError())
45 return std::move(BufferOrErr.
get());
56 if (
Error E = BufferOrError.takeError())
67 if (Buffer->getBufferSize() == 0)
70 std::unique_ptr<InstrProfReader> Result;
87 return std::move(Result);
94 if (
Error E = BufferOrError.takeError())
108 auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
114 return std::move(Result);
117 void InstrProfIterator::Increment() {
132 [](
char c) { return ::isprint(c) || ::isspace(c); });
140 bool IsIRInstr =
false;
142 IsIRLevelProfile =
false;
154 IsIRLevelProfile = IsIRInstr;
161 #define CHECK_LINE_END(Line) \
162 if (Line.is_at_end()) \
163 return error(instrprof_error::truncated);
164 #define READ_NUM(Str, Dst) \
165 if ((Str).getAsInteger(10, (Dst))) \
166 return error(instrprof_error::malformed);
167 #define VP_READ_ADVANCE(Val) \
168 CHECK_LINE_END(Line); \
170 READ_NUM((*Line), (Val)); \
181 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
185 for (
uint32_t VK = 0; VK < NumValueKinds; VK++) {
194 for (
uint32_t S = 0; S < NumValueSites; S++) {
197 std::vector<InstrProfValueData> CurrentValues;
198 for (
uint32_t V = 0; V < NumValueData; V++) {
200 std::pair<StringRef, StringRef> VD = Line->
rsplit(
':');
201 uint64_t TakenCount,
Value;
202 if (
ValueKind == IPVK_IndirectCallTarget) {
210 CurrentValues.push_back({Value, TakenCount});
219 #undef CHECK_LINE_END
221 #undef VP_READ_ADVANCE
235 Record.
Name = *Line++;
242 if ((Line++)->getAsInteger(0, Record.
Hash))
246 uint64_t NumCounters;
249 if ((Line++)->getAsInteger(10, NumCounters))
251 if (NumCounters == 0)
256 Record.
Counts.reserve(NumCounters);
257 for (uint64_t
I = 0;
I < NumCounters; ++
I) {
261 if ((Line++)->getAsInteger(10, Count))
263 Record.
Counts.push_back(Count);
267 if (
Error E = readValueProfileData(Record))
276 template <
class IntPtrT>
282 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
286 template <
class IntPtrT>
288 if (!hasFormat(*DataBuffer))
293 DataBuffer->getBufferStart());
294 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
295 return readHeader(*Header);
298 template <
class IntPtrT>
300 const char *
End = DataBuffer->getBufferEnd();
302 while (CurrentPos != End && *CurrentPos == 0)
305 if (CurrentPos == End)
312 if (reinterpret_cast<size_t>(CurrentPos) %
alignof(uint64_t))
315 uint64_t
Magic = *
reinterpret_cast<const uint64_t *
>(CurrentPos);
316 if (Magic !=
swap(RawInstrProf::getMagic<IntPtrT>()))
321 return readHeader(*Header);
324 template <
class IntPtrT>
327 return error(std::move(
E));
329 const IntPtrT FPtr =
swap(
I->FunctionPointer);
338 template <
class IntPtrT>
345 CountersDelta =
swap(Header.CountersDelta);
346 NamesDelta =
swap(Header.NamesDelta);
347 auto DataSize =
swap(Header.DataSize);
348 auto CountersSize =
swap(Header.CountersSize);
349 NamesSize =
swap(Header.NamesSize);
350 ValueKindLast =
swap(Header.ValueKindLast);
353 auto PaddingSize = getNumPaddingBytes(NamesSize);
356 ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
357 ptrdiff_t NamesOffset = CountersOffset +
sizeof(uint64_t) * CountersSize;
358 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
360 auto *Start =
reinterpret_cast<const char *
>(&Header);
361 if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
366 DataEnd =
Data + DataSize;
367 CountersStart =
reinterpret_cast<const uint64_t *
>(Start + CountersOffset);
368 NamesStart = Start + NamesOffset;
369 ValueDataStart =
reinterpret_cast<const uint8_t *
>(Start + ValueDataOffset);
371 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
372 if (
Error E = createSymtab(*NewSymtab.get()))
375 Symtab = std::move(NewSymtab);
379 template <
class IntPtrT>
385 template <
class IntPtrT>
391 template <
class IntPtrT>
395 IntPtrT CounterPtr =
Data->CounterPtr;
396 if (NumCounters == 0)
399 auto RawCounts =
makeArrayRef(getCounter(CounterPtr), NumCounters);
400 auto *NamesStartAsCounter =
reinterpret_cast<const uint64_t *
>(NamesStart);
403 if (RawCounts.data() < CountersStart ||
404 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
407 if (ShouldSwapBytes) {
409 Record.
Counts.reserve(RawCounts.size());
410 for (uint64_t Count : RawCounts)
413 Record.
Counts = RawCounts;
418 template <
class IntPtrT>
422 CurValueDataSize = 0;
426 NumValueKinds += (
Data->NumValueSites[
I] != 0);
432 ValueProfData::getValueProfData(
433 ValueDataStart, (
const unsigned char *)DataBuffer->getBufferEnd(),
434 getDataEndianness());
443 CurValueDataSize = VDataPtrOrErr.
get()->getSize();
447 template <
class IntPtrT>
451 if (
Error E = readNextHeader(getNextHeaderPos()))
455 if (
Error E = readName(Record))
459 if (
Error E = readFuncHash(Record))
463 if (
Error E = readRawCounts(Record))
467 if (
Error E = readValueProfilingData(Record))
491 const unsigned char *&
D,
const unsigned char *
const End) {
493 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
498 VDataPtrOrErr.
get()->deserializeTo(DataBuffer.back(),
nullptr);
499 D += VDataPtrOrErr.
get()->TotalSize;
506 using namespace support;
509 if (N %
sizeof(uint64_t))
513 std::vector<uint64_t> CounterBuffer;
515 const unsigned char *End = D +
N;
518 if (D +
sizeof(uint64_t) >= End)
520 uint64_t
Hash = endian::readNext<uint64_t, little, unaligned>(
D);
523 uint64_t CountsSize = N /
sizeof(uint64_t) - 1;
526 if (D +
sizeof(uint64_t) >
End)
528 CountsSize = endian::readNext<uint64_t, little, unaligned>(
D);
531 if (D + CountsSize *
sizeof(uint64_t) >
End)
534 CounterBuffer.clear();
535 CounterBuffer.reserve(CountsSize);
536 for (uint64_t J = 0; J < CountsSize; ++J)
537 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
539 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
551 template <
typename HashTableImpl>
554 auto Iter = HashTable->find(FuncName);
555 if (Iter == HashTable->end())
565 template <
typename HashTableImpl>
571 Data = *RecordIterator;
579 template <
typename HashTableImpl>
581 const unsigned char *Buckets,
const unsigned char *
const Payload,
585 HashTable.reset(HashTableImpl::Create(
586 Buckets, Payload, Base,
587 typename HashTableImpl::InfoType(HashType, Version)));
588 RecordIterator = HashTable->data_begin();
592 using namespace support;
597 endian::read<uint64_t, little, aligned>(DataBuffer.
getBufferStart());
602 const unsigned char *
604 const unsigned char *Cur) {
605 using namespace IndexedInstrProf;
606 using namespace support;
617 std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
620 const uint64_t *Src =
reinterpret_cast<const uint64_t *
>(SummaryInLE);
621 uint64_t *Dst =
reinterpret_cast<uint64_t *
>(SummaryData.get());
622 for (
unsigned I = 0;
I < SummarySize /
sizeof(uint64_t);
I++)
623 Dst[
I] = endian::byte_swap<uint64_t, little>(Src[
I]);
626 for (
unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
632 this->Summary = llvm::make_unique<ProfileSummary>(
634 SummaryData->get(Summary::TotalBlockCount),
635 SummaryData->get(Summary::MaxBlockCount),
636 SummaryData->get(Summary::MaxInternalBlockCount),
637 SummaryData->get(Summary::MaxFunctionCount),
638 SummaryData->get(Summary::TotalNumBlocks),
639 SummaryData->get(Summary::TotalNumFunctions));
640 return Cur + SummarySize;
643 using namespace IndexedInstrProf;
648 this->Summary = Builder.getSummary();
654 using namespace support;
656 const unsigned char *Start =
657 (
const unsigned char *)DataBuffer->getBufferStart();
658 const unsigned char *Cur = Start;
659 if ((
const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
666 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
671 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
672 if (GET_VERSION(FormatVersion) >
680 endian::byte_swap<uint64_t, little>(Header->HashType));
684 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
689 Start + HashOffset, Cur, Start, HashType, FormatVersion);
690 Index.reset(IndexPtr);
696 return *Symtab.get();
698 std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
699 if (
Error E = Index->populateSymtab(*NewSymtab.get())) {
703 Symtab = std::move(NewSymtab);
704 return *Symtab.get();
711 Error Err = Index->getRecords(FuncName, Data);
713 return std::move(Err);
715 for (
unsigned I = 0,
E = Data.
size(); I <
E; ++
I) {
717 if (Data[I].
Hash == FuncHash) {
718 return std::move(Data[I]);
726 std::vector<uint64_t> &Counts) {
729 return error(std::move(
E));
731 Counts = Record.
get().Counts;
736 static unsigned RecordIndex = 0;
740 Error E = Index->getRecords(Data);
742 return error(std::move(E));
744 Record = Data[RecordIndex++];
745 if (RecordIndex >= Data.
size()) {
746 Index->advanceToNextKey();
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
#define VP_READ_ADVANCE(Val)
std::error_code getError() const
Represents either an error or a value T.
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Error readHeader() override
Read the header. Required before reading first record.
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
uint64_t NumCutoffEntries
const char * getBufferStart() const
uint64_t MinBlockCount
The minimum execution count for this percentile.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static bool hasFormat(const MemoryBuffer &DataBuffer)
Return true if the given buffer is in an indexed instrprof format.
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
LLVM_NODISCARD bool equals_lower(StringRef RHS) const
equals_lower - Check for string equality, ignoring case.
Error error(instrprof_error Err)
Set the current error and return same.
AddrHashMap & getAddrHashMap()
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
static const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
InstrProfSymtab & getSymtab() override
Return the PGO symtab.
Error takeError()
Take ownership of the stored error.
InstrProfLookupTrait::offset_type offset_type
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Error readHeader() override
Read the header.
data_type ReadData(StringRef K, const unsigned char *D, offset_type N)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path)
Factory method to create an appropriately typed reader for the given instrprof file.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
static StringRef getName(Value *V)
Tagged union holding either a T or a Error.
uint64_t NumSummaryFields
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if the given buffer is in text instrprof format.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Reader for the simple text based instrprof format.
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
size_t size() const
size - Get the array size.
static bool hasFormat(const MemoryBuffer &DataBuffer)
hash_value_type ComputeHash(StringRef K)
ArrayRef< NamedInstrProfRecord > data_type
Base class and interface for reading profiling data of any known instrprof format.
uint64_t Cutoff
The required percentile of total execution count.
bool is_at_end() const
Return true if we're an "end" iterator or have reached EOF.
LLVM_NODISCARD std::pair< StringRef, StringRef > rsplit(char Separator) const
Split into two substrings around the last occurrence of a separator character.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
bool readValueProfilingData(const unsigned char *&D, const unsigned char *const End)
std::unique_ptr< InstrProfSymtab > Symtab
static const unsigned End
bool empty() const
empty - Check if the array is empty.
uint64_t ComputeHash(StringRef K)
Error getRecords(ArrayRef< NamedInstrProfRecord > &Data) override
void consumeError(Error Err)
Consume a Error without doing anything.
#define CHECK_LINE_END(Line)
#define READ_NUM(Str, Dst)
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, ValueMapType *ValueMap)
Add ValueData for ValueKind at value Site.
void clearValueData()
Clear value data entries.
static const char *const Magic
static Expected< std::unique_ptr< MemoryBuffer > > setupMemoryBuffer(const Twine &Path)
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
static ErrorSuccess success()
Create a success value.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
RawInstrProfReader< uint32_t > RawInstrProfReader32
Reader for the raw instrprof binary format from runtime.
reference get()
Returns a reference to the stored T value.
RawInstrProfReader< uint64_t > RawInstrProfReader64
This interface provides simple read-only access to a block of memory, and provides simple methods for...
InstrProfReaderIndex(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, IndexedInstrProf::HashT HashType, uint64_t Version)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Error readNextRecord(NamedInstrProfRecord &Record) override
Read a single record.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
unsigned char getSwappedBytes(unsigned char C)
size_t getBufferSize() const
success
Parameters (see the expansion example below): (the builder, addr, loaded, new_val, ordering, /* OUT.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
std::vector< uint64_t > Counts
Error readHeader() override
Read the file header.
virtual Error readHeader()=0
Read the header. Required before reading first record.
Profiling information for a single function.
Expected< InstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
virtual Error readNextRecord(NamedInstrProfRecord &Record)=0
Read a single record.
Provides ErrorOr<T> smart pointer.
LLVM Value Representation.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
Lightweight error class with error context and mandatory checking.
std::string Hash(const Unit &U)
StringRef - Represent a constant reference to a string, i.e.
Reader for the indexed binary instrprof format.
std::vector< ProfileSummaryEntry > SummaryEntryVector
InstrProfIterator()=default
void Clear()
Clear value data entries and edge counters.
Error success()
Clear the current error and return a successful one.
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
static Error initializeReader(InstrProfReader &Reader)