46 using namespace coverage;
47 using namespace object;
49 #define DEBUG_TYPE "coverage-mapping"
51 void CoverageMappingIterator::increment() {
54 if (
auto E = Reader->readNextRecord(
Record)) {
78 if (Result >= MaxPlus1)
87 if (Result >
Data.size())
94 if (
auto Err = readSize(Length))
96 Result =
Data.substr(0, Length);
102 uint64_t NumFilenames;
103 if (
auto Err = readSize(NumFilenames))
105 for (
size_t I = 0;
I < NumFilenames; ++
I) {
109 Filenames.push_back(Filename);
143 Error RawCoverageMappingReader::readCounter(
Counter &C) {
144 uint64_t EncodedCounter;
148 if (
auto Err = decodeCounter(EncodedCounter, C))
159 Error RawCoverageMappingReader::readMappingRegionsSubArray(
160 std::vector<CounterMappingRegion> &MappingRegions,
unsigned InferredFileID,
163 if (
auto Err = readSize(NumRegions))
165 unsigned LineStart = 0;
166 for (
size_t I = 0;
I < NumRegions; ++
I) {
171 uint64_t EncodedCounterAndRegion;
172 if (
auto Err = readIntMax(EncodedCounterAndRegion,
176 uint64_t ExpandedFileID = 0;
178 if (
auto Err = decodeCounter(EncodedCounterAndRegion, C))
184 ExpandedFileID = EncodedCounterAndRegion >>
186 if (ExpandedFileID >= NumFileIDs)
189 switch (EncodedCounterAndRegion >>
204 uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
216 LineStart += LineStartDelta;
225 if (ColumnStart == 0 && ColumnEnd == 0) {
231 dbgs() <<
"Counter in file " << InferredFileID <<
" " << LineStart <<
":"
232 << ColumnStart <<
" -> " << (LineStart + NumLines) <<
":"
233 << ColumnEnd <<
", ";
235 dbgs() <<
"Expands to file " << ExpandedFileID;
242 C, InferredFileID, ExpandedFileID, LineStart, ColumnStart,
243 LineStart + NumLines, ColumnEnd, Kind));
251 uint64_t NumFileMappings;
252 if (
auto Err = readSize(NumFileMappings))
254 for (
size_t I = 0;
I < NumFileMappings; ++
I) {
255 uint64_t FilenameIndex;
256 if (
auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
258 VirtualFileMapping.
push_back(FilenameIndex);
262 for (
auto I : VirtualFileMapping) {
263 Filenames.push_back(TranslationUnitFilenames[
I]);
267 uint64_t NumExpressions;
268 if (
auto Err = readSize(NumExpressions))
276 for (
size_t I = 0;
I < NumExpressions; ++
I) {
284 for (
unsigned InferredFileID = 0, S = VirtualFileMapping.size();
285 InferredFileID < S; ++InferredFileID) {
286 if (
auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
287 VirtualFileMapping.size()))
297 FileIDExpansionRegionMapping.
resize(VirtualFileMapping.size(),
nullptr);
298 for (
unsigned Pass = 1, S = VirtualFileMapping.size();
Pass < S; ++
Pass) {
299 for (
auto &R : MappingRegions) {
302 assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
303 FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
305 for (
auto &R : MappingRegions) {
306 if (FileIDExpansionRegionMapping[R.FileID]) {
307 FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
308 FileIDExpansionRegionMapping[R.FileID] =
nullptr;
318 uint64_t NumFileMappings;
319 if (
Error Err = readSize(NumFileMappings))
320 return std::move(Err);
321 if (NumFileMappings != 1)
324 uint64_t FilenameIndex;
327 return std::move(Err);
328 uint64_t NumExpressions;
329 if (
Error Err = readSize(NumExpressions))
330 return std::move(Err);
331 if (NumExpressions != 0)
334 if (
Error Err = readSize(NumRegions))
335 return std::move(Err);
338 uint64_t EncodedCounterAndRegion;
339 if (
Error Err = readIntMax(EncodedCounterAndRegion,
341 return std::move(Err);
347 if (
auto EC = Section.getContents(Data))
349 Address = Section.getAddress();
359 return Data.substr(Pointer - Address, Size);
372 struct CovMapFuncRecordReader {
373 virtual ~CovMapFuncRecordReader() =
default;
383 const char *
End) = 0;
385 template <
class IntPtrT, support::endianness Endian>
388 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
389 std::vector<StringRef> &
F);
393 template <CovMapVersion Version,
class IntPtrT, support::endianness Endian>
394 class VersionedCovMapFuncRecordReader :
public CovMapFuncRecordReader {
395 using FuncRecordType =
403 std::vector<StringRef> &Filenames;
404 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
412 Error insertFunctionRecordIfNeeded(
const FuncRecordType *CFR,
413 StringRef Mapping,
size_t FilenamesBegin) {
414 uint64_t FuncHash = CFR->template getFuncHash<Endian>();
415 NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
417 FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
418 if (InsertResult.second) {
420 if (
Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
422 if (FuncName.
empty())
424 Records.emplace_back(
Version, FuncName, FuncHash, Mapping, FilenamesBegin,
425 Filenames.
size() - FilenamesBegin);
429 size_t OldRecordIndex = InsertResult.first->second;
431 Records[OldRecordIndex];
436 if (!*OldIsDummyExpected)
442 if (*NewIsDummyExpected)
452 VersionedCovMapFuncRecordReader(
454 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
455 std::vector<StringRef> &
F)
456 : ProfileNames(P), Filenames(F), Records(R) {}
458 ~VersionedCovMapFuncRecordReader()
override =
default;
461 const char *
End)
override {
462 using namespace support;
466 auto CovHeader =
reinterpret_cast<const CovMapHeader *
>(Buf);
467 uint32_t NRecords = CovHeader->getNRecords<Endian>();
468 uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
469 uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
471 Buf =
reinterpret_cast<const char *
>(CovHeader + 1);
474 const char *FunBuf = Buf;
475 Buf += NRecords *
sizeof(FuncRecordType);
476 const char *FunEnd = Buf;
479 if (Buf + FilenamesSize > End)
481 size_t FilenamesBegin = Filenames.size();
483 if (
auto Err = Reader.read())
484 return std::move(Err);
485 Buf += FilenamesSize;
488 const char *CovBuf = Buf;
490 const char *CovEnd = Buf;
498 auto CFR =
reinterpret_cast<const FuncRecordType *
>(FunBuf);
499 while ((
const char *)CFR < FunEnd) {
501 uint32_t DataSize = CFR->template getDataSize<Endian>();
504 if (CovBuf + DataSize > CovEnd)
506 auto Mapping =
StringRef(CovBuf, DataSize);
510 insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
511 return std::move(Err);
520 template <
class IntPtrT, support::endianness Endian>
523 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
524 std::vector<StringRef> &
F) {
525 using namespace coverage;
533 if (
Error E = P.create(P.getNameData()))
541 template <
typename T, support::endianness Endian>
544 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
545 std::vector<StringRef> &Filenames) {
546 using namespace coverage;
555 CovMapFuncRecordReader::get<T, Endian>(
Version, ProfileNames, Records,
557 if (
Error E = ReaderExpected.takeError())
559 auto Reader = std::move(ReaderExpected.get());
560 for (
const char *Buf = Data.
data(), *End = Buf + Data.
size(); Buf <
End;) {
561 auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
562 if (
auto E = NextHeaderOrErr.takeError())
564 Buf = NextHeaderOrErr.get();
573 uint8_t &BytesInAddress,
582 auto ProfileNamesSize =
595 if (Data.
size() < ProfileNamesSize)
599 CoverageMapping = Data.
substr(ProfileNamesSize);
601 if (CoverageMapping.
empty())
604 if (CoverageMapping.
size() < Pad)
606 CoverageMapping = CoverageMapping.
substr(Pad);
612 for (
const auto &Section : OF.sections()) {
613 if (
auto EC = Section.getName(FoundName))
615 if (FoundName == Name)
624 uint8_t &BytesInAddress,
628 return BinOrErr.takeError();
629 auto Bin = std::move(BinOrErr.get());
630 std::unique_ptr<ObjectFile> OF;
631 if (
auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
634 auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
635 if (!ObjectFileOrErr)
636 return ObjectFileOrErr.takeError();
637 OF = std::move(ObjectFileOrErr.get());
638 }
else if (isa<ObjectFile>(Bin.get())) {
640 OF.reset(cast<ObjectFile>(Bin.release()));
649 BytesInAddress = OF->getBytesInAddress();
654 auto ObjFormat = OF->getTripleObjectFormat();
658 if (
auto E = NamesSection.takeError())
660 auto CoverageSection =
663 if (
auto E = CoverageSection.takeError())
667 if (
auto EC = CoverageSection->getContents(CoverageMapping))
681 uint8_t BytesInAddress;
685 if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
688 Coverage, BytesInAddress, Endian);
691 Coverage, BytesInAddress, Endian, Arch);
696 E = readCoverageMappingData<uint32_t, support::endianness::little>(
697 Reader->ProfileNames, Coverage, Reader->MappingRecords,
700 E = readCoverageMappingData<uint32_t, support::endianness::big>(
701 Reader->ProfileNames, Coverage, Reader->MappingRecords,
704 E = readCoverageMappingData<uint64_t, support::endianness::little>(
705 Reader->ProfileNames, Coverage, Reader->MappingRecords,
708 E = readCoverageMappingData<uint64_t, support::endianness::big>(
709 Reader->ProfileNames, Coverage, Reader->MappingRecords,
715 return std::move(Reader);
719 if (CurrentRecord >= MappingRecords.size())
722 FunctionsFilenames.clear();
724 MappingRegions.clear();
725 auto &R = MappingRecords[CurrentRecord];
728 makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
730 if (
auto Err = Reader.
read())
Pass interface - Implemented by all 'passes'.
void push_back(const T &Elt)
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static const unsigned EncodingTagMask
Reader for the raw coverage mapping data.
static Counter getZero()
Return the counter that represents the number zero.
coveragemap_error get() const
Checks if the given coverage mapping data is exported for an unused function.
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
A Counter expression is a value that represents an arithmetic operation with two counters.
Error takeError()
Take ownership of the stored error.
ArrayRef< CounterMappingRegion > MappingRegions
static StringRef readString(const uint8_t *&Ptr)
gvn Early GVN Hoisting of Expressions
Error readSize(uint64_t &Result)
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr)
Create a Binary from Source, autodetecting the file type.
Reader for the coverage mapping data that is emitted by the frontend and stored in an object file...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
ArrayRef< CounterExpression > Expressions
Tagged union holding either a T or a Error.
StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize)
Return function's PGO name from the function name's symbol address in the object file.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
StringRef CoverageMapping
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Error readIntMax(uint64_t &Result, uint64_t MaxPlus1)
Error readNextRecord(CoverageMappingRecord &Record) override
ArrayRef< StringRef > Filenames
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Coverage mapping information for a single function.
void dump(const Counter &C, raw_ostream &OS) const
static Error readCoverageMappingData(InstrProfSymtab &ProfileNames, StringRef Data, std::vector< BinaryCoverageReader::ProfileMappingRecord > &Records, std::vector< StringRef > &Filenames)
size_t alignmentAdjustment(const void *Ptr, size_t Alignment)
Returns the necessary adjustment for aligning Ptr to Alignment bytes, rounding up.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Reader for the raw coverage filenames.
Error readULEB128(uint64_t &Result)
A CodeRegion associates some code with a counter.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
A Counter mapping region associates a source range with a specific counter.
Expected< bool > isDummy()
Error readString(StringRef &Result)
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
static const unsigned End
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
void consumeError(Error Err)
Consume a Error without doing anything.
Triple - Helper class for working with autoconf configuration names.
A file format agnostic iterator over coverage mapping data.
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
print lazy value Lazy Value Info Printer Pass
static ErrorSuccess success()
Create a success value.
static uint64_t readULEB128(const uint8_t *&Ptr)
static Expected< SectionRef > lookupSection(ObjectFile &OF, StringRef Name)
static const unsigned EncodingExpansionRegionBit
static Error loadBinaryFormat(MemoryBufferRef ObjectBuffer, InstrProfSymtab &ProfileNames, StringRef &CoverageMapping, uint8_t &BytesInAddress, support::endianness &Endian, StringRef Arch)
static const char * TestingFormatMagic
static Expected< std::unique_ptr< BinaryCoverageReader > > create(std::unique_ptr< MemoryBuffer > &ObjectBuffer, StringRef Arch)
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static const unsigned EncodingCounterTagAndExpansionRegionTagBits
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
The mapping of profile information to coverage data.
static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames, StringRef &CoverageMapping, uint8_t &BytesInAddress, support::endianness &Endian)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const unsigned EncodingTagBits
static Expected< bool > isCoverageMappingDummy(uint64_t Hash, StringRef Mapping)
LLVM Value Representation.
Lightweight error class with error context and mandatory checking.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
std::string Hash(const Unit &U)
StringRef - Represent a constant reference to a string, i.e.
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.