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