38 #include <system_error> 43 using namespace coverage;
45 #define DEBUG_TYPE "coverage-mapping" 48 auto It = ExpressionIndices.find(E);
49 if (It != ExpressionIndices.end())
51 unsigned I = Expressions.size();
52 Expressions.push_back(E);
53 ExpressionIndices[
E] =
I;
57 void CounterExpressionBuilder::extractTerms(
Counter C,
int Factor,
67 extractTerms(
E.LHS, Factor, Terms);
74 Counter CounterExpressionBuilder::simplify(
Counter ExpressionTree) {
77 extractTerms(ExpressionTree, +1, Terms);
81 if (Terms.
size() == 0)
85 llvm::sort(Terms, [](
const Term &LHS,
const Term &RHS) {
86 return LHS.CounterID < RHS.CounterID;
90 auto Prev = Terms.
begin();
91 for (
auto I = Prev + 1,
E = Terms.
end();
I !=
E; ++
I) {
92 if (
I->CounterID == Prev->CounterID) {
93 Prev->Factor +=
I->Factor;
104 for (
auto T : Terms) {
107 for (
int I = 0;
I <
T.Factor; ++
I)
116 for (
auto T : Terms) {
119 for (
int I = 0;
I < -
T.Factor; ++
I)
155 if (CounterValues.empty())
162 OS <<
'[' << *Value <<
']';
189 void FunctionRecordIterator::skipOtherFiles() {
190 while (Current != Records.end() && !Filename.empty() &&
191 Filename != Current->Filenames[0])
193 if (Current == Records.end())
200 auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
201 if (RecordIt == FilenameHash2RecordIndices.end())
203 return RecordIt->second;
206 Error CoverageMapping::loadFunctionRecord(
210 if (OrigFuncName.
empty())
220 std::vector<uint64_t> Counts;
228 return make_error<InstrProfError>(IPE);
257 if (!RecordProvenance[FilenamesHash].insert(
hash_value(OrigFuncName)).second)
260 Functions.push_back(std::move(Function));
265 unsigned RecordIndex = Functions.size() - 1;
267 auto &RecordIndices = FilenameHash2RecordIndices[
hash_value(Filename)];
271 if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
272 RecordIndices.push_back(RecordIndex);
279 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
281 auto Coverage = std::unique_ptr<CoverageMapping>(
new CoverageMapping());
283 for (
const auto &CoverageReader : CoverageReaders) {
284 for (
auto RecordOrErr : *CoverageReader) {
285 if (
Error E = RecordOrErr.takeError())
287 const auto &Record = *RecordOrErr;
288 if (
Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
293 return std::move(Coverage);
302 return make_error<CoverageMapError>(CME.
get());
310 if (
Error E = ProfileReaderOrErr.takeError())
312 auto ProfileReader = std::move(ProfileReaderOrErr.get());
318 if (std::error_code EC = CovMappingBufOrErr.getError())
322 CovMappingBufOrErr.get()->getMemBufferRef();
323 auto CoverageReadersOrErr =
325 if (
Error E = CoverageReadersOrErr.takeError()) {
332 for (
auto &Reader : CoverageReadersOrErr.get())
333 Readers.push_back(std::move(Reader));
334 Buffers.
push_back(std::move(CovMappingBufOrErr.get()));
338 if (Readers.empty() && !ObjectFilenames.
empty())
340 return load(Readers, *ProfileReader);
349 class FunctionInstantiationSetCollector {
350 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
351 MapT InstantiatedFunctions;
356 while (
I !=
E &&
I->FileID != FileID)
358 assert(
I !=
E &&
"function does not cover the given file");
359 auto &Functions = InstantiatedFunctions[
I->startLoc()];
360 Functions.push_back(&Function);
363 MapT::iterator
begin() {
return InstantiatedFunctions.
begin(); }
364 MapT::iterator
end() {
return InstantiatedFunctions.
end(); }
367 class SegmentBuilder {
368 std::vector<CoverageSegment> &Segments;
371 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
378 bool IsRegionEntry,
bool EmitSkippedRegion =
false) {
379 bool HasCount = !EmitSkippedRegion &&
383 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
384 const auto &Last = Segments.back();
385 if (Last.HasCount == HasCount && Last.Count == Region.
ExecutionCount &&
391 Segments.emplace_back(StartLoc.first, StartLoc.second,
395 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
398 const auto &Last = Segments.back();
399 dbgs() <<
"Segment at " << Last.Line <<
":" << Last.Col
400 <<
" (count = " << Last.Count <<
")" 401 << (Last.IsRegionEntry ?
", RegionEntry" :
"")
402 << (!Last.HasCount ?
", Skipped" :
"")
403 << (Last.IsGapRegion ?
", Gap" :
"") <<
"\n";
413 unsigned FirstCompletedRegion) {
416 auto CompletedRegionsIt = ActiveRegions.
begin() + FirstCompletedRegion;
419 return L->
endLoc() < R->endLoc();
423 for (
unsigned I = FirstCompletedRegion + 1,
E = ActiveRegions.
size();
I <
E;
425 const auto *CompletedRegion = ActiveRegions[
I];
426 assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
427 "Completed region ends after start of new region");
429 const auto *PrevCompletedRegion = ActiveRegions[
I - 1];
430 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
433 if (Loc && CompletedSegmentLoc == *Loc)
438 if (CompletedSegmentLoc == CompletedRegion->endLoc())
442 for (
unsigned J =
I + 1; J <
E; ++J)
443 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
444 CompletedRegion = ActiveRegions[J];
446 startSegment(*CompletedRegion, CompletedSegmentLoc,
false);
449 auto Last = ActiveRegions.
back();
450 if (FirstCompletedRegion && Last->endLoc() != *Loc) {
453 startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
455 }
else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
458 startSegment(*Last, Last->endLoc(),
false,
true);
462 ActiveRegions.
erase(CompletedRegionsIt, ActiveRegions.
end());
466 for (
const auto &CR :
enumerate(Regions)) {
467 auto CurStartLoc = CR.value().startLoc();
470 auto CompletedRegions =
471 std::stable_partition(ActiveRegions.
begin(), ActiveRegions.
end(),
473 return !(Region->
endLoc() <= CurStartLoc);
475 if (CompletedRegions != ActiveRegions.
end()) {
476 unsigned FirstCompletedRegion =
477 std::distance(ActiveRegions.
begin(), CompletedRegions);
478 completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
484 if (CurStartLoc == CR.value().endLoc()) {
487 const bool Skipped = (CR.index() + 1) == Regions.
size();
488 startSegment(ActiveRegions.
empty() ? CR.value() : *ActiveRegions.
back(),
489 CurStartLoc, !GapRegion, Skipped);
492 if (CR.index() + 1 == Regions.
size() ||
493 CurStartLoc != Regions[CR.index() + 1].startLoc()) {
496 startSegment(CR.value(), CurStartLoc, !GapRegion);
504 if (!ActiveRegions.
empty())
505 completeRegionsUntil(
None, 0);
525 "Unexpected order of region kind values");
535 auto Active = Regions.
begin();
536 auto End = Regions.
end();
537 for (
auto I = Regions.
begin() + 1;
I != End; ++
I) {
538 if (Active->startLoc() !=
I->startLoc() ||
539 Active->endLoc() !=
I->endLoc()) {
558 if (
I->Kind == Active->Kind)
559 Active->ExecutionCount +=
I->ExecutionCount;
561 return Regions.
drop_back(std::distance(++Active, End));
566 static std::vector<CoverageSegment>
568 std::vector<CoverageSegment> Segments;
569 SegmentBuilder Builder(Segments);
571 sortNestedRegions(Regions);
575 dbgs() <<
"Combined regions:\n";
576 for (
const auto &CR : CombinedRegions)
577 dbgs() <<
" " << CR.LineStart <<
":" << CR.ColumnStart <<
" -> " 578 << CR.LineEnd <<
":" << CR.ColumnEnd
579 <<
" (count=" << CR.ExecutionCount <<
")\n";
582 Builder.buildSegmentsImpl(CombinedRegions);
585 for (
unsigned I = 1,
E = Segments.size();
I <
E; ++
I) {
586 const auto &L = Segments[
I - 1];
587 const auto &R = Segments[
I];
588 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
590 <<
" followed by " << R.Line <<
":" << R.Col <<
"\n");
591 assert(
false &&
"Coverage segments not unique or sorted");
603 std::vector<StringRef> Filenames;
604 for (
const auto &
Function : getCoveredFunctions())
605 Filenames.insert(Filenames.end(),
Function.Filenames.
begin(),
608 auto Last = std::unique(Filenames.begin(), Filenames.end());
609 Filenames.erase(Last, Filenames.end());
618 FilenameEquivalence[
I] =
true;
619 return FilenameEquivalence;
627 IsNotExpandedFile[CR.ExpandedFileID] =
false;
628 int I = IsNotExpandedFile.find_first();
639 if (I && SourceFile == Function.
Filenames[*I])
650 std::vector<CountedRegion> Regions;
655 getImpreciseRecordIndicesForFilename(Filename);
656 for (
unsigned RecordIndex : RecordIndices) {
661 if (FileIDs.test(CR.FileID)) {
662 Regions.push_back(CR);
664 FileCoverage.Expansions.emplace_back(CR, Function);
668 LLVM_DEBUG(
dbgs() <<
"Emitting segments for file: " << Filename <<
"\n");
669 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
674 std::vector<InstantiationGroup>
676 FunctionInstantiationSetCollector InstantiationSetCollector;
680 getImpreciseRecordIndicesForFilename(Filename);
681 for (
unsigned RecordIndex : RecordIndices) {
686 InstantiationSetCollector.insert(Function, *MainFileID);
689 std::vector<InstantiationGroup> Result;
690 for (
auto &InstantiationSet : InstantiationSetCollector) {
692 InstantiationSet.first.second,
693 std::move(InstantiationSet.second)};
694 Result.emplace_back(std::move(IG));
706 std::vector<CountedRegion> Regions;
708 if (CR.FileID == *MainFileID) {
709 Regions.push_back(CR);
711 FunctionCoverage.Expansions.emplace_back(CR, Function);
716 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
718 return FunctionCoverage;
725 std::vector<CountedRegion> Regions;
727 if (CR.FileID == Expansion.
FileID) {
728 Regions.push_back(CR);
730 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.
Function);
734 << Expansion.
FileID <<
"\n");
735 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
737 return ExpansionCoverage;
740 LineCoverageStats::LineCoverageStats(
743 : ExecutionCount(0), HasMultipleRegions(
false), Mapped(
false), Line(Line),
744 LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
746 unsigned MinRegionCount = 0;
748 return !S->
IsGapRegion && S->HasCount && S->IsRegionEntry;
750 for (
unsigned I = 0;
I < LineSegments.
size() && MinRegionCount < 2; ++
I)
751 if (isStartOfRegion(LineSegments[
I]))
754 bool StartOfSkippedRegion = !LineSegments.
empty() &&
758 HasMultipleRegions = MinRegionCount > 1;
760 !StartOfSkippedRegion &&
761 ((WrappedSegment && WrappedSegment->
HasCount) || (MinRegionCount > 0));
769 ExecutionCount = WrappedSegment->
Count;
772 for (
const auto *
LS : LineSegments)
773 if (isStartOfRegion(
LS))
774 ExecutionCount =
std::max(ExecutionCount,
LS->Count);
778 if (Next == CD.end()) {
784 WrappedSegment = Segments.back();
786 while (Next != CD.end() && Next->Line == Line)
787 Segments.push_back(&*Next++);
798 return "End of File";
800 return "No coverage data found";
802 return "Unsupported coverage format version";
804 return "Truncated coverage data";
806 return "Malformed coverage data";
817 const char *
name()
const noexcept
override {
return "llvm.coveragemap"; }
818 std::string message(
int IE)
const override {
const T & front() const
front - Get the first element.
static Expected< std::vector< std::unique_ptr< BinaryCoverageReader > > > create(MemoryBufferRef ObjectBuffer, StringRef Arch, SmallVectorImpl< std::unique_ptr< MemoryBuffer >> &ObjectFileBuffers)
const_iterator end(StringRef path)
Get end iterator over path.
reference emplace_back(ArgTypes &&... Args)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
This class represents lattice values for constants.
static Counter getZero()
Return the counter that represents the number zero.
void setCounts(ArrayRef< uint64_t > Counts)
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
void push_back(const T &Elt)
LineColPair endLoc() const
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
void pushRegion(CounterMappingRegion Region, uint64_t Count)
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
CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
static Error handleMaybeNoDataFoundError(Error E)
Iterator over Functions, optionally filtered to a single file.
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
ArrayRef< CounterExpression > Expressions
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
An iterator over the LineCoverageStats objects for lines described by a CoverageData instance...
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
Tagged union holding either a T or a Error.
block placement Basic Block Placement Stats
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
std::pair< unsigned, unsigned > LineColPair
void dump(const Counter &C, raw_ostream &OS) const
Coverage information to be processed or displayed.
static Expected< std::unique_ptr< CoverageMapping > > load(ArrayRef< std::unique_ptr< CoverageMappingReader >> CoverageReaders, IndexedInstrProfReader &ProfileReader)
Load the coverage mapping using the given readers.
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Counter add(Counter LHS, Counter RHS)
Return a counter that represents the expression that adds LHS and RHS.
const std::error_category & coveragemap_category()
The execution count information starting at a point in a file.
ArrayRef< StringRef > Filenames
friend const_iterator end(StringRef path)
Get end iterator over path.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Coverage mapping information for a single function.
Instrumentation for Order File
size_t size() const
size - Get the array size.
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.
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
A CodeRegion associates some code with a counter.
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
bool IsRegionEntry
Whether this enters a new region or returns to a previous count.
static ManagedStatic< _object_error_category > error_category
LineColPair startLoc() const
static ManagedStatic< CoverageMappingErrorCategoryType > ErrorCategory
Associates a source range with an execution count.
iterator erase(const_iterator CI)
void consumeError(Error Err)
Consume a Error without doing anything.
MutableArrayRef< T > drop_back(size_t N=1) const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Counter subtract(Counter LHS, Counter RHS)
Return a counter that represents the expression that subtracts RHS from LHS.
CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
void sort(IteratorTy Start, IteratorTy End)
coveragemap_error get() const
Code coverage information for a single function.
static ErrorSuccess success()
Create a success value.
static std::string getCoverageMapErrString(coveragemap_error Err)
Align max(MaybeAlign Lhs, Align Rhs)
Coverage statistics for a single line.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static bool isExpansion(const CountedRegion &R, unsigned FileID)
uint64_t Count
The execution count, or zero if no count was recorded.
bool HasCount
When false, the segment was uninstrumented or skipped.
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.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
The mapping of profile information to coverage data.
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< InstantiationGroup > getInstantiationGroups(StringRef Filename) const
Get the list of function instantiation groups in a particular file.
std::string message() const override
Return the error message as a string.
unsigned getExpressionID() const
CounterKind getKind() const
LLVM_NODISCARD bool empty() const
static Optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed...
std::vector< CountedRegion > CountedRegions
Regions in the function along with their counts.
std::string Name
Raw function name.
unsigned FileID
The abstract file this expansion covers.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool IsGapRegion
Whether this enters a gap region.
void stable_sort(R &&Range)
unsigned getCounterID() const
LLVM Value Representation.
std::vector< std::string > Filenames
Mapping from FileID (i.e.
Lightweight error class with error context and mandatory checking.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
This class implements an extremely fast bulk output stream that can only output to a stream...
StringRef - Represent a constant reference to a string, i.e.
Reader for the indexed binary instrprof format.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, const Twine &RemappingPath="")
Factory method to create an indexed reader.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
LineCoverageIterator & operator++()
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
const FunctionRecord & Function
Coverage for the expansion.
bool empty() const
empty - Check if the array is empty.
std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
Coverage information for a macro expansion or #included file.