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