LCOV - code coverage report
Current view: top level - lib/ProfileData/Coverage - CoverageMapping.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 308 338 91.1 %
Date: 2017-09-14 15:23:50 Functions: 28 33 84.8 %
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 <memory>
      37             : #include <string>
      38             : #include <system_error>
      39             : #include <utility>
      40             : #include <vector>
      41             : 
      42             : using namespace llvm;
      43             : using namespace coverage;
      44             : 
      45             : #define DEBUG_TYPE "coverage-mapping"
      46             : 
      47        1025 : Counter CounterExpressionBuilder::get(const CounterExpression &E) {
      48        1025 :   auto It = ExpressionIndices.find(E);
      49        3075 :   if (It != ExpressionIndices.end())
      50         464 :     return Counter::getExpression(It->second);
      51        1122 :   unsigned I = Expressions.size();
      52         561 :   Expressions.push_back(E);
      53        1122 :   ExpressionIndices[E] = I;
      54             :   return Counter::getExpression(I);
      55             : }
      56             : 
      57        2466 : void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
      58             :                                             SmallVectorImpl<Term> &Terms) {
      59        2466 :   switch (C.getKind()) {
      60             :   case Counter::Zero:
      61             :     break;
      62        1277 :   case Counter::CounterValueReference:
      63        1277 :     Terms.emplace_back(C.getCounterID(), Factor);
      64        1277 :     break;
      65         953 :   case Counter::Expression:
      66        1906 :     const auto &E = Expressions[C.getExpressionID()];
      67         953 :     extractTerms(E.LHS, Factor, Terms);
      68        1369 :     extractTerms(
      69        1369 :         E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
      70         953 :     break;
      71             :   }
      72        2466 : }
      73             : 
      74         560 : Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
      75             :   // Gather constant terms.
      76        1120 :   SmallVector<Term, 32> Terms;
      77         560 :   extractTerms(ExpressionTree, +1, Terms);
      78             : 
      79             :   // If there are no terms, this is just a zero. The algorithm below assumes at
      80             :   // least one term.
      81         560 :   if (Terms.size() == 0)
      82             :     return Counter::getZero();
      83             : 
      84             :   // Group the terms by counter ID.
      85        1110 :   std::sort(Terms.begin(), Terms.end(), [](const Term &LHS, const Term &RHS) {
      86             :     return LHS.CounterID < RHS.CounterID;
      87             :   });
      88             : 
      89             :   // Combine terms by counter ID to eliminate counters that sum to zero.
      90         555 :   auto Prev = Terms.begin();
      91        1832 :   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
      92         851 :     if (I->CounterID == Prev->CounterID) {
      93         129 :       Prev->Factor += I->Factor;
      94         129 :       continue;
      95             :     }
      96         593 :     ++Prev;
      97         593 :     *Prev = *I;
      98             :   }
      99        1110 :   Terms.erase(++Prev, Terms.end());
     100             : 
     101         555 :   Counter C;
     102             :   // Create additions. We do this before subtractions to avoid constructs like
     103             :   // ((0 - X) + Y), as opposed to (Y - X).
     104        1703 :   for (auto T : Terms) {
     105        1148 :     if (T.Factor <= 0)
     106         416 :       continue;
     107        2196 :     for (int I = 0; I < T.Factor; ++I)
     108         732 :       if (C.isZero())
     109             :         C = Counter::getCounter(T.CounterID);
     110             :       else
     111         534 :         C = get(CounterExpression(CounterExpression::Add, C,
     112             :                                   Counter::getCounter(T.CounterID)));
     113             :   }
     114             : 
     115             :   // Create subtractions.
     116        2258 :   for (auto T : Terms) {
     117        1148 :     if (T.Factor >= 0)
     118         861 :       continue;
     119         861 :     for (int I = 0; I < -T.Factor; ++I)
     120         861 :       C = get(CounterExpression(CounterExpression::Subtract, C,
     121             :                                 Counter::getCounter(T.CounterID)));
     122             :   }
     123         555 :   return C;
     124             : }
     125             : 
     126         378 : Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
     127         378 :   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
     128             : }
     129             : 
     130         182 : Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
     131             :   return simplify(
     132         182 :       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
     133             : }
     134             : 
     135        1563 : void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
     136        1563 :   switch (C.getKind()) {
     137          56 :   case Counter::Zero:
     138             :     OS << '0';
     139        1563 :     return;
     140        1213 :   case Counter::CounterValueReference:
     141        1213 :     OS << '#' << C.getCounterID();
     142             :     break;
     143         294 :   case Counter::Expression: {
     144         294 :     if (C.getExpressionID() >= Expressions.size())
     145             :       return;
     146         588 :     const auto &E = Expressions[C.getExpressionID()];
     147         294 :     OS << '(';
     148         294 :     dump(E.LHS, OS);
     149         294 :     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
     150         294 :     dump(E.RHS, OS);
     151             :     OS << ')';
     152             :     break;
     153             :   }
     154             :   }
     155        1507 :   if (CounterValues.empty())
     156             :     return;
     157           0 :   Expected<int64_t> Value = evaluate(C);
     158           0 :   if (auto E = Value.takeError()) {
     159           0 :     consumeError(std::move(E));
     160           0 :     return;
     161             :   }
     162           0 :   OS << '[' << *Value << ']';
     163             : }
     164             : 
     165        1389 : Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
     166        1389 :   switch (C.getKind()) {
     167          48 :   case Counter::Zero:
     168          96 :     return 0;
     169        1126 :   case Counter::CounterValueReference:
     170        1126 :     if (C.getCounterID() >= CounterValues.size())
     171           0 :       return errorCodeToError(errc::argument_out_of_domain);
     172        2252 :     return CounterValues[C.getCounterID()];
     173         215 :   case Counter::Expression: {
     174         215 :     if (C.getExpressionID() >= Expressions.size())
     175           0 :       return errorCodeToError(errc::argument_out_of_domain);
     176         430 :     const auto &E = Expressions[C.getExpressionID()];
     177         215 :     Expected<int64_t> LHS = evaluate(E.LHS);
     178         215 :     if (!LHS)
     179             :       return LHS;
     180         215 :     Expected<int64_t> RHS = evaluate(E.RHS);
     181         215 :     if (!RHS)
     182             :       return RHS;
     183         860 :     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
     184             :   }
     185             :   }
     186           0 :   llvm_unreachable("Unhandled CounterKind");
     187             : }
     188             : 
     189         697 : void FunctionRecordIterator::skipOtherFiles() {
     190        1891 :   while (Current != Records.end() && !Filename.empty() &&
     191          38 :          Filename != Current->Filenames[0])
     192           0 :     ++Current;
     193         697 :   if (Current == Records.end())
     194         200 :     *this = FunctionRecordIterator();
     195         697 : }
     196             : 
     197         294 : Error CoverageMapping::loadFunctionRecord(
     198             :     const CoverageMappingRecord &Record,
     199             :     IndexedInstrProfReader &ProfileReader) {
     200         294 :   StringRef OrigFuncName = Record.FunctionName;
     201         294 :   if (OrigFuncName.empty())
     202           4 :     return make_error<CoverageMapError>(coveragemap_error::malformed);
     203             : 
     204         290 :   if (Record.Filenames.empty())
     205           4 :     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
     206             :   else
     207         286 :     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
     208             : 
     209             :   // Don't load records for functions we've already seen.
     210         580 :   if (!FunctionNames.insert(OrigFuncName).second)
     211          18 :     return Error::success();
     212             : 
     213         568 :   CounterMappingContext Ctx(Record.Expressions);
     214             : 
     215         284 :   std::vector<uint64_t> Counts;
     216         284 :   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
     217         851 :                                                 Record.FunctionHash, Counts)) {
     218          93 :     instrprof_error IPE = InstrProfError::take(std::move(E));
     219          31 :     if (IPE == instrprof_error::hash_mismatch) {
     220           1 :       MismatchedFunctionCount++;
     221           3 :       return Error::success();
     222          30 :     } else if (IPE != instrprof_error::unknown_function)
     223           0 :       return make_error<InstrProfError>(IPE);
     224          60 :     Counts.assign(Record.MappingRegions.size(), 0);
     225             :   }
     226         283 :   Ctx.setCounts(Counts);
     227             : 
     228             :   assert(!Record.MappingRegions.empty() && "Function has no regions");
     229             : 
     230         566 :   FunctionRecord Function(OrigFuncName, Record.Filenames);
     231        1525 :   for (const auto &Region : Record.MappingRegions) {
     232        1918 :     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
     233        2877 :     if (auto E = ExecutionCount.takeError()) {
     234           0 :       consumeError(std::move(E));
     235           0 :       return Error::success();
     236             :     }
     237        1918 :     Function.pushRegion(Region, *ExecutionCount);
     238             :   }
     239         566 :   if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
     240           0 :     MismatchedFunctionCount++;
     241           0 :     return Error::success();
     242             :   }
     243             : 
     244         566 :   Functions.push_back(std::move(Function));
     245         849 :   return Error::success();
     246             : }
     247             : 
     248         172 : Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
     249             :     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
     250             :     IndexedInstrProfReader &ProfileReader) {
     251         688 :   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
     252             : 
     253         519 :   for (const auto &CoverageReader : CoverageReaders) {
     254        1470 :     for (auto RecordOrErr : *CoverageReader) {
     255         884 :       if (Error E = RecordOrErr.takeError())
     256           4 :         return std::move(E);
     257         294 :       const auto &Record = *RecordOrErr;
     258         878 :       if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
     259          16 :         return std::move(E);
     260             :     }
     261             :   }
     262             : 
     263         167 :   return std::move(Coverage);
     264             : }
     265             : 
     266             : Expected<std::unique_ptr<CoverageMapping>>
     267          81 : CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
     268             :                       StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
     269         162 :   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
     270         243 :   if (Error E = ProfileReaderOrErr.takeError())
     271           0 :     return std::move(E);
     272         162 :   auto ProfileReader = std::move(ProfileReaderOrErr.get());
     273             : 
     274         162 :   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
     275         162 :   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
     276         406 :   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
     277         248 :     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
     278          83 :     if (std::error_code EC = CovMappingBufOrErr.getError())
     279           0 :       return errorCodeToError(EC);
     280          88 :     StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
     281             :     auto CoverageReaderOrErr =
     282         165 :         BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
     283         248 :     if (Error E = CoverageReaderOrErr.takeError())
     284           4 :       return std::move(E);
     285         246 :     Readers.push_back(std::move(CoverageReaderOrErr.get()));
     286          82 :     Buffers.push_back(std::move(CovMappingBufOrErr.get()));
     287             :   }
     288         160 :   return load(Readers, *ProfileReader);
     289             : }
     290             : 
     291             : namespace {
     292             : 
     293             : /// \brief Distributes functions into instantiation sets.
     294             : ///
     295             : /// An instantiation set is a collection of functions that have the same source
     296             : /// code, ie, template functions specializations.
     297         368 : class FunctionInstantiationSetCollector {
     298             :   using MapT = DenseMap<LineColPair, std::vector<const FunctionRecord *>>;
     299             :   MapT InstantiatedFunctions;
     300             : 
     301             : public:
     302         138 :   void insert(const FunctionRecord &Function, unsigned FileID) {
     303         414 :     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
     304         138 :     while (I != E && I->FileID != FileID)
     305             :       ++I;
     306             :     assert(I != E && "function does not cover the given file");
     307         414 :     auto &Functions = InstantiatedFunctions[I->startLoc()];
     308         276 :     Functions.push_back(&Function);
     309         138 :   }
     310             : 
     311          92 :   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
     312         184 :   MapT::iterator end() { return InstantiatedFunctions.end(); }
     313             : };
     314             : 
     315         336 : class SegmentBuilder {
     316             :   std::vector<CoverageSegment> &Segments;
     317             :   SmallVector<const CountedRegion *, 8> ActiveRegions;
     318             : 
     319         336 :   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
     320             : 
     321             :   /// Emit a segment with the count from \p Region starting at \p StartLoc.
     322             :   //
     323             :   /// \p IsRegionEntry: The segment is at the start of a new region.
     324             :   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
     325        1315 :   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
     326             :                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
     327        2419 :     bool HasCount = !EmitSkippedRegion &&
     328        1104 :                     (Region.Kind != CounterMappingRegion::SkippedRegion);
     329             : 
     330             :     // If the new segment wouldn't affect coverage rendering, skip it.
     331        2630 :     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
     332         856 :       const auto &Last = Segments.back();
     333         591 :       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
     334         163 :           !Last.IsRegionEntry)
     335             :         return;
     336             :     }
     337             : 
     338        1304 :     if (HasCount)
     339        1088 :       Segments.emplace_back(StartLoc.first, StartLoc.second,
     340             :                             Region.ExecutionCount, IsRegionEntry);
     341             :     else
     342         216 :       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
     343             : 
     344             :     DEBUG({
     345             :       const auto &Last = Segments.back();
     346             :       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
     347             :              << " (count = " << Last.Count << ")"
     348             :              << (Last.IsRegionEntry ? ", RegionEntry" : "")
     349             :              << (!Last.HasCount ? ", Skipped" : "") << "\n";
     350             :     });
     351             :   }
     352             : 
     353             :   /// Emit segments for active regions which end before \p Loc.
     354             :   ///
     355             :   /// \p Loc: The start location of the next region. If None, all active
     356             :   /// regions are completed.
     357             :   /// \p FirstCompletedRegion: Index of the first completed region.
     358         518 :   void completeRegionsUntil(Optional<LineColPair> Loc,
     359             :                             unsigned FirstCompletedRegion) {
     360             :     // Sort the completed regions by end location. This makes it simple to
     361             :     // emit closing segments in sorted order.
     362        1036 :     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
     363        1554 :     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
     364             :                       [](const CountedRegion *L, const CountedRegion *R) {
     365         618 :                         return L->endLoc() < R->endLoc();
     366          58 :                       });
     367             : 
     368             :     // Emit segments for all completed regions.
     369        1198 :     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
     370             :          ++I) {
     371         332 :       const auto *CompletedRegion = ActiveRegions[I];
     372             :       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
     373             :              "Completed region ends after start of new region");
     374             : 
     375         332 :       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
     376         332 :       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
     377             : 
     378             :       // Don't emit any more segments if they start where the new region begins.
     379         235 :       if (Loc && CompletedSegmentLoc == *Loc)
     380             :         break;
     381             : 
     382             :       // Don't emit a segment if the next completed region ends at the same
     383             :       // location as this one.
     384         486 :       if (CompletedSegmentLoc == CompletedRegion->endLoc())
     385          23 :         continue;
     386             : 
     387         139 :       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
     388             :     }
     389             : 
     390        1036 :     auto Last = ActiveRegions.back();
     391        1445 :     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
     392             :       // If there's a gap after the end of the last completed region and the
     393             :       // start of the new region, use the last active region to fill the gap.
     394         867 :       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
     395             :                    false);
     396         522 :     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
     397             :       // Emit a skipped segment if there are no more active regions. This
     398             :       // ensures that gaps between functions are marked correctly.
     399         390 :       startSegment(*Last, Last->endLoc(), false, true);
     400             :     }
     401             : 
     402             :     // Pop the completed regions.
     403        1554 :     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
     404         518 :   }
     405             : 
     406         168 :   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
     407        1380 :     for (const auto &CR : enumerate(Regions)) {
     408        1416 :       auto CurStartLoc = CR.value().startLoc();
     409             : 
     410             :       // Active regions which end before the current region need to be popped.
     411             :       auto CompletedRegions =
     412        2124 :           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
     413             :                                 [&](const CountedRegion *Region) {
     414        2237 :                                   return !(Region->endLoc() <= CurStartLoc);
     415         708 :                                 });
     416        1416 :       if (CompletedRegions != ActiveRegions.end()) {
     417             :         unsigned FirstCompletedRegion =
     418        1098 :             std::distance(ActiveRegions.begin(), CompletedRegions);
     419         732 :         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
     420             :       }
     421             : 
     422             :       // Try to emit a segment for the current region.
     423        2124 :       if (CurStartLoc == CR.value().endLoc()) {
     424             :         // Avoid making zero-length regions active. If it's the last region,
     425             :         // emit a skipped segment. Otherwise use its predecessor's count.
     426          20 :         const bool Skipped = (CR.index() + 1) == Regions.size();
     427          28 :         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
     428             :                      CurStartLoc, true, Skipped);
     429          20 :         continue;
     430             :       }
     431         688 :       if (CR.index() + 1 == Regions.size() ||
     432        1608 :           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
     433             :         // Emit a segment if the next region doesn't start at the same location
     434             :         // as this one.
     435         672 :         startSegment(CR.value(), CurStartLoc, true);
     436             :       }
     437             : 
     438             :       // This region is active (i.e not completed).
     439         688 :       ActiveRegions.push_back(&CR.value());
     440             :     }
     441             : 
     442             :     // Complete any remaining active regions.
     443         168 :     if (!ActiveRegions.empty())
     444         304 :       completeRegionsUntil(None, 0);
     445         168 :   }
     446             : 
     447             :   /// Sort a nested sequence of regions from a single file.
     448             :   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
     449         504 :     std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
     450        1780 :                                                  const CountedRegion &RHS) {
     451        7120 :       if (LHS.startLoc() != RHS.startLoc())
     452        4866 :         return LHS.startLoc() < RHS.startLoc();
     453         632 :       if (LHS.endLoc() != RHS.endLoc())
     454             :         // When LHS completely contains RHS, we sort LHS first.
     455          84 :         return RHS.endLoc() < LHS.endLoc();
     456             :       // If LHS and RHS cover the same area, we need to sort them according
     457             :       // to their kinds so that the most suitable region will become "active"
     458             :       // in combineRegions(). Because we accumulate counter values only from
     459             :       // regions of the same kind as the first region of the area, prefer
     460             :       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
     461             :       static_assert(CounterMappingRegion::CodeRegion <
     462             :                             CounterMappingRegion::ExpansionRegion &&
     463             :                         CounterMappingRegion::ExpansionRegion <
     464             :                             CounterMappingRegion::SkippedRegion,
     465             :                     "Unexpected order of region kind values");
     466         130 :       return LHS.Kind < RHS.Kind;
     467             :     });
     468             :   }
     469             : 
     470             :   /// Combine counts of regions which cover the same area.
     471             :   static ArrayRef<CountedRegion>
     472         168 :   combineRegions(MutableArrayRef<CountedRegion> Regions) {
     473         168 :     if (Regions.empty())
     474           0 :       return Regions;
     475         168 :     auto Active = Regions.begin();
     476         168 :     auto End = Regions.end();
     477         797 :     for (auto I = Regions.begin() + 1; I != End; ++I) {
     478        2532 :       if (Active->startLoc() != I->startLoc() ||
     479         404 :           Active->endLoc() != I->endLoc()) {
     480             :         // Shift to the next region.
     481         540 :         ++Active;
     482         540 :         if (Active != I)
     483          53 :           *Active = *I;
     484         540 :         continue;
     485             :       }
     486             :       // Merge duplicate region.
     487             :       // If CodeRegions and ExpansionRegions cover the same area, it's probably
     488             :       // a macro which is fully expanded to another macro. In that case, we need
     489             :       // to accumulate counts only from CodeRegions, or else the area will be
     490             :       // counted twice.
     491             :       // On the other hand, a macro may have a nested macro in its body. If the
     492             :       // outer macro is used several times, the ExpansionRegion for the nested
     493             :       // macro will also be added several times. These ExpansionRegions cover
     494             :       // the same source locations and have to be combined to reach the correct
     495             :       // value for that area.
     496             :       // We add counts of the regions of the same kind as the active region
     497             :       // to handle the both situations.
     498          89 :       if (I->Kind == Active->Kind)
     499          85 :         Active->ExecutionCount += I->ExecutionCount;
     500             :     }
     501         504 :     return Regions.drop_back(std::distance(++Active, End));
     502             :   }
     503             : 
     504             : public:
     505             :   /// Build a sorted list of CoverageSegments from a list of Regions.
     506             :   static std::vector<CoverageSegment>
     507         168 :   buildSegments(MutableArrayRef<CountedRegion> Regions) {
     508         168 :     std::vector<CoverageSegment> Segments;
     509         336 :     SegmentBuilder Builder(Segments);
     510             : 
     511         168 :     sortNestedRegions(Regions);
     512         168 :     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
     513             : 
     514             :     DEBUG({
     515             :       dbgs() << "Combined regions:\n";
     516             :       for (const auto &CR : CombinedRegions)
     517             :         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
     518             :                << CR.LineEnd << ":" << CR.ColumnEnd
     519             :                << " (count=" << CR.ExecutionCount << ")\n";
     520             :     });
     521             : 
     522         168 :     Builder.buildSegmentsImpl(CombinedRegions);
     523             : 
     524             : #ifndef NDEBUG
     525             :     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
     526             :       const auto &L = Segments[I - 1];
     527             :       const auto &R = Segments[I];
     528             :       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
     529             :         DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
     530             :                      << " followed by " << R.Line << ":" << R.Col << "\n");
     531             :         assert(false && "Coverage segments not unique or sorted");
     532             :       }
     533             :     }
     534             : #endif
     535             : 
     536         168 :     return Segments;
     537             :   }
     538             : };
     539             : 
     540             : } // end anonymous namespace
     541             : 
     542         147 : std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
     543         147 :   std::vector<StringRef> Filenames;
     544         796 :   for (const auto &Function : getCoveredFunctions())
     545        1065 :     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
     546        1775 :                      Function.Filenames.end());
     547         441 :   std::sort(Filenames.begin(), Filenames.end());
     548         441 :   auto Last = std::unique(Filenames.begin(), Filenames.end());
     549         588 :   Filenames.erase(Last, Filenames.end());
     550         147 :   return Filenames;
     551             : }
     552             : 
     553         136 : static SmallBitVector gatherFileIDs(StringRef SourceFile,
     554             :                                     const FunctionRecord &Function) {
     555         272 :   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
     556         460 :   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
     557         564 :     if (SourceFile == Function.Filenames[I])
     558         141 :       FilenameEquivalence[I] = true;
     559         136 :   return FilenameEquivalence;
     560             : }
     561             : 
     562             : /// Return the ID of the file where the definition of the function is located.
     563         454 : static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
     564        1362 :   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
     565        3484 :   for (const auto &CR : Function.CountedRegions)
     566        1668 :     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
     567         116 :       IsNotExpandedFile[CR.ExpandedFileID] = false;
     568         454 :   int I = IsNotExpandedFile.find_first();
     569         454 :   if (I == -1)
     570             :     return None;
     571         908 :   return I;
     572             : }
     573             : 
     574             : /// Check if SourceFile is the file that contains the definition of
     575             : /// the Function. Return the ID of the file in that case or None otherwise.
     576         381 : static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
     577             :                                              const FunctionRecord &Function) {
     578         762 :   Optional<unsigned> I = findMainViewFileID(Function);
     579        1524 :   if (I && SourceFile == Function.Filenames[*I])
     580             :     return I;
     581             :   return None;
     582             : }
     583             : 
     584             : static bool isExpansion(const CountedRegion &R, unsigned FileID) {
     585         779 :   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
     586             : }
     587             : 
     588          92 : CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
     589          92 :   CoverageData FileCoverage(Filename);
     590         184 :   std::vector<CountedRegion> Regions;
     591             : 
     592         504 :   for (const auto &Function : Functions) {
     593         272 :     auto MainFileID = findMainViewFileID(Filename, Function);
     594         272 :     auto FileIDs = gatherFileIDs(Filename, Function);
     595        1119 :     for (const auto &CR : Function.CountedRegions)
     596        1150 :       if (FileIDs.test(CR.FileID)) {
     597         523 :         Regions.push_back(CR);
     598        1044 :         if (MainFileID && isExpansion(CR, *MainFileID))
     599          16 :           FileCoverage.Expansions.emplace_back(CR, Function);
     600             :       }
     601             :   }
     602             : 
     603             :   DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
     604         276 :   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
     605             : 
     606          92 :   return FileCoverage;
     607             : }
     608             : 
     609             : std::vector<InstantiationGroup>
     610          92 : CoverageMapping::getInstantiationGroups(StringRef Filename) const {
     611         184 :   FunctionInstantiationSetCollector InstantiationSetCollector;
     612         613 :   for (const auto &Function : Functions) {
     613         383 :     auto MainFileID = findMainViewFileID(Filename, Function);
     614         245 :     if (!MainFileID)
     615         107 :       continue;
     616         138 :     InstantiationSetCollector.insert(Function, *MainFileID);
     617             :   }
     618             : 
     619          92 :   std::vector<InstantiationGroup> Result;
     620         614 :   for (const auto &InstantiationSet : InstantiationSetCollector) {
     621         123 :     InstantiationGroup IG{InstantiationSet.first.first,
     622         123 :                           InstantiationSet.first.second,
     623         492 :                           std::move(InstantiationSet.second)};
     624         123 :     Result.emplace_back(std::move(IG));
     625             :   }
     626          92 :   return Result;
     627             : }
     628             : 
     629             : CoverageData
     630          73 : CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
     631         146 :   auto MainFileID = findMainViewFileID(Function);
     632          73 :   if (!MainFileID)
     633           0 :     return CoverageData();
     634             : 
     635         292 :   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
     636         146 :   std::vector<CountedRegion> Regions;
     637         560 :   for (const auto &CR : Function.CountedRegions)
     638         536 :     if (CR.FileID == *MainFileID) {
     639         262 :       Regions.push_back(CR);
     640         264 :       if (isExpansion(CR, *MainFileID))
     641           2 :         FunctionCoverage.Expansions.emplace_back(CR, Function);
     642             :     }
     643             : 
     644             :   DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
     645         219 :   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
     646             : 
     647          73 :   return FunctionCoverage;
     648             : }
     649             : 
     650           3 : CoverageData CoverageMapping::getCoverageForExpansion(
     651             :     const ExpansionRecord &Expansion) const {
     652             :   CoverageData ExpansionCoverage(
     653           9 :       Expansion.Function.Filenames[Expansion.FileID]);
     654           6 :   std::vector<CountedRegion> Regions;
     655          60 :   for (const auto &CR : Expansion.Function.CountedRegions)
     656          48 :     if (CR.FileID == Expansion.FileID) {
     657          12 :       Regions.push_back(CR);
     658          14 :       if (isExpansion(CR, Expansion.FileID))
     659           2 :         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
     660             :     }
     661             : 
     662             :   DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
     663             :                << "\n");
     664           9 :   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
     665             : 
     666           3 :   return ExpansionCoverage;
     667             : }
     668             : 
     669           5 : static std::string getCoverageMapErrString(coveragemap_error Err) {
     670           5 :   switch (Err) {
     671             :   case coveragemap_error::success:
     672           0 :     return "Success";
     673             :   case coveragemap_error::eof:
     674           0 :     return "End of File";
     675             :   case coveragemap_error::no_data_found:
     676           0 :     return "No coverage data found";
     677             :   case coveragemap_error::unsupported_version:
     678           0 :     return "Unsupported coverage format version";
     679             :   case coveragemap_error::truncated:
     680           0 :     return "Truncated coverage data";
     681             :   case coveragemap_error::malformed:
     682          10 :     return "Malformed coverage data";
     683             :   }
     684           0 :   llvm_unreachable("A value of coveragemap_error has no message.");
     685             : }
     686             : 
     687             : namespace {
     688             : 
     689             : // FIXME: This class is only here to support the transition to llvm::Error. It
     690             : // will be removed once this transition is complete. Clients should prefer to
     691             : // deal with the Error value directly, rather than converting to error_code.
     692           0 : class CoverageMappingErrorCategoryType : public std::error_category {
     693           0 :   const char *name() const noexcept override { return "llvm.coveragemap"; }
     694           0 :   std::string message(int IE) const override {
     695           0 :     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
     696             :   }
     697             : };
     698             : 
     699             : } // end anonymous namespace
     700             : 
     701           5 : std::string CoverageMapError::message() const {
     702           5 :   return getCoverageMapErrString(Err);
     703             : }
     704             : 
     705             : static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
     706             : 
     707           0 : const std::error_category &llvm::coverage::coveragemap_category() {
     708           0 :   return *ErrorCategory;
     709             : }
     710             : 
     711             : char CoverageMapError::ID = 0;

Generated by: LCOV version 1.13