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