LCOV - code coverage report
Current view: top level - lib/ProfileData/Coverage - CoverageMapping.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 289 314 92.0 %
Date: 2018-10-20 13:21:21 Functions: 29 33 87.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file contains support for clang's and llvm's instrumentation based
      11             : // code coverage.
      12             : //
      13             : //===----------------------------------------------------------------------===//
      14             : 
      15             : #include "llvm/ProfileData/Coverage/CoverageMapping.h"
      16             : #include "llvm/ADT/ArrayRef.h"
      17             : #include "llvm/ADT/DenseMap.h"
      18             : #include "llvm/ADT/None.h"
      19             : #include "llvm/ADT/Optional.h"
      20             : #include "llvm/ADT/SmallBitVector.h"
      21             : #include "llvm/ADT/SmallVector.h"
      22             : #include "llvm/ADT/StringRef.h"
      23             : #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
      24             : #include "llvm/ProfileData/InstrProfReader.h"
      25             : #include "llvm/Support/Debug.h"
      26             : #include "llvm/Support/Errc.h"
      27             : #include "llvm/Support/Error.h"
      28             : #include "llvm/Support/ErrorHandling.h"
      29             : #include "llvm/Support/ManagedStatic.h"
      30             : #include "llvm/Support/MemoryBuffer.h"
      31             : #include "llvm/Support/raw_ostream.h"
      32             : #include <algorithm>
      33             : #include <cassert>
      34             : #include <cstdint>
      35             : #include <iterator>
      36             : #include <map>
      37             : #include <memory>
      38             : #include <string>
      39             : #include <system_error>
      40             : #include <utility>
      41             : #include <vector>
      42             : 
      43             : using namespace llvm;
      44             : using namespace coverage;
      45             : 
      46             : #define DEBUG_TYPE "coverage-mapping"
      47             : 
      48        1169 : Counter CounterExpressionBuilder::get(const CounterExpression &E) {
      49        1169 :   auto It = ExpressionIndices.find(E);
      50        1169 :   if (It != ExpressionIndices.end())
      51         557 :     return Counter::getExpression(It->second);
      52         612 :   unsigned I = Expressions.size();
      53         612 :   Expressions.push_back(E);
      54         612 :   ExpressionIndices[E] = I;
      55             :   return Counter::getExpression(I);
      56             : }
      57             : 
      58        2831 : void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
      59             :                                             SmallVectorImpl<Term> &Terms) {
      60        2831 :   switch (C.getKind()) {
      61             :   case Counter::Zero:
      62             :     break;
      63        1400 :   case Counter::CounterValueReference:
      64        1400 :     Terms.emplace_back(C.getCounterID(), Factor);
      65        1400 :     break;
      66        1090 :   case Counter::Expression:
      67        1090 :     const auto &E = Expressions[C.getExpressionID()];
      68        1090 :     extractTerms(E.LHS, Factor, Terms);
      69        1090 :     extractTerms(
      70        1090 :         E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
      71        1090 :     break;
      72             :   }
      73        2831 : }
      74             : 
      75         651 : Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
      76             :   // Gather constant terms.
      77             :   SmallVector<Term, 32> Terms;
      78         651 :   extractTerms(ExpressionTree, +1, Terms);
      79             : 
      80             :   // If there are no terms, this is just a zero. The algorithm below assumes at
      81             :   // least one term.
      82        1302 :   if (Terms.size() == 0)
      83             :     return Counter::getZero();
      84             : 
      85             :   // Group the terms by counter ID.
      86             :   llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
      87           0 :     return LHS.CounterID < RHS.CounterID;
      88             :   });
      89             : 
      90             :   // Combine terms by counter ID to eliminate counters that sum to zero.
      91             :   auto Prev = Terms.begin();
      92        1400 :   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
      93         785 :     if (I->CounterID == Prev->CounterID) {
      94         140 :       Prev->Factor += I->Factor;
      95         140 :       continue;
      96             :     }
      97         645 :     ++Prev;
      98         645 :     *Prev = *I;
      99             :   }
     100         615 :   Terms.erase(++Prev, Terms.end());
     101             : 
     102             :   Counter C;
     103             :   // Create additions. We do this before subtractions to avoid constructs like
     104             :   // ((0 - X) + Y), as opposed to (Y - X).
     105        1875 :   for (auto T : Terms) {
     106        1260 :     if (T.Factor <= 0)
     107             :       continue;
     108        1652 :     for (int I = 0; I < T.Factor; ++I)
     109         828 :       if (C.isZero())
     110             :         C = Counter::getCounter(T.CounterID);
     111             :       else
     112         214 :         C = get(CounterExpression(CounterExpression::Add, C,
     113         214 :                                   Counter::getCounter(T.CounterID)));
     114             :   }
     115             : 
     116             :   // Create subtractions.
     117        1875 :   for (auto T : Terms) {
     118        1260 :     if (T.Factor >= 0)
     119             :       continue;
     120         608 :     for (int I = 0; I < -T.Factor; ++I)
     121         304 :       C = get(CounterExpression(CounterExpression::Subtract, C,
     122         304 :                                 Counter::getCounter(T.CounterID)));
     123             :   }
     124         615 :   return C;
     125             : }
     126             : 
     127         458 : Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
     128         458 :   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
     129             : }
     130             : 
     131         193 : Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
     132             :   return simplify(
     133         193 :       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
     134             : }
     135             : 
     136        1814 : void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
     137        1814 :   switch (C.getKind()) {
     138             :   case Counter::Zero:
     139             :     OS << '0';
     140        1814 :     return;
     141             :   case Counter::CounterValueReference:
     142        1440 :     OS << '#' << C.getCounterID();
     143             :     break;
     144         318 :   case Counter::Expression: {
     145         318 :     if (C.getExpressionID() >= Expressions.size())
     146             :       return;
     147         318 :     const auto &E = Expressions[C.getExpressionID()];
     148             :     OS << '(';
     149         318 :     dump(E.LHS, OS);
     150         420 :     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
     151         318 :     dump(E.RHS, OS);
     152             :     OS << ')';
     153             :     break;
     154             :   }
     155             :   }
     156        1758 :   if (CounterValues.empty())
     157             :     return;
     158           0 :   Expected<int64_t> Value = evaluate(C);
     159           0 :   if (auto E = Value.takeError()) {
     160           0 :     consumeError(std::move(E));
     161             :     return;
     162             :   }
     163           0 :   OS << '[' << *Value << ']';
     164             : }
     165             : 
     166        3082 : Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
     167        3082 :   switch (C.getKind()) {
     168          92 :   case Counter::Zero:
     169             :     return 0;
     170        2489 :   case Counter::CounterValueReference:
     171        2489 :     if (C.getCounterID() >= CounterValues.size())
     172           0 :       return errorCodeToError(errc::argument_out_of_domain);
     173        2489 :     return CounterValues[C.getCounterID()];
     174         501 :   case Counter::Expression: {
     175         501 :     if (C.getExpressionID() >= Expressions.size())
     176           0 :       return errorCodeToError(errc::argument_out_of_domain);
     177         501 :     const auto &E = Expressions[C.getExpressionID()];
     178         501 :     Expected<int64_t> LHS = evaluate(E.LHS);
     179         501 :     if (!LHS)
     180             :       return LHS;
     181         501 :     Expected<int64_t> RHS = evaluate(E.RHS);
     182         501 :     if (!RHS)
     183             :       return RHS;
     184         501 :     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
     185             :   }
     186             :   }
     187           0 :   llvm_unreachable("Unhandled CounterKind");
     188             : }
     189             : 
     190        1157 : void FunctionRecordIterator::skipOtherFiles() {
     191        2370 :   while (Current != Records.end() && !Filename.empty() &&
     192         104 :          Filename != Current->Filenames[0])
     193          28 :     ++Current;
     194        1157 :   if (Current == Records.end())
     195         258 :     *this = FunctionRecordIterator();
     196        1157 : }
     197             : 
     198         499 : Error CoverageMapping::loadFunctionRecord(
     199             :     const CoverageMappingRecord &Record,
     200             :     IndexedInstrProfReader &ProfileReader) {
     201         499 :   StringRef OrigFuncName = Record.FunctionName;
     202         499 :   if (OrigFuncName.empty())
     203             :     return make_error<CoverageMapError>(coveragemap_error::malformed);
     204             : 
     205         495 :   if (Record.Filenames.empty())
     206           4 :     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
     207             :   else
     208         491 :     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
     209             : 
     210             :   CounterMappingContext Ctx(Record.Expressions);
     211             : 
     212             :   std::vector<uint64_t> Counts;
     213         495 :   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
     214         495 :                                                 Record.FunctionHash, Counts)) {
     215          44 :     instrprof_error IPE = InstrProfError::take(std::move(E));
     216          44 :     if (IPE == instrprof_error::hash_mismatch) {
     217           1 :       FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash);
     218             :       return Error::success();
     219          43 :     } else if (IPE != instrprof_error::unknown_function)
     220             :       return make_error<InstrProfError>(IPE);
     221          43 :     Counts.assign(Record.MappingRegions.size(), 0);
     222             :   }
     223             :   Ctx.setCounts(Counts);
     224             : 
     225             :   assert(!Record.MappingRegions.empty() && "Function has no regions");
     226             : 
     227             :   // This coverage record is a zero region for a function that's unused in
     228             :   // some TU, but used in a different TU. Ignore it. The coverage maps from the
     229             :   // the other TU will either be loaded (providing full region counts) or they
     230             :   // won't (in which case we don't unintuitively report functions as uncovered
     231             :   // when they have non-zero counts in the profile).
     232         693 :   if (Record.MappingRegions.size() == 1 &&
     233         494 :       Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
     234             :     return Error::success();
     235             : 
     236         988 :   FunctionRecord Function(OrigFuncName, Record.Filenames);
     237        2574 :   for (const auto &Region : Record.MappingRegions) {
     238        2080 :     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
     239        2080 :     if (auto E = ExecutionCount.takeError()) {
     240           0 :       consumeError(std::move(E));
     241             :       return Error::success();
     242             :     }
     243        4160 :     Function.pushRegion(Region, *ExecutionCount);
     244             :   }
     245             : 
     246             :   // Don't create records for (filenames, function) pairs we've already seen.
     247             :   auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
     248         494 :                                           Record.Filenames.end());
     249         494 :   if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
     250             :     return Error::success();
     251             : 
     252         486 :   Functions.push_back(std::move(Function));
     253             :   return Error::success();
     254             : }
     255             : 
     256         204 : Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
     257             :     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
     258             :     IndexedInstrProfReader &ProfileReader) {
     259         408 :   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
     260             : 
     261         418 :   for (const auto &CoverageReader : CoverageReaders) {
     262         714 :     for (auto RecordOrErr : *CoverageReader) {
     263         500 :       if (Error E = RecordOrErr.takeError())
     264             :         return std::move(E);
     265             :       const auto &Record = *RecordOrErr;
     266         998 :       if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
     267             :         return std::move(E);
     268             :     }
     269             :   }
     270             : 
     271             :   return std::move(Coverage);
     272             : }
     273             : 
     274             : Expected<std::unique_ptr<CoverageMapping>>
     275         105 : CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
     276             :                       StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
     277         210 :   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
     278         105 :   if (Error E = ProfileReaderOrErr.takeError())
     279             :     return std::move(E);
     280             :   auto ProfileReader = std::move(ProfileReaderOrErr.get());
     281             : 
     282         105 :   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
     283         105 :   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
     284         212 :   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
     285         108 :     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
     286         108 :     if (std::error_code EC = CovMappingBufOrErr.getError())
     287           0 :       return errorCodeToError(EC);
     288         108 :     StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
     289             :     auto CoverageReaderOrErr =
     290         215 :         BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
     291         108 :     if (Error E = CoverageReaderOrErr.takeError())
     292             :       return std::move(E);
     293         107 :     Readers.push_back(std::move(CoverageReaderOrErr.get()));
     294         107 :     Buffers.push_back(std::move(CovMappingBufOrErr.get()));
     295             :   }
     296         104 :   return load(Readers, *ProfileReader);
     297             : }
     298             : 
     299             : namespace {
     300             : 
     301             : /// Distributes functions into instantiation sets.
     302             : ///
     303             : /// An instantiation set is a collection of functions that have the same source
     304             : /// code, ie, template functions specializations.
     305             : class FunctionInstantiationSetCollector {
     306             :   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
     307             :   MapT InstantiatedFunctions;
     308             : 
     309             : public:
     310         354 :   void insert(const FunctionRecord &Function, unsigned FileID) {
     311         354 :     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
     312         354 :     while (I != E && I->FileID != FileID)
     313             :       ++I;
     314             :     assert(I != E && "function does not cover the given file");
     315         354 :     auto &Functions = InstantiatedFunctions[I->startLoc()];
     316         354 :     Functions.push_back(&Function);
     317         354 :   }
     318             : 
     319             :   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
     320             :   MapT::iterator end() { return InstantiatedFunctions.end(); }
     321             : };
     322             : 
     323             : class SegmentBuilder {
     324             :   std::vector<CoverageSegment> &Segments;
     325             :   SmallVector<const CountedRegion *, 8> ActiveRegions;
     326             : 
     327         490 :   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
     328             : 
     329             :   /// Emit a segment with the count from \p Region starting at \p StartLoc.
     330             :   //
     331             :   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
     332             :   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
     333        3934 :   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
     334             :                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
     335        3934 :     bool HasCount = !EmitSkippedRegion &&
     336        3399 :                     (Region.Kind != CounterMappingRegion::SkippedRegion);
     337             : 
     338             :     // If the new segment wouldn't affect coverage rendering, skip it.
     339        7868 :     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
     340             :       const auto &Last = Segments.back();
     341        1531 :       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
     342         519 :           !Last.IsRegionEntry)
     343             :         return;
     344             :     }
     345             : 
     346        3838 :     if (HasCount)
     347        3295 :       Segments.emplace_back(StartLoc.first, StartLoc.second,
     348        3295 :                             Region.ExecutionCount, IsRegionEntry,
     349        3295 :                             Region.Kind == CounterMappingRegion::GapRegion);
     350             :     else
     351         543 :       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
     352             : 
     353             :     LLVM_DEBUG({
     354             :       const auto &Last = Segments.back();
     355             :       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
     356             :              << " (count = " << Last.Count << ")"
     357             :              << (Last.IsRegionEntry ? ", RegionEntry" : "")
     358             :              << (!Last.HasCount ? ", Skipped" : "")
     359             :              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
     360             :     });
     361             :   }
     362             : 
     363             :   /// Emit segments for active regions which end before \p Loc.
     364             :   ///
     365             :   /// \p Loc: The start location of the next region. If None, all active
     366             :   /// regions are completed.
     367             :   /// \p FirstCompletedRegion: Index of the first completed region.
     368        2030 :   void completeRegionsUntil(Optional<LineColPair> Loc,
     369             :                             unsigned FirstCompletedRegion) {
     370             :     // Sort the completed regions by end location. This makes it simple to
     371             :     // emit closing segments in sorted order.
     372        2030 :     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
     373             :     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
     374             :                       [](const CountedRegion *L, const CountedRegion *R) {
     375             :                         return L->endLoc() < R->endLoc();
     376             :                       });
     377             : 
     378             :     // Emit segments for all completed regions.
     379        2463 :     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
     380             :          ++I) {
     381         437 :       const auto *CompletedRegion = ActiveRegions[I];
     382             :       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
     383             :              "Completed region ends after start of new region");
     384             : 
     385         874 :       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
     386             :       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
     387             : 
     388             :       // Don't emit any more segments if they start where the new region begins.
     389         437 :       if (Loc && CompletedSegmentLoc == *Loc)
     390             :         break;
     391             : 
     392             :       // Don't emit a segment if the next completed region ends at the same
     393             :       // location as this one.
     394             :       if (CompletedSegmentLoc == CompletedRegion->endLoc())
     395             :         continue;
     396             : 
     397             :       // Use the count from the last completed region which ends at this loc.
     398         317 :       for (unsigned J = I + 1; J < E; ++J)
     399         162 :         if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
     400             :           CompletedRegion = ActiveRegions[J];
     401             : 
     402         236 :       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
     403             :     }
     404             : 
     405        2030 :     auto Last = ActiveRegions.back();
     406        2030 :     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
     407             :       // If there's a gap after the end of the last completed region and the
     408             :       // start of the new region, use the last active region to fill the gap.
     409        1416 :       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
     410             :                    false);
     411        1322 :     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
     412             :       // Emit a skipped segment if there are no more active regions. This
     413             :       // ensures that gaps between functions are marked correctly.
     414         519 :       startSegment(*Last, Last->endLoc(), false, true);
     415             :     }
     416             : 
     417             :     // Pop the completed regions.
     418        4060 :     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
     419        2030 :   }
     420             : 
     421         490 :   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
     422        2981 :     for (const auto &CR : enumerate(Regions)) {
     423        2491 :       auto CurStartLoc = CR.value().startLoc();
     424             : 
     425             :       // Active regions which end before the current region need to be popped.
     426             :       auto CompletedRegions =
     427             :           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
     428             :                                 [&](const CountedRegion *Region) {
     429             :                                   return !(Region->endLoc() <= CurStartLoc);
     430             :                                 });
     431        2491 :       if (CompletedRegions != ActiveRegions.end()) {
     432             :         unsigned FirstCompletedRegion =
     433        1556 :             std::distance(ActiveRegions.begin(), CompletedRegions);
     434        1556 :         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
     435             :       }
     436             : 
     437        2491 :       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
     438             : 
     439             :       // Try to emit a segment for the current region.
     440        2491 :       if (CurStartLoc == CR.value().endLoc()) {
     441             :         // Avoid making zero-length regions active. If it's the last region,
     442             :         // emit a skipped segment. Otherwise use its predecessor's count.
     443          20 :         const bool Skipped = (CR.index() + 1) == Regions.size();
     444          20 :         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
     445          20 :                      CurStartLoc, !GapRegion, Skipped);
     446          20 :         continue;
     447             :       }
     448        2471 :       if (CR.index() + 1 == Regions.size() ||
     449        1997 :           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
     450             :         // Emit a segment if the next region doesn't start at the same location
     451             :         // as this one.
     452        2451 :         startSegment(CR.value(), CurStartLoc, !GapRegion);
     453             :       }
     454             : 
     455             :       // This region is active (i.e not completed).
     456        2471 :       ActiveRegions.push_back(&CR.value());
     457             :     }
     458             : 
     459             :     // Complete any remaining active regions.
     460         490 :     if (!ActiveRegions.empty())
     461         474 :       completeRegionsUntil(None, 0);
     462         490 :   }
     463             : 
     464             :   /// Sort a nested sequence of regions from a single file.
     465             :   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
     466             :     llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
     467             :       if (LHS.startLoc() != RHS.startLoc())
     468             :         return LHS.startLoc() < RHS.startLoc();
     469             :       if (LHS.endLoc() != RHS.endLoc())
     470             :         // When LHS completely contains RHS, we sort LHS first.
     471             :         return RHS.endLoc() < LHS.endLoc();
     472             :       // If LHS and RHS cover the same area, we need to sort them according
     473             :       // to their kinds so that the most suitable region will become "active"
     474             :       // in combineRegions(). Because we accumulate counter values only from
     475             :       // regions of the same kind as the first region of the area, prefer
     476             :       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
     477             :       static_assert(CounterMappingRegion::CodeRegion <
     478             :                             CounterMappingRegion::ExpansionRegion &&
     479             :                         CounterMappingRegion::ExpansionRegion <
     480             :                             CounterMappingRegion::SkippedRegion,
     481             :                     "Unexpected order of region kind values");
     482             :       return LHS.Kind < RHS.Kind;
     483             :     });
     484             :   }
     485             : 
     486             :   /// Combine counts of regions which cover the same area.
     487             :   static ArrayRef<CountedRegion>
     488         490 :   combineRegions(MutableArrayRef<CountedRegion> Regions) {
     489         490 :     if (Regions.empty())
     490           0 :       return Regions;
     491             :     auto Active = Regions.begin();
     492             :     auto End = Regions.end();
     493        2835 :     for (auto I = Regions.begin() + 1; I != End; ++I) {
     494             :       if (Active->startLoc() != I->startLoc() ||
     495             :           Active->endLoc() != I->endLoc()) {
     496             :         // Shift to the next region.
     497        2001 :         ++Active;
     498        2001 :         if (Active != I)
     499         228 :           *Active = *I;
     500        2001 :         continue;
     501             :       }
     502             :       // Merge duplicate region.
     503             :       // If CodeRegions and ExpansionRegions cover the same area, it's probably
     504             :       // a macro which is fully expanded to another macro. In that case, we need
     505             :       // to accumulate counts only from CodeRegions, or else the area will be
     506             :       // counted twice.
     507             :       // On the other hand, a macro may have a nested macro in its body. If the
     508             :       // outer macro is used several times, the ExpansionRegion for the nested
     509             :       // macro will also be added several times. These ExpansionRegions cover
     510             :       // the same source locations and have to be combined to reach the correct
     511             :       // value for that area.
     512             :       // We add counts of the regions of the same kind as the active region
     513             :       // to handle the both situations.
     514         344 :       if (I->Kind == Active->Kind)
     515         340 :         Active->ExecutionCount += I->ExecutionCount;
     516             :     }
     517        1470 :     return Regions.drop_back(std::distance(++Active, End));
     518             :   }
     519             : 
     520             : public:
     521             :   /// Build a sorted list of CoverageSegments from a list of Regions.
     522             :   static std::vector<CoverageSegment>
     523         490 :   buildSegments(MutableArrayRef<CountedRegion> Regions) {
     524             :     std::vector<CoverageSegment> Segments;
     525             :     SegmentBuilder Builder(Segments);
     526             : 
     527             :     sortNestedRegions(Regions);
     528         490 :     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
     529             : 
     530             :     LLVM_DEBUG({
     531             :       dbgs() << "Combined regions:\n";
     532             :       for (const auto &CR : CombinedRegions)
     533             :         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
     534             :                << CR.LineEnd << ":" << CR.ColumnEnd
     535             :                << " (count=" << CR.ExecutionCount << ")\n";
     536             :     });
     537             : 
     538         490 :     Builder.buildSegmentsImpl(CombinedRegions);
     539             : 
     540             : #ifndef NDEBUG
     541             :     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
     542             :       const auto &L = Segments[I - 1];
     543             :       const auto &R = Segments[I];
     544             :       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
     545             :         LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
     546             :                           << " followed by " << R.Line << ":" << R.Col << "\n");
     547             :         assert(false && "Coverage segments not unique or sorted");
     548             :       }
     549             :     }
     550             : #endif
     551             : 
     552         490 :     return Segments;
     553             :   }
     554             : };
     555             : 
     556             : } // end anonymous namespace
     557             : 
     558         194 : std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
     559             :   std::vector<StringRef> Filenames;
     560        1095 :   for (const auto &Function : getCoveredFunctions())
     561             :     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
     562        1414 :                      Function.Filenames.end());
     563             :   llvm::sort(Filenames);
     564         194 :   auto Last = std::unique(Filenames.begin(), Filenames.end());
     565             :   Filenames.erase(Last, Filenames.end());
     566         194 :   return Filenames;
     567             : }
     568             : 
     569         872 : static SmallBitVector gatherFileIDs(StringRef SourceFile,
     570             :                                     const FunctionRecord &Function) {
     571        1744 :   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
     572        2668 :   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
     573         924 :     if (SourceFile == Function.Filenames[I])
     574         247 :       FilenameEquivalence[I] = true;
     575         872 :   return FilenameEquivalence;
     576             : }
     577             : 
     578             : /// Return the ID of the file where the definition of the function is located.
     579        2709 : static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
     580        8127 :   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
     581       17406 :   for (const auto &CR : Function.CountedRegions)
     582       14697 :     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
     583          65 :       IsNotExpandedFile[CR.ExpandedFileID] = false;
     584        2709 :   int I = IsNotExpandedFile.find_first();
     585        2709 :   if (I == -1)
     586             :     return None;
     587        2709 :   return I;
     588             : }
     589             : 
     590             : /// Check if SourceFile is the file that contains the definition of
     591             : /// the Function. Return the ID of the file in that case or None otherwise.
     592        2392 : static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
     593             :                                              const FunctionRecord &Function) {
     594        2392 :   Optional<unsigned> I = findMainViewFileID(Function);
     595        2392 :   if (I && SourceFile == Function.Filenames[*I])
     596             :     return I;
     597             :   return None;
     598             : }
     599             : 
     600           0 : static bool isExpansion(const CountedRegion &R, unsigned FileID) {
     601          31 :   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
     602             : }
     603             : 
     604         170 : CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
     605         170 :   CoverageData FileCoverage(Filename);
     606             :   std::vector<CountedRegion> Regions;
     607             : 
     608        1042 :   for (const auto &Function : Functions) {
     609         872 :     auto MainFileID = findMainViewFileID(Filename, Function);
     610        1744 :     auto FileIDs = gatherFileIDs(Filename, Function);
     611        5833 :     for (const auto &CR : Function.CountedRegions)
     612        9922 :       if (FileIDs.test(CR.FileID)) {
     613        1252 :         Regions.push_back(CR);
     614        1252 :         if (MainFileID && isExpansion(CR, *MainFileID))
     615          16 :           FileCoverage.Expansions.emplace_back(CR, Function);
     616             :       }
     617             :   }
     618             : 
     619             :   LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
     620         340 :   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
     621             : 
     622         170 :   return FileCoverage;
     623             : }
     624             : 
     625             : std::vector<InstantiationGroup>
     626         235 : CoverageMapping::getInstantiationGroups(StringRef Filename) const {
     627             :   FunctionInstantiationSetCollector InstantiationSetCollector;
     628        1755 :   for (const auto &Function : Functions) {
     629        1520 :     auto MainFileID = findMainViewFileID(Filename, Function);
     630        1520 :     if (!MainFileID)
     631             :       continue;
     632         354 :     InstantiationSetCollector.insert(Function, *MainFileID);
     633             :   }
     634             : 
     635             :   std::vector<InstantiationGroup> Result;
     636         519 :   for (auto &InstantiationSet : InstantiationSetCollector) {
     637         284 :     InstantiationGroup IG{InstantiationSet.first.first,
     638         284 :                           InstantiationSet.first.second,
     639             :                           std::move(InstantiationSet.second)};
     640         284 :     Result.emplace_back(std::move(IG));
     641             :   }
     642         235 :   return Result;
     643             : }
     644             : 
     645             : CoverageData
     646         317 : CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
     647         317 :   auto MainFileID = findMainViewFileID(Function);
     648         317 :   if (!MainFileID)
     649           0 :     return CoverageData();
     650             : 
     651         951 :   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
     652             :   std::vector<CountedRegion> Regions;
     653        1918 :   for (const auto &CR : Function.CountedRegions)
     654        1601 :     if (CR.FileID == *MainFileID) {
     655        1571 :       Regions.push_back(CR);
     656        1571 :       if (isExpansion(CR, *MainFileID))
     657           7 :         FunctionCoverage.Expansions.emplace_back(CR, Function);
     658             :     }
     659             : 
     660             :   LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
     661             :                     << "\n");
     662         317 :   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
     663             : 
     664         317 :   return FunctionCoverage;
     665             : }
     666             : 
     667           3 : CoverageData CoverageMapping::getCoverageForExpansion(
     668             :     const ExpansionRecord &Expansion) const {
     669             :   CoverageData ExpansionCoverage(
     670           6 :       Expansion.Function.Filenames[Expansion.FileID]);
     671             :   std::vector<CountedRegion> Regions;
     672          51 :   for (const auto &CR : Expansion.Function.CountedRegions)
     673          48 :     if (CR.FileID == Expansion.FileID) {
     674          12 :       Regions.push_back(CR);
     675          12 :       if (isExpansion(CR, Expansion.FileID))
     676           2 :         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
     677             :     }
     678             : 
     679             :   LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
     680             :                     << Expansion.FileID << "\n");
     681           6 :   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
     682             : 
     683           3 :   return ExpansionCoverage;
     684             : }
     685             : 
     686        3830 : LineCoverageStats::LineCoverageStats(
     687             :     ArrayRef<const CoverageSegment *> LineSegments,
     688        3830 :     const CoverageSegment *WrappedSegment, unsigned Line)
     689             :     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
     690        3830 :       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
     691             :   // Find the minimum number of regions which start in this line.
     692             :   unsigned MinRegionCount = 0;
     693             :   auto isStartOfRegion = [](const CoverageSegment *S) {
     694        4881 :     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
     695             :   };
     696        6819 :   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
     697        2989 :     if (isStartOfRegion(LineSegments[I]))
     698        1494 :       ++MinRegionCount;
     699             : 
     700        1851 :   bool StartOfSkippedRegion = !LineSegments.empty() &&
     701        3830 :                               !LineSegments.front()->HasCount &&
     702         370 :                               LineSegments.front()->IsRegionEntry;
     703             : 
     704        3830 :   HasMultipleRegions = MinRegionCount > 1;
     705        3830 :   Mapped =
     706        3830 :       !StartOfSkippedRegion &&
     707        3826 :       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
     708             : 
     709        3830 :   if (!Mapped)
     710             :     return;
     711             : 
     712             :   // Pick the max count from the non-gap, region entry segments and the
     713             :   // wrapped count.
     714        2903 :   if (WrappedSegment)
     715        2524 :     ExecutionCount = WrappedSegment->Count;
     716        2903 :   if (!MinRegionCount)
     717             :     return;
     718        3959 :   for (const auto *LS : LineSegments)
     719             :     if (isStartOfRegion(LS))
     720        2113 :       ExecutionCount = std::max(ExecutionCount, LS->Count);
     721             : }
     722             : 
     723        4993 : LineCoverageIterator &LineCoverageIterator::operator++() {
     724        9986 :   if (Next == CD.end()) {
     725        1163 :     Stats = LineCoverageStats();
     726        1163 :     Ended = true;
     727        1163 :     return *this;
     728             :   }
     729        7660 :   if (Segments.size())
     730        1474 :     WrappedSegment = Segments.back();
     731             :   Segments.clear();
     732       14300 :   while (Next != CD.end() && Next->Line == Line)
     733        6640 :     Segments.push_back(&*Next++);
     734        7660 :   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
     735        3830 :   ++Line;
     736        3830 :   return *this;
     737             : }
     738             : 
     739           5 : static std::string getCoverageMapErrString(coveragemap_error Err) {
     740           5 :   switch (Err) {
     741             :   case coveragemap_error::success:
     742           0 :     return "Success";
     743             :   case coveragemap_error::eof:
     744           0 :     return "End of File";
     745             :   case coveragemap_error::no_data_found:
     746           0 :     return "No coverage data found";
     747             :   case coveragemap_error::unsupported_version:
     748           0 :     return "Unsupported coverage format version";
     749             :   case coveragemap_error::truncated:
     750           0 :     return "Truncated coverage data";
     751             :   case coveragemap_error::malformed:
     752           5 :     return "Malformed coverage data";
     753             :   }
     754           0 :   llvm_unreachable("A value of coveragemap_error has no message.");
     755             : }
     756             : 
     757             : namespace {
     758             : 
     759             : // FIXME: This class is only here to support the transition to llvm::Error. It
     760             : // will be removed once this transition is complete. Clients should prefer to
     761             : // deal with the Error value directly, rather than converting to error_code.
     762           0 : class CoverageMappingErrorCategoryType : public std::error_category {
     763           0 :   const char *name() const noexcept override { return "llvm.coveragemap"; }
     764           0 :   std::string message(int IE) const override {
     765           0 :     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
     766             :   }
     767             : };
     768             : 
     769             : } // end anonymous namespace
     770             : 
     771           5 : std::string CoverageMapError::message() const {
     772           5 :   return getCoverageMapErrString(Err);
     773             : }
     774             : 
     775             : static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
     776             : 
     777           0 : const std::error_category &llvm::coverage::coveragemap_category() {
     778           0 :   return *ErrorCategory;
     779             : }
     780             : 
     781             : char CoverageMapError::ID = 0;

Generated by: LCOV version 1.13