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