172208a82SEugene Zelenko //===- CoverageMapping.cpp - Code coverage mapping support ----------------===// 2dc707122SEaswaran Raman // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6dc707122SEaswaran Raman // 7dc707122SEaswaran Raman //===----------------------------------------------------------------------===// 8dc707122SEaswaran Raman // 9dc707122SEaswaran Raman // This file contains support for clang's and llvm's instrumentation based 10dc707122SEaswaran Raman // code coverage. 11dc707122SEaswaran Raman // 12dc707122SEaswaran Raman //===----------------------------------------------------------------------===// 13dc707122SEaswaran Raman 146bda14b3SChandler Carruth #include "llvm/ProfileData/Coverage/CoverageMapping.h" 15e78d131aSEugene Zelenko #include "llvm/ADT/ArrayRef.h" 16dc707122SEaswaran Raman #include "llvm/ADT/DenseMap.h" 17e78d131aSEugene Zelenko #include "llvm/ADT/None.h" 18dc707122SEaswaran Raman #include "llvm/ADT/Optional.h" 19dc707122SEaswaran Raman #include "llvm/ADT/SmallBitVector.h" 20e78d131aSEugene Zelenko #include "llvm/ADT/SmallVector.h" 21e78d131aSEugene Zelenko #include "llvm/ADT/StringRef.h" 22dc707122SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 23dc707122SEaswaran Raman #include "llvm/ProfileData/InstrProfReader.h" 24dc707122SEaswaran Raman #include "llvm/Support/Debug.h" 25dc707122SEaswaran Raman #include "llvm/Support/Errc.h" 26e78d131aSEugene Zelenko #include "llvm/Support/Error.h" 27dc707122SEaswaran Raman #include "llvm/Support/ErrorHandling.h" 28dc707122SEaswaran Raman #include "llvm/Support/ManagedStatic.h" 29e78d131aSEugene Zelenko #include "llvm/Support/MemoryBuffer.h" 30dc707122SEaswaran Raman #include "llvm/Support/raw_ostream.h" 31e78d131aSEugene Zelenko #include <algorithm> 32e78d131aSEugene Zelenko #include <cassert> 33e78d131aSEugene Zelenko #include <cstdint> 34e78d131aSEugene Zelenko #include <iterator> 357bef6da6SVedant Kumar #include <map> 36e78d131aSEugene Zelenko #include <memory> 37e78d131aSEugene Zelenko #include <string> 38e78d131aSEugene Zelenko #include <system_error> 39e78d131aSEugene Zelenko #include <utility> 40e78d131aSEugene Zelenko #include <vector> 41dc707122SEaswaran Raman 42dc707122SEaswaran Raman using namespace llvm; 43dc707122SEaswaran Raman using namespace coverage; 44dc707122SEaswaran Raman 45dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping" 46dc707122SEaswaran Raman 47dc707122SEaswaran Raman Counter CounterExpressionBuilder::get(const CounterExpression &E) { 48dc707122SEaswaran Raman auto It = ExpressionIndices.find(E); 49dc707122SEaswaran Raman if (It != ExpressionIndices.end()) 50dc707122SEaswaran Raman return Counter::getExpression(It->second); 51dc707122SEaswaran Raman unsigned I = Expressions.size(); 52dc707122SEaswaran Raman Expressions.push_back(E); 53dc707122SEaswaran Raman ExpressionIndices[E] = I; 54dc707122SEaswaran Raman return Counter::getExpression(I); 55dc707122SEaswaran Raman } 56dc707122SEaswaran Raman 5771b3d721SVedant Kumar void CounterExpressionBuilder::extractTerms(Counter C, int Factor, 5871b3d721SVedant Kumar SmallVectorImpl<Term> &Terms) { 59dc707122SEaswaran Raman switch (C.getKind()) { 60dc707122SEaswaran Raman case Counter::Zero: 61dc707122SEaswaran Raman break; 62dc707122SEaswaran Raman case Counter::CounterValueReference: 6371b3d721SVedant Kumar Terms.emplace_back(C.getCounterID(), Factor); 64dc707122SEaswaran Raman break; 65dc707122SEaswaran Raman case Counter::Expression: 66dc707122SEaswaran Raman const auto &E = Expressions[C.getExpressionID()]; 6771b3d721SVedant Kumar extractTerms(E.LHS, Factor, Terms); 6871b3d721SVedant Kumar extractTerms( 6971b3d721SVedant Kumar E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms); 70dc707122SEaswaran Raman break; 71dc707122SEaswaran Raman } 72dc707122SEaswaran Raman } 73dc707122SEaswaran Raman 74dc707122SEaswaran Raman Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) { 75dc707122SEaswaran Raman // Gather constant terms. 7671b3d721SVedant Kumar SmallVector<Term, 32> Terms; 77dc707122SEaswaran Raman extractTerms(ExpressionTree, +1, Terms); 78dc707122SEaswaran Raman 79dc707122SEaswaran Raman // If there are no terms, this is just a zero. The algorithm below assumes at 80dc707122SEaswaran Raman // least one term. 81dc707122SEaswaran Raman if (Terms.size() == 0) 82dc707122SEaswaran Raman return Counter::getZero(); 83dc707122SEaswaran Raman 84dc707122SEaswaran Raman // Group the terms by counter ID. 850cac726aSFangrui Song llvm::sort(Terms, [](const Term &LHS, const Term &RHS) { 8671b3d721SVedant Kumar return LHS.CounterID < RHS.CounterID; 87dc707122SEaswaran Raman }); 88dc707122SEaswaran Raman 89dc707122SEaswaran Raman // Combine terms by counter ID to eliminate counters that sum to zero. 90dc707122SEaswaran Raman auto Prev = Terms.begin(); 91dc707122SEaswaran Raman for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) { 9271b3d721SVedant Kumar if (I->CounterID == Prev->CounterID) { 9371b3d721SVedant Kumar Prev->Factor += I->Factor; 94dc707122SEaswaran Raman continue; 95dc707122SEaswaran Raman } 96dc707122SEaswaran Raman ++Prev; 97dc707122SEaswaran Raman *Prev = *I; 98dc707122SEaswaran Raman } 99dc707122SEaswaran Raman Terms.erase(++Prev, Terms.end()); 100dc707122SEaswaran Raman 101dc707122SEaswaran Raman Counter C; 102dc707122SEaswaran Raman // Create additions. We do this before subtractions to avoid constructs like 103dc707122SEaswaran Raman // ((0 - X) + Y), as opposed to (Y - X). 10471b3d721SVedant Kumar for (auto T : Terms) { 10571b3d721SVedant Kumar if (T.Factor <= 0) 106dc707122SEaswaran Raman continue; 10771b3d721SVedant Kumar for (int I = 0; I < T.Factor; ++I) 108dc707122SEaswaran Raman if (C.isZero()) 10971b3d721SVedant Kumar C = Counter::getCounter(T.CounterID); 110dc707122SEaswaran Raman else 111dc707122SEaswaran Raman C = get(CounterExpression(CounterExpression::Add, C, 11271b3d721SVedant Kumar Counter::getCounter(T.CounterID))); 113dc707122SEaswaran Raman } 114dc707122SEaswaran Raman 115dc707122SEaswaran Raman // Create subtractions. 11671b3d721SVedant Kumar for (auto T : Terms) { 11771b3d721SVedant Kumar if (T.Factor >= 0) 118dc707122SEaswaran Raman continue; 11971b3d721SVedant Kumar for (int I = 0; I < -T.Factor; ++I) 120dc707122SEaswaran Raman C = get(CounterExpression(CounterExpression::Subtract, C, 12171b3d721SVedant Kumar Counter::getCounter(T.CounterID))); 122dc707122SEaswaran Raman } 123dc707122SEaswaran Raman return C; 124dc707122SEaswaran Raman } 125dc707122SEaswaran Raman 126dc707122SEaswaran Raman Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) { 127dc707122SEaswaran Raman return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS))); 128dc707122SEaswaran Raman } 129dc707122SEaswaran Raman 130dc707122SEaswaran Raman Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) { 131dc707122SEaswaran Raman return simplify( 132dc707122SEaswaran Raman get(CounterExpression(CounterExpression::Subtract, LHS, RHS))); 133dc707122SEaswaran Raman } 134dc707122SEaswaran Raman 135e78d131aSEugene Zelenko void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const { 136dc707122SEaswaran Raman switch (C.getKind()) { 137dc707122SEaswaran Raman case Counter::Zero: 138dc707122SEaswaran Raman OS << '0'; 139dc707122SEaswaran Raman return; 140dc707122SEaswaran Raman case Counter::CounterValueReference: 141dc707122SEaswaran Raman OS << '#' << C.getCounterID(); 142dc707122SEaswaran Raman break; 143dc707122SEaswaran Raman case Counter::Expression: { 144dc707122SEaswaran Raman if (C.getExpressionID() >= Expressions.size()) 145dc707122SEaswaran Raman return; 146dc707122SEaswaran Raman const auto &E = Expressions[C.getExpressionID()]; 147dc707122SEaswaran Raman OS << '('; 148dc707122SEaswaran Raman dump(E.LHS, OS); 149dc707122SEaswaran Raman OS << (E.Kind == CounterExpression::Subtract ? " - " : " + "); 150dc707122SEaswaran Raman dump(E.RHS, OS); 151dc707122SEaswaran Raman OS << ')'; 152dc707122SEaswaran Raman break; 153dc707122SEaswaran Raman } 154dc707122SEaswaran Raman } 155dc707122SEaswaran Raman if (CounterValues.empty()) 156dc707122SEaswaran Raman return; 1579152fd17SVedant Kumar Expected<int64_t> Value = evaluate(C); 1589152fd17SVedant Kumar if (auto E = Value.takeError()) { 159e78d131aSEugene Zelenko consumeError(std::move(E)); 160dc707122SEaswaran Raman return; 1619152fd17SVedant Kumar } 162dc707122SEaswaran Raman OS << '[' << *Value << ']'; 163dc707122SEaswaran Raman } 164dc707122SEaswaran Raman 1659152fd17SVedant Kumar Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const { 166dc707122SEaswaran Raman switch (C.getKind()) { 167dc707122SEaswaran Raman case Counter::Zero: 168dc707122SEaswaran Raman return 0; 169dc707122SEaswaran Raman case Counter::CounterValueReference: 170dc707122SEaswaran Raman if (C.getCounterID() >= CounterValues.size()) 1719152fd17SVedant Kumar return errorCodeToError(errc::argument_out_of_domain); 172dc707122SEaswaran Raman return CounterValues[C.getCounterID()]; 173dc707122SEaswaran Raman case Counter::Expression: { 174dc707122SEaswaran Raman if (C.getExpressionID() >= Expressions.size()) 1759152fd17SVedant Kumar return errorCodeToError(errc::argument_out_of_domain); 176dc707122SEaswaran Raman const auto &E = Expressions[C.getExpressionID()]; 1779152fd17SVedant Kumar Expected<int64_t> LHS = evaluate(E.LHS); 178dc707122SEaswaran Raman if (!LHS) 179dc707122SEaswaran Raman return LHS; 1809152fd17SVedant Kumar Expected<int64_t> RHS = evaluate(E.RHS); 181dc707122SEaswaran Raman if (!RHS) 182dc707122SEaswaran Raman return RHS; 183dc707122SEaswaran Raman return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS; 184dc707122SEaswaran Raman } 185dc707122SEaswaran Raman } 186dc707122SEaswaran Raman llvm_unreachable("Unhandled CounterKind"); 187dc707122SEaswaran Raman } 188dc707122SEaswaran Raman 189dc707122SEaswaran Raman void FunctionRecordIterator::skipOtherFiles() { 190dc707122SEaswaran Raman while (Current != Records.end() && !Filename.empty() && 191dc707122SEaswaran Raman Filename != Current->Filenames[0]) 192dc707122SEaswaran Raman ++Current; 193dc707122SEaswaran Raman if (Current == Records.end()) 194dc707122SEaswaran Raman *this = FunctionRecordIterator(); 195dc707122SEaswaran Raman } 196dc707122SEaswaran Raman 19768216d7bSVedant Kumar Error CoverageMapping::loadFunctionRecord( 19868216d7bSVedant Kumar const CoverageMappingRecord &Record, 199dc707122SEaswaran Raman IndexedInstrProfReader &ProfileReader) { 200743574b8SVedant Kumar StringRef OrigFuncName = Record.FunctionName; 201b1d331a3SVedant Kumar if (OrigFuncName.empty()) 202b1d331a3SVedant Kumar return make_error<CoverageMapError>(coveragemap_error::malformed); 203b1d331a3SVedant Kumar 204743574b8SVedant Kumar if (Record.Filenames.empty()) 205743574b8SVedant Kumar OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName); 206743574b8SVedant Kumar else 207743574b8SVedant Kumar OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]); 208743574b8SVedant Kumar 209dc707122SEaswaran Raman CounterMappingContext Ctx(Record.Expressions); 210dc707122SEaswaran Raman 21168216d7bSVedant Kumar std::vector<uint64_t> Counts; 21268216d7bSVedant Kumar if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName, 21368216d7bSVedant Kumar Record.FunctionHash, Counts)) { 2149152fd17SVedant Kumar instrprof_error IPE = InstrProfError::take(std::move(E)); 2159152fd17SVedant Kumar if (IPE == instrprof_error::hash_mismatch) { 21618dd9e88SVedant Kumar FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash); 21768216d7bSVedant Kumar return Error::success(); 2189152fd17SVedant Kumar } else if (IPE != instrprof_error::unknown_function) 2199152fd17SVedant Kumar return make_error<InstrProfError>(IPE); 220dc707122SEaswaran Raman Counts.assign(Record.MappingRegions.size(), 0); 221dc707122SEaswaran Raman } 222dc707122SEaswaran Raman Ctx.setCounts(Counts); 223dc707122SEaswaran Raman 224dc707122SEaswaran Raman assert(!Record.MappingRegions.empty() && "Function has no regions"); 225dc707122SEaswaran Raman 226381e9d23SVedant Kumar // This coverage record is a zero region for a function that's unused in 227381e9d23SVedant Kumar // some TU, but used in a different TU. Ignore it. The coverage maps from the 228381e9d23SVedant Kumar // the other TU will either be loaded (providing full region counts) or they 229381e9d23SVedant Kumar // won't (in which case we don't unintuitively report functions as uncovered 230381e9d23SVedant Kumar // when they have non-zero counts in the profile). 231381e9d23SVedant Kumar if (Record.MappingRegions.size() == 1 && 232381e9d23SVedant Kumar Record.MappingRegions[0].Count.isZero() && Counts[0] > 0) 233381e9d23SVedant Kumar return Error::success(); 234381e9d23SVedant Kumar 235dc707122SEaswaran Raman FunctionRecord Function(OrigFuncName, Record.Filenames); 236dc707122SEaswaran Raman for (const auto &Region : Record.MappingRegions) { 2379152fd17SVedant Kumar Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count); 2389152fd17SVedant Kumar if (auto E = ExecutionCount.takeError()) { 239e78d131aSEugene Zelenko consumeError(std::move(E)); 24068216d7bSVedant Kumar return Error::success(); 2419152fd17SVedant Kumar } 242dc707122SEaswaran Raman Function.pushRegion(Region, *ExecutionCount); 243dc707122SEaswaran Raman } 244dc707122SEaswaran Raman 245381e9d23SVedant Kumar // Don't create records for (filenames, function) pairs we've already seen. 246381e9d23SVedant Kumar auto FilenamesHash = hash_combine_range(Record.Filenames.begin(), 247381e9d23SVedant Kumar Record.Filenames.end()); 248381e9d23SVedant Kumar if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second) 249381e9d23SVedant Kumar return Error::success(); 250381e9d23SVedant Kumar 25168216d7bSVedant Kumar Functions.push_back(std::move(Function)); 25268216d7bSVedant Kumar return Error::success(); 253dc707122SEaswaran Raman } 254dc707122SEaswaran Raman 255743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load( 256743574b8SVedant Kumar ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders, 257743574b8SVedant Kumar IndexedInstrProfReader &ProfileReader) { 258743574b8SVedant Kumar auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); 259743574b8SVedant Kumar 260bae83970SVedant Kumar for (const auto &CoverageReader : CoverageReaders) { 261bae83970SVedant Kumar for (auto RecordOrErr : *CoverageReader) { 262bae83970SVedant Kumar if (Error E = RecordOrErr.takeError()) 263bae83970SVedant Kumar return std::move(E); 264bae83970SVedant Kumar const auto &Record = *RecordOrErr; 265743574b8SVedant Kumar if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader)) 2669152fd17SVedant Kumar return std::move(E); 267bae83970SVedant Kumar } 268bae83970SVedant Kumar } 269743574b8SVedant Kumar 270743574b8SVedant Kumar return std::move(Coverage); 271743574b8SVedant Kumar } 272743574b8SVedant Kumar 273743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> 274743574b8SVedant Kumar CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames, 2754b102c3dSVedant Kumar StringRef ProfileFilename, ArrayRef<StringRef> Arches) { 276dc707122SEaswaran Raman auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename); 2779152fd17SVedant Kumar if (Error E = ProfileReaderOrErr.takeError()) 2789152fd17SVedant Kumar return std::move(E); 279dc707122SEaswaran Raman auto ProfileReader = std::move(ProfileReaderOrErr.get()); 280743574b8SVedant Kumar 281743574b8SVedant Kumar SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers; 282743574b8SVedant Kumar SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers; 2834b102c3dSVedant Kumar for (const auto &File : llvm::enumerate(ObjectFilenames)) { 2844b102c3dSVedant Kumar auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value()); 285743574b8SVedant Kumar if (std::error_code EC = CovMappingBufOrErr.getError()) 286743574b8SVedant Kumar return errorCodeToError(EC); 2874b102c3dSVedant Kumar StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()]; 288*901d04fcSVedant Kumar MemoryBufferRef CovMappingBufRef = 289*901d04fcSVedant Kumar CovMappingBufOrErr.get()->getMemBufferRef(); 290*901d04fcSVedant Kumar auto CoverageReadersOrErr = 291*901d04fcSVedant Kumar BinaryCoverageReader::create(CovMappingBufRef, Arch, Buffers); 292*901d04fcSVedant Kumar if (Error E = CoverageReadersOrErr.takeError()) 293743574b8SVedant Kumar return std::move(E); 294*901d04fcSVedant Kumar for (auto &Reader : CoverageReadersOrErr.get()) 295*901d04fcSVedant Kumar Readers.push_back(std::move(Reader)); 296743574b8SVedant Kumar Buffers.push_back(std::move(CovMappingBufOrErr.get())); 297743574b8SVedant Kumar } 298743574b8SVedant Kumar return load(Readers, *ProfileReader); 299dc707122SEaswaran Raman } 300dc707122SEaswaran Raman 301dc707122SEaswaran Raman namespace { 302e78d131aSEugene Zelenko 3035f8f34e4SAdrian Prantl /// Distributes functions into instantiation sets. 304dc707122SEaswaran Raman /// 305dc707122SEaswaran Raman /// An instantiation set is a collection of functions that have the same source 306dc707122SEaswaran Raman /// code, ie, template functions specializations. 307dc707122SEaswaran Raman class FunctionInstantiationSetCollector { 3087bef6da6SVedant Kumar using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>; 309dc707122SEaswaran Raman MapT InstantiatedFunctions; 310dc707122SEaswaran Raman 311dc707122SEaswaran Raman public: 312dc707122SEaswaran Raman void insert(const FunctionRecord &Function, unsigned FileID) { 313dc707122SEaswaran Raman auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end(); 314dc707122SEaswaran Raman while (I != E && I->FileID != FileID) 315dc707122SEaswaran Raman ++I; 316dc707122SEaswaran Raman assert(I != E && "function does not cover the given file"); 317dc707122SEaswaran Raman auto &Functions = InstantiatedFunctions[I->startLoc()]; 318dc707122SEaswaran Raman Functions.push_back(&Function); 319dc707122SEaswaran Raman } 320dc707122SEaswaran Raman 321dc707122SEaswaran Raman MapT::iterator begin() { return InstantiatedFunctions.begin(); } 322dc707122SEaswaran Raman MapT::iterator end() { return InstantiatedFunctions.end(); } 323dc707122SEaswaran Raman }; 324dc707122SEaswaran Raman 325dc707122SEaswaran Raman class SegmentBuilder { 326dc707122SEaswaran Raman std::vector<CoverageSegment> &Segments; 327dc707122SEaswaran Raman SmallVector<const CountedRegion *, 8> ActiveRegions; 328dc707122SEaswaran Raman 329dc707122SEaswaran Raman SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {} 330dc707122SEaswaran Raman 33179a1b5eeSVedant Kumar /// Emit a segment with the count from \p Region starting at \p StartLoc. 33279a1b5eeSVedant Kumar // 333ad8f637bSVedant Kumar /// \p IsRegionEntry: The segment is at the start of a new non-gap region. 33479a1b5eeSVedant Kumar /// \p EmitSkippedRegion: The segment must be emitted as a skipped region. 33579a1b5eeSVedant Kumar void startSegment(const CountedRegion &Region, LineColPair StartLoc, 33679a1b5eeSVedant Kumar bool IsRegionEntry, bool EmitSkippedRegion = false) { 33779a1b5eeSVedant Kumar bool HasCount = !EmitSkippedRegion && 33879a1b5eeSVedant Kumar (Region.Kind != CounterMappingRegion::SkippedRegion); 33979a1b5eeSVedant Kumar 34079a1b5eeSVedant Kumar // If the new segment wouldn't affect coverage rendering, skip it. 34179a1b5eeSVedant Kumar if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) { 34279a1b5eeSVedant Kumar const auto &Last = Segments.back(); 34379a1b5eeSVedant Kumar if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount && 34479a1b5eeSVedant Kumar !Last.IsRegionEntry) 34579a1b5eeSVedant Kumar return; 346dc707122SEaswaran Raman } 347dc707122SEaswaran Raman 34879a1b5eeSVedant Kumar if (HasCount) 34979a1b5eeSVedant Kumar Segments.emplace_back(StartLoc.first, StartLoc.second, 350ad8f637bSVedant Kumar Region.ExecutionCount, IsRegionEntry, 351ad8f637bSVedant Kumar Region.Kind == CounterMappingRegion::GapRegion); 352dc707122SEaswaran Raman else 35379a1b5eeSVedant Kumar Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry); 35479a1b5eeSVedant Kumar 355d34e60caSNicola Zaghen LLVM_DEBUG({ 35679a1b5eeSVedant Kumar const auto &Last = Segments.back(); 35779a1b5eeSVedant Kumar dbgs() << "Segment at " << Last.Line << ":" << Last.Col 35879a1b5eeSVedant Kumar << " (count = " << Last.Count << ")" 35979a1b5eeSVedant Kumar << (Last.IsRegionEntry ? ", RegionEntry" : "") 360ad8f637bSVedant Kumar << (!Last.HasCount ? ", Skipped" : "") 361ad8f637bSVedant Kumar << (Last.IsGapRegion ? ", Gap" : "") << "\n"; 36279a1b5eeSVedant Kumar }); 36379a1b5eeSVedant Kumar } 36479a1b5eeSVedant Kumar 36579a1b5eeSVedant Kumar /// Emit segments for active regions which end before \p Loc. 36679a1b5eeSVedant Kumar /// 36779a1b5eeSVedant Kumar /// \p Loc: The start location of the next region. If None, all active 36879a1b5eeSVedant Kumar /// regions are completed. 36979a1b5eeSVedant Kumar /// \p FirstCompletedRegion: Index of the first completed region. 37079a1b5eeSVedant Kumar void completeRegionsUntil(Optional<LineColPair> Loc, 37179a1b5eeSVedant Kumar unsigned FirstCompletedRegion) { 37279a1b5eeSVedant Kumar // Sort the completed regions by end location. This makes it simple to 37379a1b5eeSVedant Kumar // emit closing segments in sorted order. 37479a1b5eeSVedant Kumar auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion; 37579a1b5eeSVedant Kumar std::stable_sort(CompletedRegionsIt, ActiveRegions.end(), 37679a1b5eeSVedant Kumar [](const CountedRegion *L, const CountedRegion *R) { 37779a1b5eeSVedant Kumar return L->endLoc() < R->endLoc(); 37879a1b5eeSVedant Kumar }); 37979a1b5eeSVedant Kumar 38079a1b5eeSVedant Kumar // Emit segments for all completed regions. 38179a1b5eeSVedant Kumar for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E; 38279a1b5eeSVedant Kumar ++I) { 38379a1b5eeSVedant Kumar const auto *CompletedRegion = ActiveRegions[I]; 38479a1b5eeSVedant Kumar assert((!Loc || CompletedRegion->endLoc() <= *Loc) && 38579a1b5eeSVedant Kumar "Completed region ends after start of new region"); 38679a1b5eeSVedant Kumar 38779a1b5eeSVedant Kumar const auto *PrevCompletedRegion = ActiveRegions[I - 1]; 38879a1b5eeSVedant Kumar auto CompletedSegmentLoc = PrevCompletedRegion->endLoc(); 38979a1b5eeSVedant Kumar 39079a1b5eeSVedant Kumar // Don't emit any more segments if they start where the new region begins. 39179a1b5eeSVedant Kumar if (Loc && CompletedSegmentLoc == *Loc) 39279a1b5eeSVedant Kumar break; 39379a1b5eeSVedant Kumar 39479a1b5eeSVedant Kumar // Don't emit a segment if the next completed region ends at the same 39579a1b5eeSVedant Kumar // location as this one. 39679a1b5eeSVedant Kumar if (CompletedSegmentLoc == CompletedRegion->endLoc()) 39779a1b5eeSVedant Kumar continue; 39879a1b5eeSVedant Kumar 399337b0db1SVedant Kumar // Use the count from the last completed region which ends at this loc. 400337b0db1SVedant Kumar for (unsigned J = I + 1; J < E; ++J) 401337b0db1SVedant Kumar if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc()) 402337b0db1SVedant Kumar CompletedRegion = ActiveRegions[J]; 40380fbb855SVedant Kumar 40479a1b5eeSVedant Kumar startSegment(*CompletedRegion, CompletedSegmentLoc, false); 40579a1b5eeSVedant Kumar } 40679a1b5eeSVedant Kumar 40779a1b5eeSVedant Kumar auto Last = ActiveRegions.back(); 40879a1b5eeSVedant Kumar if (FirstCompletedRegion && Last->endLoc() != *Loc) { 40979a1b5eeSVedant Kumar // If there's a gap after the end of the last completed region and the 41079a1b5eeSVedant Kumar // start of the new region, use the last active region to fill the gap. 41179a1b5eeSVedant Kumar startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(), 41279a1b5eeSVedant Kumar false); 41379a1b5eeSVedant Kumar } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) { 41479a1b5eeSVedant Kumar // Emit a skipped segment if there are no more active regions. This 41579a1b5eeSVedant Kumar // ensures that gaps between functions are marked correctly. 41679a1b5eeSVedant Kumar startSegment(*Last, Last->endLoc(), false, true); 41779a1b5eeSVedant Kumar } 41879a1b5eeSVedant Kumar 41979a1b5eeSVedant Kumar // Pop the completed regions. 42079a1b5eeSVedant Kumar ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end()); 421dc707122SEaswaran Raman } 422dc707122SEaswaran Raman 423dc707122SEaswaran Raman void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) { 42479a1b5eeSVedant Kumar for (const auto &CR : enumerate(Regions)) { 42579a1b5eeSVedant Kumar auto CurStartLoc = CR.value().startLoc(); 42679a1b5eeSVedant Kumar 42779a1b5eeSVedant Kumar // Active regions which end before the current region need to be popped. 42879a1b5eeSVedant Kumar auto CompletedRegions = 42979a1b5eeSVedant Kumar std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(), 43079a1b5eeSVedant Kumar [&](const CountedRegion *Region) { 43179a1b5eeSVedant Kumar return !(Region->endLoc() <= CurStartLoc); 43279a1b5eeSVedant Kumar }); 43379a1b5eeSVedant Kumar if (CompletedRegions != ActiveRegions.end()) { 43479a1b5eeSVedant Kumar unsigned FirstCompletedRegion = 43579a1b5eeSVedant Kumar std::distance(ActiveRegions.begin(), CompletedRegions); 43679a1b5eeSVedant Kumar completeRegionsUntil(CurStartLoc, FirstCompletedRegion); 437dc707122SEaswaran Raman } 43879a1b5eeSVedant Kumar 439ad8f637bSVedant Kumar bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion; 440ad8f637bSVedant Kumar 44179a1b5eeSVedant Kumar // Try to emit a segment for the current region. 44279a1b5eeSVedant Kumar if (CurStartLoc == CR.value().endLoc()) { 44379a1b5eeSVedant Kumar // Avoid making zero-length regions active. If it's the last region, 44479a1b5eeSVedant Kumar // emit a skipped segment. Otherwise use its predecessor's count. 44579a1b5eeSVedant Kumar const bool Skipped = (CR.index() + 1) == Regions.size(); 44679a1b5eeSVedant Kumar startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(), 447ad8f637bSVedant Kumar CurStartLoc, !GapRegion, Skipped); 44879a1b5eeSVedant Kumar continue; 44979a1b5eeSVedant Kumar } 45079a1b5eeSVedant Kumar if (CR.index() + 1 == Regions.size() || 45179a1b5eeSVedant Kumar CurStartLoc != Regions[CR.index() + 1].startLoc()) { 45279a1b5eeSVedant Kumar // Emit a segment if the next region doesn't start at the same location 45379a1b5eeSVedant Kumar // as this one. 454ad8f637bSVedant Kumar startSegment(CR.value(), CurStartLoc, !GapRegion); 45579a1b5eeSVedant Kumar } 45679a1b5eeSVedant Kumar 45779a1b5eeSVedant Kumar // This region is active (i.e not completed). 45879a1b5eeSVedant Kumar ActiveRegions.push_back(&CR.value()); 45979a1b5eeSVedant Kumar } 46079a1b5eeSVedant Kumar 46179a1b5eeSVedant Kumar // Complete any remaining active regions. 46279a1b5eeSVedant Kumar if (!ActiveRegions.empty()) 46379a1b5eeSVedant Kumar completeRegionsUntil(None, 0); 464dc707122SEaswaran Raman } 465dc707122SEaswaran Raman 466dc707122SEaswaran Raman /// Sort a nested sequence of regions from a single file. 467dc707122SEaswaran Raman static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) { 4680cac726aSFangrui Song llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) { 46927d8dd39SIgor Kudrin if (LHS.startLoc() != RHS.startLoc()) 47027d8dd39SIgor Kudrin return LHS.startLoc() < RHS.startLoc(); 47127d8dd39SIgor Kudrin if (LHS.endLoc() != RHS.endLoc()) 472dc707122SEaswaran Raman // When LHS completely contains RHS, we sort LHS first. 473dc707122SEaswaran Raman return RHS.endLoc() < LHS.endLoc(); 47427d8dd39SIgor Kudrin // If LHS and RHS cover the same area, we need to sort them according 47527d8dd39SIgor Kudrin // to their kinds so that the most suitable region will become "active" 47627d8dd39SIgor Kudrin // in combineRegions(). Because we accumulate counter values only from 47727d8dd39SIgor Kudrin // regions of the same kind as the first region of the area, prefer 47827d8dd39SIgor Kudrin // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion. 479e78d131aSEugene Zelenko static_assert(CounterMappingRegion::CodeRegion < 480e78d131aSEugene Zelenko CounterMappingRegion::ExpansionRegion && 481e78d131aSEugene Zelenko CounterMappingRegion::ExpansionRegion < 482e78d131aSEugene Zelenko CounterMappingRegion::SkippedRegion, 48327d8dd39SIgor Kudrin "Unexpected order of region kind values"); 48427d8dd39SIgor Kudrin return LHS.Kind < RHS.Kind; 485dc707122SEaswaran Raman }); 486dc707122SEaswaran Raman } 487dc707122SEaswaran Raman 488dc707122SEaswaran Raman /// Combine counts of regions which cover the same area. 489dc707122SEaswaran Raman static ArrayRef<CountedRegion> 490dc707122SEaswaran Raman combineRegions(MutableArrayRef<CountedRegion> Regions) { 491dc707122SEaswaran Raman if (Regions.empty()) 492dc707122SEaswaran Raman return Regions; 493dc707122SEaswaran Raman auto Active = Regions.begin(); 494dc707122SEaswaran Raman auto End = Regions.end(); 495dc707122SEaswaran Raman for (auto I = Regions.begin() + 1; I != End; ++I) { 496dc707122SEaswaran Raman if (Active->startLoc() != I->startLoc() || 497dc707122SEaswaran Raman Active->endLoc() != I->endLoc()) { 498dc707122SEaswaran Raman // Shift to the next region. 499dc707122SEaswaran Raman ++Active; 500dc707122SEaswaran Raman if (Active != I) 501dc707122SEaswaran Raman *Active = *I; 502dc707122SEaswaran Raman continue; 503dc707122SEaswaran Raman } 504dc707122SEaswaran Raman // Merge duplicate region. 50527d8dd39SIgor Kudrin // If CodeRegions and ExpansionRegions cover the same area, it's probably 50627d8dd39SIgor Kudrin // a macro which is fully expanded to another macro. In that case, we need 50727d8dd39SIgor Kudrin // to accumulate counts only from CodeRegions, or else the area will be 50827d8dd39SIgor Kudrin // counted twice. 50927d8dd39SIgor Kudrin // On the other hand, a macro may have a nested macro in its body. If the 51027d8dd39SIgor Kudrin // outer macro is used several times, the ExpansionRegion for the nested 51127d8dd39SIgor Kudrin // macro will also be added several times. These ExpansionRegions cover 51227d8dd39SIgor Kudrin // the same source locations and have to be combined to reach the correct 51327d8dd39SIgor Kudrin // value for that area. 51427d8dd39SIgor Kudrin // We add counts of the regions of the same kind as the active region 51527d8dd39SIgor Kudrin // to handle the both situations. 51627d8dd39SIgor Kudrin if (I->Kind == Active->Kind) 517dc707122SEaswaran Raman Active->ExecutionCount += I->ExecutionCount; 518dc707122SEaswaran Raman } 519dc707122SEaswaran Raman return Regions.drop_back(std::distance(++Active, End)); 520dc707122SEaswaran Raman } 521dc707122SEaswaran Raman 522dc707122SEaswaran Raman public: 52379a1b5eeSVedant Kumar /// Build a sorted list of CoverageSegments from a list of Regions. 524dc707122SEaswaran Raman static std::vector<CoverageSegment> 525dc707122SEaswaran Raman buildSegments(MutableArrayRef<CountedRegion> Regions) { 526dc707122SEaswaran Raman std::vector<CoverageSegment> Segments; 527dc707122SEaswaran Raman SegmentBuilder Builder(Segments); 528dc707122SEaswaran Raman 529dc707122SEaswaran Raman sortNestedRegions(Regions); 530dc707122SEaswaran Raman ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions); 531dc707122SEaswaran Raman 532d34e60caSNicola Zaghen LLVM_DEBUG({ 53379a1b5eeSVedant Kumar dbgs() << "Combined regions:\n"; 53479a1b5eeSVedant Kumar for (const auto &CR : CombinedRegions) 53579a1b5eeSVedant Kumar dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " 53679a1b5eeSVedant Kumar << CR.LineEnd << ":" << CR.ColumnEnd 53779a1b5eeSVedant Kumar << " (count=" << CR.ExecutionCount << ")\n"; 53879a1b5eeSVedant Kumar }); 53979a1b5eeSVedant Kumar 540dc707122SEaswaran Raman Builder.buildSegmentsImpl(CombinedRegions); 54179a1b5eeSVedant Kumar 54279a1b5eeSVedant Kumar #ifndef NDEBUG 54379a1b5eeSVedant Kumar for (unsigned I = 1, E = Segments.size(); I < E; ++I) { 54479a1b5eeSVedant Kumar const auto &L = Segments[I - 1]; 54579a1b5eeSVedant Kumar const auto &R = Segments[I]; 54679a1b5eeSVedant Kumar if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) { 547d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col 54879a1b5eeSVedant Kumar << " followed by " << R.Line << ":" << R.Col << "\n"); 54979a1b5eeSVedant Kumar assert(false && "Coverage segments not unique or sorted"); 55079a1b5eeSVedant Kumar } 55179a1b5eeSVedant Kumar } 55279a1b5eeSVedant Kumar #endif 55379a1b5eeSVedant Kumar 554dc707122SEaswaran Raman return Segments; 555dc707122SEaswaran Raman } 556dc707122SEaswaran Raman }; 557e78d131aSEugene Zelenko 558e78d131aSEugene Zelenko } // end anonymous namespace 559dc707122SEaswaran Raman 560dc707122SEaswaran Raman std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const { 561dc707122SEaswaran Raman std::vector<StringRef> Filenames; 562dc707122SEaswaran Raman for (const auto &Function : getCoveredFunctions()) 563dc707122SEaswaran Raman Filenames.insert(Filenames.end(), Function.Filenames.begin(), 564dc707122SEaswaran Raman Function.Filenames.end()); 5650cac726aSFangrui Song llvm::sort(Filenames); 566dc707122SEaswaran Raman auto Last = std::unique(Filenames.begin(), Filenames.end()); 567dc707122SEaswaran Raman Filenames.erase(Last, Filenames.end()); 568dc707122SEaswaran Raman return Filenames; 569dc707122SEaswaran Raman } 570dc707122SEaswaran Raman 571dc707122SEaswaran Raman static SmallBitVector gatherFileIDs(StringRef SourceFile, 572dc707122SEaswaran Raman const FunctionRecord &Function) { 573dc707122SEaswaran Raman SmallBitVector FilenameEquivalence(Function.Filenames.size(), false); 574dc707122SEaswaran Raman for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I) 575dc707122SEaswaran Raman if (SourceFile == Function.Filenames[I]) 576dc707122SEaswaran Raman FilenameEquivalence[I] = true; 577dc707122SEaswaran Raman return FilenameEquivalence; 578dc707122SEaswaran Raman } 579dc707122SEaswaran Raman 580dc707122SEaswaran Raman /// Return the ID of the file where the definition of the function is located. 581dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) { 582dc707122SEaswaran Raman SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true); 583dc707122SEaswaran Raman for (const auto &CR : Function.CountedRegions) 584dc707122SEaswaran Raman if (CR.Kind == CounterMappingRegion::ExpansionRegion) 585dc707122SEaswaran Raman IsNotExpandedFile[CR.ExpandedFileID] = false; 586dc707122SEaswaran Raman int I = IsNotExpandedFile.find_first(); 587dc707122SEaswaran Raman if (I == -1) 588dc707122SEaswaran Raman return None; 589dc707122SEaswaran Raman return I; 590dc707122SEaswaran Raman } 591dc707122SEaswaran Raman 592dc707122SEaswaran Raman /// Check if SourceFile is the file that contains the definition of 593dc707122SEaswaran Raman /// the Function. Return the ID of the file in that case or None otherwise. 594dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(StringRef SourceFile, 595dc707122SEaswaran Raman const FunctionRecord &Function) { 596dc707122SEaswaran Raman Optional<unsigned> I = findMainViewFileID(Function); 597dc707122SEaswaran Raman if (I && SourceFile == Function.Filenames[*I]) 598dc707122SEaswaran Raman return I; 599dc707122SEaswaran Raman return None; 600dc707122SEaswaran Raman } 601dc707122SEaswaran Raman 602dc707122SEaswaran Raman static bool isExpansion(const CountedRegion &R, unsigned FileID) { 603dc707122SEaswaran Raman return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID; 604dc707122SEaswaran Raman } 605dc707122SEaswaran Raman 6067fcc5472SVedant Kumar CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const { 607dc707122SEaswaran Raman CoverageData FileCoverage(Filename); 608e78d131aSEugene Zelenko std::vector<CountedRegion> Regions; 609dc707122SEaswaran Raman 610dc707122SEaswaran Raman for (const auto &Function : Functions) { 611dc707122SEaswaran Raman auto MainFileID = findMainViewFileID(Filename, Function); 612dc707122SEaswaran Raman auto FileIDs = gatherFileIDs(Filename, Function); 613dc707122SEaswaran Raman for (const auto &CR : Function.CountedRegions) 614dc707122SEaswaran Raman if (FileIDs.test(CR.FileID)) { 615dc707122SEaswaran Raman Regions.push_back(CR); 616dc707122SEaswaran Raman if (MainFileID && isExpansion(CR, *MainFileID)) 617dc707122SEaswaran Raman FileCoverage.Expansions.emplace_back(CR, Function); 618dc707122SEaswaran Raman } 619dc707122SEaswaran Raman } 620dc707122SEaswaran Raman 621d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n"); 622dc707122SEaswaran Raman FileCoverage.Segments = SegmentBuilder::buildSegments(Regions); 623dc707122SEaswaran Raman 624dc707122SEaswaran Raman return FileCoverage; 625dc707122SEaswaran Raman } 626dc707122SEaswaran Raman 627dde19c5aSVedant Kumar std::vector<InstantiationGroup> 628dde19c5aSVedant Kumar CoverageMapping::getInstantiationGroups(StringRef Filename) const { 629dc707122SEaswaran Raman FunctionInstantiationSetCollector InstantiationSetCollector; 630dc707122SEaswaran Raman for (const auto &Function : Functions) { 631dc707122SEaswaran Raman auto MainFileID = findMainViewFileID(Filename, Function); 632dc707122SEaswaran Raman if (!MainFileID) 633dc707122SEaswaran Raman continue; 634dc707122SEaswaran Raman InstantiationSetCollector.insert(Function, *MainFileID); 635dc707122SEaswaran Raman } 636dc707122SEaswaran Raman 637dde19c5aSVedant Kumar std::vector<InstantiationGroup> Result; 63824cb28bbSBenjamin Kramer for (auto &InstantiationSet : InstantiationSetCollector) { 639dde19c5aSVedant Kumar InstantiationGroup IG{InstantiationSet.first.first, 640dde19c5aSVedant Kumar InstantiationSet.first.second, 641dde19c5aSVedant Kumar std::move(InstantiationSet.second)}; 642dde19c5aSVedant Kumar Result.emplace_back(std::move(IG)); 643dc707122SEaswaran Raman } 644dc707122SEaswaran Raman return Result; 645dc707122SEaswaran Raman } 646dc707122SEaswaran Raman 647dc707122SEaswaran Raman CoverageData 648f681e2e5SVedant Kumar CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const { 649dc707122SEaswaran Raman auto MainFileID = findMainViewFileID(Function); 650dc707122SEaswaran Raman if (!MainFileID) 651dc707122SEaswaran Raman return CoverageData(); 652dc707122SEaswaran Raman 653dc707122SEaswaran Raman CoverageData FunctionCoverage(Function.Filenames[*MainFileID]); 654e78d131aSEugene Zelenko std::vector<CountedRegion> Regions; 655dc707122SEaswaran Raman for (const auto &CR : Function.CountedRegions) 656dc707122SEaswaran Raman if (CR.FileID == *MainFileID) { 657dc707122SEaswaran Raman Regions.push_back(CR); 658dc707122SEaswaran Raman if (isExpansion(CR, *MainFileID)) 659dc707122SEaswaran Raman FunctionCoverage.Expansions.emplace_back(CR, Function); 660dc707122SEaswaran Raman } 661dc707122SEaswaran Raman 662d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name 663d34e60caSNicola Zaghen << "\n"); 664dc707122SEaswaran Raman FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 665dc707122SEaswaran Raman 666dc707122SEaswaran Raman return FunctionCoverage; 667dc707122SEaswaran Raman } 668dc707122SEaswaran Raman 669f681e2e5SVedant Kumar CoverageData CoverageMapping::getCoverageForExpansion( 670f681e2e5SVedant Kumar const ExpansionRecord &Expansion) const { 671dc707122SEaswaran Raman CoverageData ExpansionCoverage( 672dc707122SEaswaran Raman Expansion.Function.Filenames[Expansion.FileID]); 673e78d131aSEugene Zelenko std::vector<CountedRegion> Regions; 674dc707122SEaswaran Raman for (const auto &CR : Expansion.Function.CountedRegions) 675dc707122SEaswaran Raman if (CR.FileID == Expansion.FileID) { 676dc707122SEaswaran Raman Regions.push_back(CR); 677dc707122SEaswaran Raman if (isExpansion(CR, Expansion.FileID)) 678dc707122SEaswaran Raman ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function); 679dc707122SEaswaran Raman } 680dc707122SEaswaran Raman 681d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file " 682d34e60caSNicola Zaghen << Expansion.FileID << "\n"); 683dc707122SEaswaran Raman ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 684dc707122SEaswaran Raman 685dc707122SEaswaran Raman return ExpansionCoverage; 686dc707122SEaswaran Raman } 687dc707122SEaswaran Raman 688821160d5SVedant Kumar LineCoverageStats::LineCoverageStats( 689f5f153ddSVedant Kumar ArrayRef<const CoverageSegment *> LineSegments, 690f5f153ddSVedant Kumar const CoverageSegment *WrappedSegment, unsigned Line) 691821160d5SVedant Kumar : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line), 692821160d5SVedant Kumar LineSegments(LineSegments), WrappedSegment(WrappedSegment) { 693821160d5SVedant Kumar // Find the minimum number of regions which start in this line. 694821160d5SVedant Kumar unsigned MinRegionCount = 0; 695f5f153ddSVedant Kumar auto isStartOfRegion = [](const CoverageSegment *S) { 696821160d5SVedant Kumar return !S->IsGapRegion && S->HasCount && S->IsRegionEntry; 697821160d5SVedant Kumar }; 698821160d5SVedant Kumar for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I) 699821160d5SVedant Kumar if (isStartOfRegion(LineSegments[I])) 700821160d5SVedant Kumar ++MinRegionCount; 701821160d5SVedant Kumar 702821160d5SVedant Kumar bool StartOfSkippedRegion = !LineSegments.empty() && 703821160d5SVedant Kumar !LineSegments.front()->HasCount && 704821160d5SVedant Kumar LineSegments.front()->IsRegionEntry; 705821160d5SVedant Kumar 706821160d5SVedant Kumar HasMultipleRegions = MinRegionCount > 1; 707821160d5SVedant Kumar Mapped = 708821160d5SVedant Kumar !StartOfSkippedRegion && 709821160d5SVedant Kumar ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0)); 710821160d5SVedant Kumar 711821160d5SVedant Kumar if (!Mapped) 712821160d5SVedant Kumar return; 713821160d5SVedant Kumar 71443247f05SVedant Kumar // Pick the max count from the non-gap, region entry segments and the 71543247f05SVedant Kumar // wrapped count. 71643247f05SVedant Kumar if (WrappedSegment) 717821160d5SVedant Kumar ExecutionCount = WrappedSegment->Count; 71843247f05SVedant Kumar if (!MinRegionCount) 719821160d5SVedant Kumar return; 720821160d5SVedant Kumar for (const auto *LS : LineSegments) 721821160d5SVedant Kumar if (isStartOfRegion(LS)) 722821160d5SVedant Kumar ExecutionCount = std::max(ExecutionCount, LS->Count); 723821160d5SVedant Kumar } 724821160d5SVedant Kumar 725821160d5SVedant Kumar LineCoverageIterator &LineCoverageIterator::operator++() { 726821160d5SVedant Kumar if (Next == CD.end()) { 727821160d5SVedant Kumar Stats = LineCoverageStats(); 728821160d5SVedant Kumar Ended = true; 729821160d5SVedant Kumar return *this; 730821160d5SVedant Kumar } 731821160d5SVedant Kumar if (Segments.size()) 732821160d5SVedant Kumar WrappedSegment = Segments.back(); 733821160d5SVedant Kumar Segments.clear(); 734821160d5SVedant Kumar while (Next != CD.end() && Next->Line == Line) 735821160d5SVedant Kumar Segments.push_back(&*Next++); 736821160d5SVedant Kumar Stats = LineCoverageStats(Segments, WrappedSegment, Line); 737821160d5SVedant Kumar ++Line; 738821160d5SVedant Kumar return *this; 739821160d5SVedant Kumar } 740821160d5SVedant Kumar 741e78d131aSEugene Zelenko static std::string getCoverageMapErrString(coveragemap_error Err) { 7429152fd17SVedant Kumar switch (Err) { 743dc707122SEaswaran Raman case coveragemap_error::success: 744dc707122SEaswaran Raman return "Success"; 745dc707122SEaswaran Raman case coveragemap_error::eof: 746dc707122SEaswaran Raman return "End of File"; 747dc707122SEaswaran Raman case coveragemap_error::no_data_found: 748dc707122SEaswaran Raman return "No coverage data found"; 749dc707122SEaswaran Raman case coveragemap_error::unsupported_version: 750dc707122SEaswaran Raman return "Unsupported coverage format version"; 751dc707122SEaswaran Raman case coveragemap_error::truncated: 752dc707122SEaswaran Raman return "Truncated coverage data"; 753dc707122SEaswaran Raman case coveragemap_error::malformed: 754dc707122SEaswaran Raman return "Malformed coverage data"; 755dc707122SEaswaran Raman } 756dc707122SEaswaran Raman llvm_unreachable("A value of coveragemap_error has no message."); 757dc707122SEaswaran Raman } 7589152fd17SVedant Kumar 759e78d131aSEugene Zelenko namespace { 760e78d131aSEugene Zelenko 7614718f8b5SPeter Collingbourne // FIXME: This class is only here to support the transition to llvm::Error. It 7624718f8b5SPeter Collingbourne // will be removed once this transition is complete. Clients should prefer to 7634718f8b5SPeter Collingbourne // deal with the Error value directly, rather than converting to error_code. 7649152fd17SVedant Kumar class CoverageMappingErrorCategoryType : public std::error_category { 765990504e6SReid Kleckner const char *name() const noexcept override { return "llvm.coveragemap"; } 7669152fd17SVedant Kumar std::string message(int IE) const override { 7679152fd17SVedant Kumar return getCoverageMapErrString(static_cast<coveragemap_error>(IE)); 7689152fd17SVedant Kumar } 769dc707122SEaswaran Raman }; 770e78d131aSEugene Zelenko 7719152fd17SVedant Kumar } // end anonymous namespace 7729152fd17SVedant Kumar 7739152fd17SVedant Kumar std::string CoverageMapError::message() const { 7749152fd17SVedant Kumar return getCoverageMapErrString(Err); 775dc707122SEaswaran Raman } 776dc707122SEaswaran Raman 777dc707122SEaswaran Raman static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory; 778dc707122SEaswaran Raman 779dc707122SEaswaran Raman const std::error_category &llvm::coverage::coveragemap_category() { 780dc707122SEaswaran Raman return *ErrorCategory; 781dc707122SEaswaran Raman } 7829152fd17SVedant Kumar 7839152fd17SVedant Kumar char CoverageMapError::ID = 0; 784