xref: /llvm-project/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp (revision a3b0dde4edb93248f74d86c63b0ae108854004e6)
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/SmallBitVector.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Object/BuildID.h"
21 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
22 #include "llvm/ProfileData/InstrProfReader.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Errc.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstdint>
32 #include <iterator>
33 #include <map>
34 #include <memory>
35 #include <optional>
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 Error CoverageMapping::loadFromFile(
347     StringRef Filename, StringRef Arch, StringRef CompilationDir,
348     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage,
349     bool &DataFound, SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
350   auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
351       Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false);
352   if (std::error_code EC = CovMappingBufOrErr.getError())
353     return createFileError(Filename, errorCodeToError(EC));
354   MemoryBufferRef CovMappingBufRef =
355       CovMappingBufOrErr.get()->getMemBufferRef();
356   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
357 
358   SmallVector<object::BuildIDRef> BinaryIDs;
359   auto CoverageReadersOrErr = BinaryCoverageReader::create(
360       CovMappingBufRef, Arch, Buffers, CompilationDir,
361       FoundBinaryIDs ? &BinaryIDs : nullptr);
362   if (Error E = CoverageReadersOrErr.takeError()) {
363     E = handleMaybeNoDataFoundError(std::move(E));
364     if (E)
365       return createFileError(Filename, std::move(E));
366     return E;
367   }
368 
369   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
370   for (auto &Reader : CoverageReadersOrErr.get())
371     Readers.push_back(std::move(Reader));
372   if (FoundBinaryIDs && !Readers.empty()) {
373     llvm::append_range(*FoundBinaryIDs,
374                        llvm::map_range(BinaryIDs, [](object::BuildIDRef BID) {
375                          return object::BuildID(BID);
376                        }));
377   }
378   DataFound |= !Readers.empty();
379   if (Error E = loadFromReaders(Readers, ProfileReader, Coverage))
380     return createFileError(Filename, std::move(E));
381   return Error::success();
382 }
383 
384 Expected<std::unique_ptr<CoverageMapping>>
385 CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
386                       StringRef ProfileFilename, ArrayRef<StringRef> Arches,
387                       StringRef CompilationDir,
388                       const object::BuildIDFetcher *BIDFetcher) {
389   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
390   if (Error E = ProfileReaderOrErr.takeError())
391     return createFileError(ProfileFilename, std::move(E));
392   auto ProfileReader = std::move(ProfileReaderOrErr.get());
393   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
394   bool DataFound = false;
395 
396   auto GetArch = [&](size_t Idx) {
397     if (Arches.empty())
398       return StringRef();
399     if (Arches.size() == 1)
400       return Arches.front();
401     return Arches[Idx];
402   };
403 
404   SmallVector<object::BuildID> FoundBinaryIDs;
405   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
406     if (Error E =
407             loadFromFile(File.value(), GetArch(File.index()), CompilationDir,
408                          *ProfileReader, *Coverage, DataFound, &FoundBinaryIDs))
409       return std::move(E);
410   }
411 
412   if (BIDFetcher) {
413     const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) {
414       return StringRef(reinterpret_cast<const char *>(A.data()), A.size()) <
415              StringRef(reinterpret_cast<const char *>(B.data()), B.size());
416     };
417     std::vector<object::BuildID> ProfileBinaryIDs;
418     if (Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs))
419       return createFileError(ProfileFilename, std::move(E));
420     llvm::sort(ProfileBinaryIDs, Compare);
421     std::unique(ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(), Compare);
422 
423     SmallVector<object::BuildIDRef> BinaryIDsToFetch;
424     if (!ProfileBinaryIDs.empty()) {
425       llvm::sort(FoundBinaryIDs, Compare);
426       std::unique(FoundBinaryIDs.begin(), FoundBinaryIDs.end(), Compare);
427       std::set_difference(
428           ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(),
429           FoundBinaryIDs.begin(), FoundBinaryIDs.end(),
430           std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.end()), Compare);
431     }
432 
433     for (object::BuildIDRef BinaryID : BinaryIDsToFetch) {
434       std::optional<std::string> PathOpt = BIDFetcher->fetch(BinaryID);
435       if (!PathOpt)
436         continue;
437       std::string Path = std::move(*PathOpt);
438       StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef();
439       if (Error E = loadFromFile(Path, Arch, CompilationDir, *ProfileReader,
440                                  *Coverage, DataFound))
441         return std::move(E);
442     }
443   }
444 
445   if (!DataFound)
446     return createFileError(
447         join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
448         make_error<CoverageMapError>(coveragemap_error::no_data_found));
449   return std::move(Coverage);
450 }
451 
452 namespace {
453 
454 /// Distributes functions into instantiation sets.
455 ///
456 /// An instantiation set is a collection of functions that have the same source
457 /// code, ie, template functions specializations.
458 class FunctionInstantiationSetCollector {
459   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
460   MapT InstantiatedFunctions;
461 
462 public:
463   void insert(const FunctionRecord &Function, unsigned FileID) {
464     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
465     while (I != E && I->FileID != FileID)
466       ++I;
467     assert(I != E && "function does not cover the given file");
468     auto &Functions = InstantiatedFunctions[I->startLoc()];
469     Functions.push_back(&Function);
470   }
471 
472   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
473   MapT::iterator end() { return InstantiatedFunctions.end(); }
474 };
475 
476 class SegmentBuilder {
477   std::vector<CoverageSegment> &Segments;
478   SmallVector<const CountedRegion *, 8> ActiveRegions;
479 
480   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
481 
482   /// Emit a segment with the count from \p Region starting at \p StartLoc.
483   //
484   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
485   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
486   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
487                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
488     bool HasCount = !EmitSkippedRegion &&
489                     (Region.Kind != CounterMappingRegion::SkippedRegion);
490 
491     // If the new segment wouldn't affect coverage rendering, skip it.
492     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
493       const auto &Last = Segments.back();
494       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
495           !Last.IsRegionEntry)
496         return;
497     }
498 
499     if (HasCount)
500       Segments.emplace_back(StartLoc.first, StartLoc.second,
501                             Region.ExecutionCount, IsRegionEntry,
502                             Region.Kind == CounterMappingRegion::GapRegion);
503     else
504       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
505 
506     LLVM_DEBUG({
507       const auto &Last = Segments.back();
508       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
509              << " (count = " << Last.Count << ")"
510              << (Last.IsRegionEntry ? ", RegionEntry" : "")
511              << (!Last.HasCount ? ", Skipped" : "")
512              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
513     });
514   }
515 
516   /// Emit segments for active regions which end before \p Loc.
517   ///
518   /// \p Loc: The start location of the next region. If std::nullopt, all active
519   /// regions are completed.
520   /// \p FirstCompletedRegion: Index of the first completed region.
521   void completeRegionsUntil(std::optional<LineColPair> Loc,
522                             unsigned FirstCompletedRegion) {
523     // Sort the completed regions by end location. This makes it simple to
524     // emit closing segments in sorted order.
525     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
526     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
527                       [](const CountedRegion *L, const CountedRegion *R) {
528                         return L->endLoc() < R->endLoc();
529                       });
530 
531     // Emit segments for all completed regions.
532     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
533          ++I) {
534       const auto *CompletedRegion = ActiveRegions[I];
535       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
536              "Completed region ends after start of new region");
537 
538       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
539       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
540 
541       // Don't emit any more segments if they start where the new region begins.
542       if (Loc && CompletedSegmentLoc == *Loc)
543         break;
544 
545       // Don't emit a segment if the next completed region ends at the same
546       // location as this one.
547       if (CompletedSegmentLoc == CompletedRegion->endLoc())
548         continue;
549 
550       // Use the count from the last completed region which ends at this loc.
551       for (unsigned J = I + 1; J < E; ++J)
552         if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
553           CompletedRegion = ActiveRegions[J];
554 
555       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
556     }
557 
558     auto Last = ActiveRegions.back();
559     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
560       // If there's a gap after the end of the last completed region and the
561       // start of the new region, use the last active region to fill the gap.
562       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
563                    false);
564     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
565       // Emit a skipped segment if there are no more active regions. This
566       // ensures that gaps between functions are marked correctly.
567       startSegment(*Last, Last->endLoc(), false, true);
568     }
569 
570     // Pop the completed regions.
571     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
572   }
573 
574   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
575     for (const auto &CR : enumerate(Regions)) {
576       auto CurStartLoc = CR.value().startLoc();
577 
578       // Active regions which end before the current region need to be popped.
579       auto CompletedRegions =
580           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
581                                 [&](const CountedRegion *Region) {
582                                   return !(Region->endLoc() <= CurStartLoc);
583                                 });
584       if (CompletedRegions != ActiveRegions.end()) {
585         unsigned FirstCompletedRegion =
586             std::distance(ActiveRegions.begin(), CompletedRegions);
587         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
588       }
589 
590       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
591 
592       // Try to emit a segment for the current region.
593       if (CurStartLoc == CR.value().endLoc()) {
594         // Avoid making zero-length regions active. If it's the last region,
595         // emit a skipped segment. Otherwise use its predecessor's count.
596         const bool Skipped =
597             (CR.index() + 1) == Regions.size() ||
598             CR.value().Kind == CounterMappingRegion::SkippedRegion;
599         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
600                      CurStartLoc, !GapRegion, Skipped);
601         // If it is skipped segment, create a segment with last pushed
602         // regions's count at CurStartLoc.
603         if (Skipped && !ActiveRegions.empty())
604           startSegment(*ActiveRegions.back(), CurStartLoc, false);
605         continue;
606       }
607       if (CR.index() + 1 == Regions.size() ||
608           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
609         // Emit a segment if the next region doesn't start at the same location
610         // as this one.
611         startSegment(CR.value(), CurStartLoc, !GapRegion);
612       }
613 
614       // This region is active (i.e not completed).
615       ActiveRegions.push_back(&CR.value());
616     }
617 
618     // Complete any remaining active regions.
619     if (!ActiveRegions.empty())
620       completeRegionsUntil(std::nullopt, 0);
621   }
622 
623   /// Sort a nested sequence of regions from a single file.
624   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
625     llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
626       if (LHS.startLoc() != RHS.startLoc())
627         return LHS.startLoc() < RHS.startLoc();
628       if (LHS.endLoc() != RHS.endLoc())
629         // When LHS completely contains RHS, we sort LHS first.
630         return RHS.endLoc() < LHS.endLoc();
631       // If LHS and RHS cover the same area, we need to sort them according
632       // to their kinds so that the most suitable region will become "active"
633       // in combineRegions(). Because we accumulate counter values only from
634       // regions of the same kind as the first region of the area, prefer
635       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
636       static_assert(CounterMappingRegion::CodeRegion <
637                             CounterMappingRegion::ExpansionRegion &&
638                         CounterMappingRegion::ExpansionRegion <
639                             CounterMappingRegion::SkippedRegion,
640                     "Unexpected order of region kind values");
641       return LHS.Kind < RHS.Kind;
642     });
643   }
644 
645   /// Combine counts of regions which cover the same area.
646   static ArrayRef<CountedRegion>
647   combineRegions(MutableArrayRef<CountedRegion> Regions) {
648     if (Regions.empty())
649       return Regions;
650     auto Active = Regions.begin();
651     auto End = Regions.end();
652     for (auto I = Regions.begin() + 1; I != End; ++I) {
653       if (Active->startLoc() != I->startLoc() ||
654           Active->endLoc() != I->endLoc()) {
655         // Shift to the next region.
656         ++Active;
657         if (Active != I)
658           *Active = *I;
659         continue;
660       }
661       // Merge duplicate region.
662       // If CodeRegions and ExpansionRegions cover the same area, it's probably
663       // a macro which is fully expanded to another macro. In that case, we need
664       // to accumulate counts only from CodeRegions, or else the area will be
665       // counted twice.
666       // On the other hand, a macro may have a nested macro in its body. If the
667       // outer macro is used several times, the ExpansionRegion for the nested
668       // macro will also be added several times. These ExpansionRegions cover
669       // the same source locations and have to be combined to reach the correct
670       // value for that area.
671       // We add counts of the regions of the same kind as the active region
672       // to handle the both situations.
673       if (I->Kind == Active->Kind)
674         Active->ExecutionCount += I->ExecutionCount;
675     }
676     return Regions.drop_back(std::distance(++Active, End));
677   }
678 
679 public:
680   /// Build a sorted list of CoverageSegments from a list of Regions.
681   static std::vector<CoverageSegment>
682   buildSegments(MutableArrayRef<CountedRegion> Regions) {
683     std::vector<CoverageSegment> Segments;
684     SegmentBuilder Builder(Segments);
685 
686     sortNestedRegions(Regions);
687     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
688 
689     LLVM_DEBUG({
690       dbgs() << "Combined regions:\n";
691       for (const auto &CR : CombinedRegions)
692         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
693                << CR.LineEnd << ":" << CR.ColumnEnd
694                << " (count=" << CR.ExecutionCount << ")\n";
695     });
696 
697     Builder.buildSegmentsImpl(CombinedRegions);
698 
699 #ifndef NDEBUG
700     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
701       const auto &L = Segments[I - 1];
702       const auto &R = Segments[I];
703       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
704         if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
705           continue;
706         LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
707                           << " followed by " << R.Line << ":" << R.Col << "\n");
708         assert(false && "Coverage segments not unique or sorted");
709       }
710     }
711 #endif
712 
713     return Segments;
714   }
715 };
716 
717 } // end anonymous namespace
718 
719 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
720   std::vector<StringRef> Filenames;
721   for (const auto &Function : getCoveredFunctions())
722     llvm::append_range(Filenames, Function.Filenames);
723   llvm::sort(Filenames);
724   auto Last = std::unique(Filenames.begin(), Filenames.end());
725   Filenames.erase(Last, Filenames.end());
726   return Filenames;
727 }
728 
729 static SmallBitVector gatherFileIDs(StringRef SourceFile,
730                                     const FunctionRecord &Function) {
731   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
732   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
733     if (SourceFile == Function.Filenames[I])
734       FilenameEquivalence[I] = true;
735   return FilenameEquivalence;
736 }
737 
738 /// Return the ID of the file where the definition of the function is located.
739 static std::optional<unsigned>
740 findMainViewFileID(const FunctionRecord &Function) {
741   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
742   for (const auto &CR : Function.CountedRegions)
743     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
744       IsNotExpandedFile[CR.ExpandedFileID] = false;
745   int I = IsNotExpandedFile.find_first();
746   if (I == -1)
747     return std::nullopt;
748   return I;
749 }
750 
751 /// Check if SourceFile is the file that contains the definition of
752 /// the Function. Return the ID of the file in that case or std::nullopt
753 /// otherwise.
754 static std::optional<unsigned>
755 findMainViewFileID(StringRef SourceFile, const FunctionRecord &Function) {
756   std::optional<unsigned> I = findMainViewFileID(Function);
757   if (I && SourceFile == Function.Filenames[*I])
758     return I;
759   return std::nullopt;
760 }
761 
762 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
763   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
764 }
765 
766 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
767   CoverageData FileCoverage(Filename);
768   std::vector<CountedRegion> Regions;
769 
770   // Look up the function records in the given file. Due to hash collisions on
771   // the filename, we may get back some records that are not in the file.
772   ArrayRef<unsigned> RecordIndices =
773       getImpreciseRecordIndicesForFilename(Filename);
774   for (unsigned RecordIndex : RecordIndices) {
775     const FunctionRecord &Function = Functions[RecordIndex];
776     auto MainFileID = findMainViewFileID(Filename, Function);
777     auto FileIDs = gatherFileIDs(Filename, Function);
778     for (const auto &CR : Function.CountedRegions)
779       if (FileIDs.test(CR.FileID)) {
780         Regions.push_back(CR);
781         if (MainFileID && isExpansion(CR, *MainFileID))
782           FileCoverage.Expansions.emplace_back(CR, Function);
783       }
784     // Capture branch regions specific to the function (excluding expansions).
785     for (const auto &CR : Function.CountedBranchRegions)
786       if (FileIDs.test(CR.FileID) && (CR.FileID == CR.ExpandedFileID))
787         FileCoverage.BranchRegions.push_back(CR);
788   }
789 
790   LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
791   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
792 
793   return FileCoverage;
794 }
795 
796 std::vector<InstantiationGroup>
797 CoverageMapping::getInstantiationGroups(StringRef Filename) const {
798   FunctionInstantiationSetCollector InstantiationSetCollector;
799   // Look up the function records in the given file. Due to hash collisions on
800   // the filename, we may get back some records that are not in the file.
801   ArrayRef<unsigned> RecordIndices =
802       getImpreciseRecordIndicesForFilename(Filename);
803   for (unsigned RecordIndex : RecordIndices) {
804     const FunctionRecord &Function = Functions[RecordIndex];
805     auto MainFileID = findMainViewFileID(Filename, Function);
806     if (!MainFileID)
807       continue;
808     InstantiationSetCollector.insert(Function, *MainFileID);
809   }
810 
811   std::vector<InstantiationGroup> Result;
812   for (auto &InstantiationSet : InstantiationSetCollector) {
813     InstantiationGroup IG{InstantiationSet.first.first,
814                           InstantiationSet.first.second,
815                           std::move(InstantiationSet.second)};
816     Result.emplace_back(std::move(IG));
817   }
818   return Result;
819 }
820 
821 CoverageData
822 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
823   auto MainFileID = findMainViewFileID(Function);
824   if (!MainFileID)
825     return CoverageData();
826 
827   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
828   std::vector<CountedRegion> Regions;
829   for (const auto &CR : Function.CountedRegions)
830     if (CR.FileID == *MainFileID) {
831       Regions.push_back(CR);
832       if (isExpansion(CR, *MainFileID))
833         FunctionCoverage.Expansions.emplace_back(CR, Function);
834     }
835   // Capture branch regions specific to the function (excluding expansions).
836   for (const auto &CR : Function.CountedBranchRegions)
837     if (CR.FileID == *MainFileID)
838       FunctionCoverage.BranchRegions.push_back(CR);
839 
840   LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
841                     << "\n");
842   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
843 
844   return FunctionCoverage;
845 }
846 
847 CoverageData CoverageMapping::getCoverageForExpansion(
848     const ExpansionRecord &Expansion) const {
849   CoverageData ExpansionCoverage(
850       Expansion.Function.Filenames[Expansion.FileID]);
851   std::vector<CountedRegion> Regions;
852   for (const auto &CR : Expansion.Function.CountedRegions)
853     if (CR.FileID == Expansion.FileID) {
854       Regions.push_back(CR);
855       if (isExpansion(CR, Expansion.FileID))
856         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
857     }
858   for (const auto &CR : Expansion.Function.CountedBranchRegions)
859     // Capture branch regions that only pertain to the corresponding expansion.
860     if (CR.FileID == Expansion.FileID)
861       ExpansionCoverage.BranchRegions.push_back(CR);
862 
863   LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
864                     << Expansion.FileID << "\n");
865   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
866 
867   return ExpansionCoverage;
868 }
869 
870 LineCoverageStats::LineCoverageStats(
871     ArrayRef<const CoverageSegment *> LineSegments,
872     const CoverageSegment *WrappedSegment, unsigned Line)
873     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
874       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
875   // Find the minimum number of regions which start in this line.
876   unsigned MinRegionCount = 0;
877   auto isStartOfRegion = [](const CoverageSegment *S) {
878     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
879   };
880   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
881     if (isStartOfRegion(LineSegments[I]))
882       ++MinRegionCount;
883 
884   bool StartOfSkippedRegion = !LineSegments.empty() &&
885                               !LineSegments.front()->HasCount &&
886                               LineSegments.front()->IsRegionEntry;
887 
888   HasMultipleRegions = MinRegionCount > 1;
889   Mapped =
890       !StartOfSkippedRegion &&
891       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
892 
893   if (!Mapped)
894     return;
895 
896   // Pick the max count from the non-gap, region entry segments and the
897   // wrapped count.
898   if (WrappedSegment)
899     ExecutionCount = WrappedSegment->Count;
900   if (!MinRegionCount)
901     return;
902   for (const auto *LS : LineSegments)
903     if (isStartOfRegion(LS))
904       ExecutionCount = std::max(ExecutionCount, LS->Count);
905 }
906 
907 LineCoverageIterator &LineCoverageIterator::operator++() {
908   if (Next == CD.end()) {
909     Stats = LineCoverageStats();
910     Ended = true;
911     return *this;
912   }
913   if (Segments.size())
914     WrappedSegment = Segments.back();
915   Segments.clear();
916   while (Next != CD.end() && Next->Line == Line)
917     Segments.push_back(&*Next++);
918   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
919   ++Line;
920   return *this;
921 }
922 
923 static std::string getCoverageMapErrString(coveragemap_error Err) {
924   switch (Err) {
925   case coveragemap_error::success:
926     return "Success";
927   case coveragemap_error::eof:
928     return "End of File";
929   case coveragemap_error::no_data_found:
930     return "No coverage data found";
931   case coveragemap_error::unsupported_version:
932     return "Unsupported coverage format version";
933   case coveragemap_error::truncated:
934     return "Truncated coverage data";
935   case coveragemap_error::malformed:
936     return "Malformed coverage data";
937   case coveragemap_error::decompression_failed:
938     return "Failed to decompress coverage data (zlib)";
939   case coveragemap_error::invalid_or_missing_arch_specifier:
940     return "`-arch` specifier is invalid or missing for universal binary";
941   }
942   llvm_unreachable("A value of coveragemap_error has no message.");
943 }
944 
945 namespace {
946 
947 // FIXME: This class is only here to support the transition to llvm::Error. It
948 // will be removed once this transition is complete. Clients should prefer to
949 // deal with the Error value directly, rather than converting to error_code.
950 class CoverageMappingErrorCategoryType : public std::error_category {
951   const char *name() const noexcept override { return "llvm.coveragemap"; }
952   std::string message(int IE) const override {
953     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
954   }
955 };
956 
957 } // end anonymous namespace
958 
959 std::string CoverageMapError::message() const {
960   return getCoverageMapErrString(Err);
961 }
962 
963 const std::error_category &llvm::coverage::coveragemap_category() {
964   static CoverageMappingErrorCategoryType ErrorCategory;
965   return ErrorCategory;
966 }
967 
968 char CoverageMapError::ID = 0;
969