38 using namespace coverage;
41 #define DEBUG_TYPE "coverage-mapping" 43 void CoverageMappingIterator::increment() {
49 if (
auto E = Reader->readNextRecord(
Record))
72 if (Result >= MaxPlus1)
81 if (Result >
Data.size())
88 if (
auto Err = readSize(Length))
90 Result =
Data.substr(0, Length);
96 uint64_t NumFilenames;
97 if (
auto Err = readSize(NumFilenames))
99 for (
size_t I = 0;
I < NumFilenames; ++
I) {
103 Filenames.push_back(Filename);
137 Error RawCoverageMappingReader::readCounter(
Counter &C) {
138 uint64_t EncodedCounter;
142 if (
auto Err = decodeCounter(EncodedCounter, C))
153 Error RawCoverageMappingReader::readMappingRegionsSubArray(
154 std::vector<CounterMappingRegion> &MappingRegions,
unsigned InferredFileID,
157 if (
auto Err = readSize(NumRegions))
159 unsigned LineStart = 0;
160 for (
size_t I = 0;
I < NumRegions; ++
I) {
165 uint64_t EncodedCounterAndRegion;
166 if (
auto Err = readIntMax(EncodedCounterAndRegion,
170 uint64_t ExpandedFileID = 0;
172 if (
auto Err = decodeCounter(EncodedCounterAndRegion, C))
176 if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
178 ExpandedFileID = EncodedCounterAndRegion >>
180 if (ExpandedFileID >= NumFileIDs)
183 switch (EncodedCounterAndRegion >>
198 uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
210 LineStart += LineStartDelta;
213 if (ColumnEnd & (1U << 31)) {
215 ColumnEnd &= ~(1U << 31);
226 if (ColumnStart == 0 && ColumnEnd == 0) {
232 dbgs() <<
"Counter in file " << InferredFileID <<
" " << LineStart <<
":" 233 << ColumnStart <<
" -> " << (LineStart + NumLines) <<
":" 234 << ColumnEnd <<
", ";
236 dbgs() <<
"Expands to file " << ExpandedFileID;
243 LineStart, ColumnStart,
244 LineStart + NumLines, ColumnEnd, Kind);
245 if (CMR.startLoc() > CMR.endLoc())
247 MappingRegions.push_back(CMR);
255 uint64_t NumFileMappings;
256 if (
auto Err = readSize(NumFileMappings))
258 for (
size_t I = 0;
I < NumFileMappings; ++
I) {
259 uint64_t FilenameIndex;
260 if (
auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
262 VirtualFileMapping.
push_back(FilenameIndex);
266 for (
auto I : VirtualFileMapping) {
267 Filenames.push_back(TranslationUnitFilenames[
I]);
271 uint64_t NumExpressions;
272 if (
auto Err = readSize(NumExpressions))
280 for (
size_t I = 0;
I < NumExpressions; ++
I) {
288 for (
unsigned InferredFileID = 0, S = VirtualFileMapping.size();
289 InferredFileID < S; ++InferredFileID) {
290 if (
auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
291 VirtualFileMapping.size()))
301 FileIDExpansionRegionMapping.
resize(VirtualFileMapping.size(),
nullptr);
302 for (
unsigned Pass = 1, S = VirtualFileMapping.size();
Pass < S; ++
Pass) {
303 for (
auto &R : MappingRegions) {
306 assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
307 FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
309 for (
auto &R : MappingRegions) {
310 if (FileIDExpansionRegionMapping[R.FileID]) {
311 FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
312 FileIDExpansionRegionMapping[R.FileID] =
nullptr;
322 uint64_t NumFileMappings;
323 if (
Error Err = readSize(NumFileMappings))
324 return std::move(Err);
325 if (NumFileMappings != 1)
328 uint64_t FilenameIndex;
331 return std::move(Err);
332 uint64_t NumExpressions;
333 if (
Error Err = readSize(NumExpressions))
334 return std::move(Err);
335 if (NumExpressions != 0)
338 if (
Error Err = readSize(NumRegions))
339 return std::move(Err);
342 uint64_t EncodedCounterAndRegion;
343 if (
Error Err = readIntMax(EncodedCounterAndRegion,
345 return std::move(Err);
355 Address = Section.getAddress();
359 const ObjectFile *Obj = Section.getObject();
360 if (isa<COFFObjectFile>(Obj) && !Obj->isRelocatableObject())
372 return Data.substr(Pointer - Address, Size);
385 struct CovMapFuncRecordReader {
386 virtual ~CovMapFuncRecordReader() =
default;
396 const char *End) = 0;
398 template <
class IntPtrT, support::endianness Endian>
401 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
402 std::vector<StringRef> &
F);
406 template <CovMapVersion Version,
class IntPtrT, support::endianness Endian>
407 class VersionedCovMapFuncRecordReader :
public CovMapFuncRecordReader {
408 using FuncRecordType =
416 std::vector<StringRef> &Filenames;
417 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
425 Error insertFunctionRecordIfNeeded(
const FuncRecordType *CFR,
426 StringRef Mapping,
size_t FilenamesBegin) {
427 uint64_t FuncHash = CFR->template getFuncHash<Endian>();
428 NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
430 FunctionRecords.
insert(std::make_pair(NameRef, Records.size()));
431 if (InsertResult.second) {
433 if (
Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
435 if (FuncName.
empty())
437 Records.emplace_back(
Version, FuncName, FuncHash, Mapping, FilenamesBegin,
438 Filenames.
size() - FilenamesBegin);
442 size_t OldRecordIndex = InsertResult.first->second;
444 Records[OldRecordIndex];
449 if (!*OldIsDummyExpected)
455 if (*NewIsDummyExpected)
465 VersionedCovMapFuncRecordReader(
467 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
468 std::vector<StringRef> &
F)
469 : ProfileNames(P), Filenames(F), Records(R) {}
471 ~VersionedCovMapFuncRecordReader()
override =
default;
474 const char *End)
override {
475 using namespace support;
479 auto CovHeader =
reinterpret_cast<const CovMapHeader *
>(Buf);
480 uint32_t NRecords = CovHeader->getNRecords<Endian>();
481 uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
482 uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
484 Buf =
reinterpret_cast<const char *
>(CovHeader + 1);
487 const char *FunBuf = Buf;
488 Buf += NRecords *
sizeof(FuncRecordType);
489 const char *FunEnd = Buf;
492 if (Buf + FilenamesSize > End)
494 size_t FilenamesBegin = Filenames.size();
496 if (
auto Err = Reader.
read())
497 return std::move(Err);
498 Buf += FilenamesSize;
501 const char *CovBuf = Buf;
503 const char *CovEnd = Buf;
511 auto CFR =
reinterpret_cast<const FuncRecordType *
>(FunBuf);
512 while ((
const char *)CFR < FunEnd) {
514 uint32_t DataSize = CFR->template getDataSize<Endian>();
517 if (CovBuf + DataSize > CovEnd)
519 auto Mapping =
StringRef(CovBuf, DataSize);
523 insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
524 return std::move(Err);
533 template <
class IntPtrT, support::endianness Endian>
536 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
537 std::vector<StringRef> &
F) {
538 using namespace coverage;
542 return std::make_unique<VersionedCovMapFuncRecordReader<
547 if (
Error E = P.create(P.getNameData()))
550 return std::make_unique<VersionedCovMapFuncRecordReader<
553 return std::make_unique<VersionedCovMapFuncRecordReader<
559 template <
typename T, support::endianness Endian>
562 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
563 std::vector<StringRef> &Filenames) {
564 using namespace coverage;
573 CovMapFuncRecordReader::get<T, Endian>(
Version, ProfileNames, Records,
575 if (
Error E = ReaderExpected.takeError())
577 auto Reader = std::move(ReaderExpected.get());
578 for (
const char *Buf = Data.
data(), *End = Buf + Data.
size(); Buf < End;) {
579 auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
580 if (
auto E = NextHeaderOrErr.takeError())
582 Buf = NextHeaderOrErr.get();
594 Reader->ProfileNames = std::move(ProfileNames);
597 readCoverageMappingData<uint32_t, support::endianness::little>(
598 Reader->ProfileNames, Coverage, Reader->MappingRecords,
602 if (
Error E = readCoverageMappingData<uint32_t, support::endianness::big>(
603 Reader->ProfileNames, Coverage, Reader->MappingRecords,
608 readCoverageMappingData<uint64_t, support::endianness::little>(
609 Reader->ProfileNames, Coverage, Reader->MappingRecords,
613 if (
Error E = readCoverageMappingData<uint64_t, support::endianness::big>(
614 Reader->ProfileNames, Coverage, Reader->MappingRecords,
619 return std::move(Reader);
624 uint8_t BytesInAddress = 8;
642 if (Data.
size() < ProfileNamesSize)
649 if (CoverageMapping.
empty())
652 if (CoverageMapping.
size() < Pad)
654 CoverageMapping = CoverageMapping.
substr(Pad);
656 CoverageMapping, std::move(ProfileNames), BytesInAddress, Endian);
663 bool IsCOFF = isa<COFFObjectFile>(OF);
665 return IsCOFF ?
N.split(
'$').first :
N;
667 Name = stripSuffix(Name);
669 for (
const auto &
Section : OF.sections()) {
673 if (stripSuffix(*NameOrErr) == Name)
681 std::unique_ptr<ObjectFile> OF;
682 if (
auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
685 auto ObjectFileOrErr = Universal->getMachOObjectForArch(Arch);
686 if (!ObjectFileOrErr)
687 return ObjectFileOrErr.takeError();
688 OF = std::move(ObjectFileOrErr.get());
689 }
else if (isa<ObjectFile>(Bin.get())) {
691 OF.reset(cast<ObjectFile>(Bin.release()));
700 uint8_t BytesInAddress = OF->getBytesInAddress();
706 auto ObjFormat = OF->getTripleObjectFormat();
710 if (
auto E = NamesSection.takeError())
712 auto CoverageSection =
715 if (
auto E = CoverageSection.takeError())
719 auto CoverageMappingOrErr = CoverageSection->getContents();
720 if (!CoverageMappingOrErr)
721 return CoverageMappingOrErr.takeError();
728 CoverageMappingOrErr.get(), std::move(ProfileNames), BytesInAddress,
736 std::vector<std::unique_ptr<BinaryCoverageReader>> Readers;
742 return ReaderOrErr.takeError();
743 Readers.push_back(std::move(ReaderOrErr.get()));
744 return std::move(Readers);
749 return BinOrErr.takeError();
750 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
754 if (
auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
755 for (
auto &ObjForArch : Universal->objects()) {
757 std::string ObjArch = ObjForArch.getArchFlagName();
761 auto ArchiveOrErr = ObjForArch.getAsArchive();
769 ArchiveOrErr.get()->getMemoryBufferRef(), Arch, ObjectFileBuffers);
774 if (
auto *Ar = dyn_cast<Archive>(Bin.get())) {
776 for (
auto &Child : Ar->children(Err)) {
782 ChildBufOrErr.
get(), Arch, ObjectFileBuffers);
783 if (!ChildReadersOrErr)
784 return ChildReadersOrErr.takeError();
785 for (
auto &Reader : ChildReadersOrErr.get())
786 Readers.push_back(std::move(Reader));
789 return std::move(Err);
795 for (
auto &Buffer : Ar->takeThinBuffers())
796 ObjectFileBuffers.push_back(std::move(Buffer));
798 return std::move(Readers);
803 return ReaderOrErr.takeError();
804 Readers.push_back(std::move(ReaderOrErr.get()));
805 return std::move(Readers);
809 if (CurrentRecord >= MappingRecords.size())
812 FunctionsFilenames.clear();
814 MappingRegions.clear();
815 auto &R = MappingRecords[CurrentRecord];
818 makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
820 if (
auto Err = Reader.
read())
Pass interface - Implemented by all 'passes'.
static Expected< std::vector< std::unique_ptr< BinaryCoverageReader > > > create(MemoryBufferRef ObjectBuffer, StringRef Arch, SmallVectorImpl< std::unique_ptr< MemoryBuffer >> &ObjectFileBuffers)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
static const unsigned EncodingTagMask
Reader for the raw coverage mapping data.
This class represents lattice values for constants.
static Counter getZero()
Return the counter that represents the number zero.
uint64_t offsetToAlignedAddr(const void *Addr, Align Alignment)
Returns the necessary adjustment for aligning Addr to Alignment bytes, rounding up.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
void push_back(const T &Elt)
Checks if the given coverage mapping data is exported for an unused function.
static Expected< std::unique_ptr< BinaryCoverageReader > > loadTestingFormat(StringRef Data)
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
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.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
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
StringRef getBuffer() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Tagged union holding either a T or a Error.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx)
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.
void dump(const Counter &C, raw_ostream &OS) const
LLVM_NODISCARD size_t size() const
size - Get the string size.
StringRef CoverageMapping
Error readIntMax(uint64_t &Result, uint64_t MaxPlus1)
Error readNextRecord(CoverageMappingRecord &Record) override
ArrayRef< StringRef > Filenames
Coverage mapping information for a single function.
static Error readCoverageMappingData(InstrProfSymtab &ProfileNames, StringRef Data, std::vector< BinaryCoverageReader::ProfileMappingRecord > &Records, std::vector< StringRef > &Filenames)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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.
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.
void consumeError(Error Err)
Consume a Error without doing anything.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
print lazy value Lazy Value Info Printer Pass
static ErrorSuccess success()
Create a success value.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Align max(MaybeAlign Lhs, Align Rhs)
static Expected< SectionRef > lookupSection(ObjectFile &OF, StringRef Name)
static const unsigned EncodingExpansionRegionBit
static const char * TestingFormatMagic
reference get()
Returns a reference to the stored T value.
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 StringRef readString(WasmObjectFile::ReadContext &Ctx)
static const unsigned EncodingCounterTagAndExpansionRegionTagBits
The mapping of profile information to coverage data.
const unsigned char * bytes_begin() const
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static Expected< std::unique_ptr< BinaryCoverageReader > > createCoverageReaderFromBuffer(StringRef Coverage, InstrProfSymtab &&ProfileNames, uint8_t BytesInAddress, support::endianness Endian)
static const unsigned EncodingTagBits
static Expected< bool > isCoverageMappingDummy(uint64_t Hash, StringRef Mapping)
LLVM Value Representation.
static Expected< std::unique_ptr< BinaryCoverageReader > > loadBinaryFormat(std::unique_ptr< Binary > Bin, StringRef Arch)
Lightweight error class with error context and mandatory checking.
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.