xref: /llvm-project/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp (revision 3d0a689eb72aef639347edbec4608e631d5208a1)
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/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Object/BuildID.h"
22 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23 #include "llvm/ProfileData/InstrProfReader.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/VirtualFileSystem.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <cassert>
33 #include <cmath>
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 Expected<BitVector> CounterMappingContext::evaluateBitmap(
226     const CounterMappingRegion *MCDCDecision) const {
227   unsigned ID = MCDCDecision->MCDCParams.BitmapIdx;
228   unsigned NC = MCDCDecision->MCDCParams.NumConditions;
229   unsigned SizeInBits = llvm::alignTo(uint64_t(1) << NC, CHAR_BIT);
230   unsigned SizeInBytes = SizeInBits / CHAR_BIT;
231 
232   assert(ID + SizeInBytes <= BitmapBytes.size() && "BitmapBytes overrun");
233   ArrayRef<uint8_t> Bytes(&BitmapBytes[ID], SizeInBytes);
234 
235   // Mask each bitmap byte into the BitVector. Go in reverse so that the
236   // bitvector can just be shifted over by one byte on each iteration.
237   BitVector Result(SizeInBits, false);
238   for (auto Byte = std::rbegin(Bytes); Byte != std::rend(Bytes); ++Byte) {
239     uint32_t Data = *Byte;
240     Result <<= CHAR_BIT;
241     Result.setBitsInMask(&Data, 1);
242   }
243   return Result;
244 }
245 
246 class MCDCRecordProcessor {
247   /// A bitmap representing the executed test vectors for a boolean expression.
248   /// Each index of the bitmap corresponds to a possible test vector. An index
249   /// with a bit value of '1' indicates that the corresponding Test Vector
250   /// identified by that index was executed.
251   const BitVector &ExecutedTestVectorBitmap;
252 
253   /// Decision Region to which the ExecutedTestVectorBitmap applies.
254   const CounterMappingRegion &Region;
255 
256   /// Array of branch regions corresponding each conditions in the boolean
257   /// expression.
258   ArrayRef<const CounterMappingRegion *> Branches;
259 
260   /// Total number of conditions in the boolean expression.
261   unsigned NumConditions;
262 
263   /// Mapping of a condition ID to its corresponding branch region.
264   llvm::DenseMap<unsigned, const CounterMappingRegion *> Map;
265 
266   /// Vector used to track whether a condition is constant folded.
267   MCDCRecord::BoolVector Folded;
268 
269   /// Mapping of calculated MC/DC Independence Pairs for each condition.
270   MCDCRecord::TVPairMap IndependencePairs;
271 
272   /// Total number of possible Test Vectors for the boolean expression.
273   MCDCRecord::TestVectors TestVectors;
274 
275   /// Actual executed Test Vectors for the boolean expression, based on
276   /// ExecutedTestVectorBitmap.
277   MCDCRecord::TestVectors ExecVectors;
278 
279 public:
280   MCDCRecordProcessor(const BitVector &Bitmap,
281                       const CounterMappingRegion &Region,
282                       ArrayRef<const CounterMappingRegion *> Branches)
283       : ExecutedTestVectorBitmap(Bitmap), Region(Region), Branches(Branches),
284         NumConditions(Region.MCDCParams.NumConditions),
285         Folded(NumConditions, false), IndependencePairs(NumConditions),
286         TestVectors((size_t)1 << NumConditions) {}
287 
288 private:
289   void recordTestVector(MCDCRecord::TestVector &TV, unsigned Index,
290                         MCDCRecord::CondState Result) {
291     // Copy the completed test vector to the vector of testvectors.
292     TestVectors[Index] = TV;
293 
294     // The final value (T,F) is equal to the last non-dontcare state on the
295     // path (in a short-circuiting system).
296     TestVectors[Index].push_back(Result);
297   }
298 
299   // Walk the binary decision diagram and try assigning both false and true to
300   // each node. When a terminal node (ID == 0) is reached, fill in the value in
301   // the truth table.
302   void buildTestVector(MCDCRecord::TestVector &TV, unsigned ID,
303                        unsigned Index) {
304     const CounterMappingRegion *Branch = Map[ID];
305 
306     TV[ID - 1] = MCDCRecord::MCDC_False;
307     if (Branch->MCDCParams.FalseID > 0)
308       buildTestVector(TV, Branch->MCDCParams.FalseID, Index);
309     else
310       recordTestVector(TV, Index, MCDCRecord::MCDC_False);
311 
312     Index |= 1 << (ID - 1);
313     TV[ID - 1] = MCDCRecord::MCDC_True;
314     if (Branch->MCDCParams.TrueID > 0)
315       buildTestVector(TV, Branch->MCDCParams.TrueID, Index);
316     else
317       recordTestVector(TV, Index, MCDCRecord::MCDC_True);
318 
319     // Reset back to DontCare.
320     TV[ID - 1] = MCDCRecord::MCDC_DontCare;
321   }
322 
323   /// Walk the bits in the bitmap.  A bit set to '1' indicates that the test
324   /// vector at the corresponding index was executed during a test run.
325   void findExecutedTestVectors(const BitVector &ExecutedTestVectorBitmap) {
326     for (unsigned Idx = 0; Idx < ExecutedTestVectorBitmap.size(); ++Idx) {
327       if (ExecutedTestVectorBitmap[Idx] == 0)
328         continue;
329       assert(!TestVectors[Idx].empty() && "Test Vector doesn't exist.");
330       ExecVectors.push_back(TestVectors[Idx]);
331     }
332   }
333 
334   // Find an independence pair for each condition:
335   // - The condition is true in one test and false in the other.
336   // - The decision outcome is true one test and false in the other.
337   // - All other conditions' values must be equal or marked as "don't care".
338   void findIndependencePairs() {
339     unsigned NumTVs = ExecVectors.size();
340     for (unsigned I = 1; I < NumTVs; ++I) {
341       const MCDCRecord::TestVector &A = ExecVectors[I];
342       for (unsigned J = 0; J < I; ++J) {
343         const MCDCRecord::TestVector &B = ExecVectors[J];
344         // Enumerate two execution vectors whose outcomes are different.
345         if (A[NumConditions] == B[NumConditions])
346           continue;
347         unsigned Flip = NumConditions, Idx;
348         for (Idx = 0; Idx < NumConditions; ++Idx) {
349           MCDCRecord::CondState ACond = A[Idx], BCond = B[Idx];
350           if (ACond == BCond || ACond == MCDCRecord::MCDC_DontCare ||
351               BCond == MCDCRecord::MCDC_DontCare)
352             continue;
353           if (Flip != NumConditions)
354             break;
355           Flip = Idx;
356         }
357         // If the two vectors differ in exactly one condition, ignoring DontCare
358         // conditions, we have found an independence pair.
359         if (Idx == NumConditions && Flip != NumConditions)
360           IndependencePairs.insert({Flip, std::make_pair(J + 1, I + 1)});
361       }
362     }
363   }
364 
365 public:
366   /// Process the MC/DC Record in order to produce a result for a boolean
367   /// expression. This process includes tracking the conditions that comprise
368   /// the decision region, calculating the list of all possible test vectors,
369   /// marking the executed test vectors, and then finding an Independence Pair
370   /// out of the executed test vectors for each condition in the boolean
371   /// expression. A condition is tracked to ensure that its ID can be mapped to
372   /// its ordinal position in the boolean expression. The condition's source
373   /// location is also tracked, as well as whether it is constant folded (in
374   /// which case it is excuded from the metric).
375   MCDCRecord processMCDCRecord() {
376     unsigned I = 0;
377     MCDCRecord::CondIDMap PosToID;
378     MCDCRecord::LineColPairMap CondLoc;
379 
380     // Walk the Record's BranchRegions (representing Conditions) in order to:
381     // - Hash the condition based on its corresponding ID. This will be used to
382     //   calculate the test vectors.
383     // - Keep a map of the condition's ordinal position (1, 2, 3, 4) to its
384     //   actual ID.  This will be used to visualize the conditions in the
385     //   correct order.
386     // - Keep track of the condition source location. This will be used to
387     //   visualize where the condition is.
388     // - Record whether the condition is constant folded so that we exclude it
389     //   from being measured.
390     for (const auto *B : Branches) {
391       Map[B->MCDCParams.ID] = B;
392       PosToID[I] = B->MCDCParams.ID - 1;
393       CondLoc[I] = B->startLoc();
394       Folded[I++] = (B->Count.isZero() && B->FalseCount.isZero());
395     }
396 
397     // Walk the binary decision diagram to enumerate all possible test vectors.
398     // We start at the root node (ID == 1) with all values being DontCare.
399     // `Index` encodes the bitmask of true values and is initially 0.
400     MCDCRecord::TestVector TV(NumConditions, MCDCRecord::MCDC_DontCare);
401     buildTestVector(TV, 1, 0);
402 
403     // Using Profile Bitmap from runtime, mark the executed test vectors.
404     findExecutedTestVectors(ExecutedTestVectorBitmap);
405 
406     // Compare executed test vectors against each other to find an independence
407     // pairs for each condition.  This processing takes the most time.
408     findIndependencePairs();
409 
410     // Record Test vectors, executed vectors, and independence pairs.
411     MCDCRecord Res(Region, ExecVectors, IndependencePairs, Folded, PosToID,
412                    CondLoc);
413     return Res;
414   }
415 };
416 
417 Expected<MCDCRecord> CounterMappingContext::evaluateMCDCRegion(
418     const CounterMappingRegion &Region,
419     const BitVector &ExecutedTestVectorBitmap,
420     ArrayRef<const CounterMappingRegion *> Branches) {
421 
422   MCDCRecordProcessor MCDCProcessor(ExecutedTestVectorBitmap, Region, Branches);
423   return MCDCProcessor.processMCDCRecord();
424 }
425 
426 unsigned CounterMappingContext::getMaxCounterID(const Counter &C) const {
427   struct StackElem {
428     Counter ICounter;
429     int64_t LHS = 0;
430     enum {
431       KNeverVisited = 0,
432       KVisitedOnce = 1,
433       KVisitedTwice = 2,
434     } VisitCount = KNeverVisited;
435   };
436 
437   std::stack<StackElem> CounterStack;
438   CounterStack.push({C});
439 
440   int64_t LastPoppedValue;
441 
442   while (!CounterStack.empty()) {
443     StackElem &Current = CounterStack.top();
444 
445     switch (Current.ICounter.getKind()) {
446     case Counter::Zero:
447       LastPoppedValue = 0;
448       CounterStack.pop();
449       break;
450     case Counter::CounterValueReference:
451       LastPoppedValue = Current.ICounter.getCounterID();
452       CounterStack.pop();
453       break;
454     case Counter::Expression: {
455       if (Current.ICounter.getExpressionID() >= Expressions.size()) {
456         LastPoppedValue = 0;
457         CounterStack.pop();
458       } else {
459         const auto &E = Expressions[Current.ICounter.getExpressionID()];
460         if (Current.VisitCount == StackElem::KNeverVisited) {
461           CounterStack.push(StackElem{E.LHS});
462           Current.VisitCount = StackElem::KVisitedOnce;
463         } else if (Current.VisitCount == StackElem::KVisitedOnce) {
464           Current.LHS = LastPoppedValue;
465           CounterStack.push(StackElem{E.RHS});
466           Current.VisitCount = StackElem::KVisitedTwice;
467         } else {
468           int64_t LHS = Current.LHS;
469           int64_t RHS = LastPoppedValue;
470           LastPoppedValue = std::max(LHS, RHS);
471           CounterStack.pop();
472         }
473       }
474       break;
475     }
476     }
477   }
478 
479   return LastPoppedValue;
480 }
481 
482 void FunctionRecordIterator::skipOtherFiles() {
483   while (Current != Records.end() && !Filename.empty() &&
484          Filename != Current->Filenames[0])
485     ++Current;
486   if (Current == Records.end())
487     *this = FunctionRecordIterator();
488 }
489 
490 ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename(
491     StringRef Filename) const {
492   size_t FilenameHash = hash_value(Filename);
493   auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
494   if (RecordIt == FilenameHash2RecordIndices.end())
495     return {};
496   return RecordIt->second;
497 }
498 
499 static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
500                                 const CoverageMappingRecord &Record) {
501   unsigned MaxCounterID = 0;
502   for (const auto &Region : Record.MappingRegions) {
503     MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count));
504   }
505   return MaxCounterID;
506 }
507 
508 static unsigned getMaxBitmapSize(const CounterMappingContext &Ctx,
509                                  const CoverageMappingRecord &Record) {
510   unsigned MaxBitmapID = 0;
511   unsigned NumConditions = 0;
512   // Scan max(BitmapIdx).
513   // Note that `<=` is used insted of `<`, because `BitmapIdx == 0` is valid
514   // and `MaxBitmapID is `unsigned`. `BitmapIdx` is unique in the record.
515   for (const auto &Region : reverse(Record.MappingRegions)) {
516     if (Region.Kind == CounterMappingRegion::MCDCDecisionRegion &&
517         MaxBitmapID <= Region.MCDCParams.BitmapIdx) {
518       MaxBitmapID = Region.MCDCParams.BitmapIdx;
519       NumConditions = Region.MCDCParams.NumConditions;
520     }
521   }
522   unsigned SizeInBits = llvm::alignTo(uint64_t(1) << NumConditions, CHAR_BIT);
523   return MaxBitmapID + (SizeInBits / CHAR_BIT);
524 }
525 
526 Error CoverageMapping::loadFunctionRecord(
527     const CoverageMappingRecord &Record,
528     IndexedInstrProfReader &ProfileReader) {
529   StringRef OrigFuncName = Record.FunctionName;
530   if (OrigFuncName.empty())
531     return make_error<CoverageMapError>(coveragemap_error::malformed,
532                                         "record function name is empty");
533 
534   if (Record.Filenames.empty())
535     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
536   else
537     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
538 
539   CounterMappingContext Ctx(Record.Expressions);
540 
541   std::vector<uint64_t> Counts;
542   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
543                                                 Record.FunctionHash, Counts)) {
544     instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
545     if (IPE == instrprof_error::hash_mismatch) {
546       FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
547                                       Record.FunctionHash);
548       return Error::success();
549     }
550     if (IPE != instrprof_error::unknown_function)
551       return make_error<InstrProfError>(IPE);
552     Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
553   }
554   Ctx.setCounts(Counts);
555 
556   std::vector<uint8_t> BitmapBytes;
557   if (Error E = ProfileReader.getFunctionBitmapBytes(
558           Record.FunctionName, Record.FunctionHash, BitmapBytes)) {
559     instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
560     if (IPE == instrprof_error::hash_mismatch) {
561       FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
562                                       Record.FunctionHash);
563       return Error::success();
564     }
565     if (IPE != instrprof_error::unknown_function)
566       return make_error<InstrProfError>(IPE);
567     BitmapBytes.assign(getMaxBitmapSize(Ctx, Record) + 1, 0);
568   }
569   Ctx.setBitmapBytes(BitmapBytes);
570 
571   assert(!Record.MappingRegions.empty() && "Function has no regions");
572 
573   // This coverage record is a zero region for a function that's unused in
574   // some TU, but used in a different TU. Ignore it. The coverage maps from the
575   // the other TU will either be loaded (providing full region counts) or they
576   // won't (in which case we don't unintuitively report functions as uncovered
577   // when they have non-zero counts in the profile).
578   if (Record.MappingRegions.size() == 1 &&
579       Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
580     return Error::success();
581 
582   unsigned NumConds = 0;
583   const CounterMappingRegion *MCDCDecision;
584   std::vector<const CounterMappingRegion *> MCDCBranches;
585 
586   FunctionRecord Function(OrigFuncName, Record.Filenames);
587   for (const auto &Region : Record.MappingRegions) {
588     // If an MCDCDecisionRegion is seen, track the BranchRegions that follow
589     // it according to Region.NumConditions.
590     if (Region.Kind == CounterMappingRegion::MCDCDecisionRegion) {
591       assert(NumConds == 0);
592       MCDCDecision = &Region;
593       NumConds = Region.MCDCParams.NumConditions;
594       continue;
595     }
596     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
597     if (auto E = ExecutionCount.takeError()) {
598       consumeError(std::move(E));
599       return Error::success();
600     }
601     Expected<int64_t> AltExecutionCount = Ctx.evaluate(Region.FalseCount);
602     if (auto E = AltExecutionCount.takeError()) {
603       consumeError(std::move(E));
604       return Error::success();
605     }
606     Function.pushRegion(Region, *ExecutionCount, *AltExecutionCount);
607 
608     // If a MCDCDecisionRegion was seen, store the BranchRegions that
609     // correspond to it in a vector, according to the number of conditions
610     // recorded for the region (tracked by NumConds).
611     if (NumConds > 0 && Region.Kind == CounterMappingRegion::MCDCBranchRegion) {
612       MCDCBranches.push_back(&Region);
613 
614       // As we move through all of the MCDCBranchRegions that follow the
615       // MCDCDecisionRegion, decrement NumConds to make sure we account for
616       // them all before we calculate the bitmap of executed test vectors.
617       if (--NumConds == 0) {
618         // Evaluating the test vector bitmap for the decision region entails
619         // calculating precisely what bits are pertinent to this region alone.
620         // This is calculated based on the recorded offset into the global
621         // profile bitmap; the length is calculated based on the recorded
622         // number of conditions.
623         Expected<BitVector> ExecutedTestVectorBitmap =
624             Ctx.evaluateBitmap(MCDCDecision);
625         if (auto E = ExecutedTestVectorBitmap.takeError()) {
626           consumeError(std::move(E));
627           return Error::success();
628         }
629 
630         // Since the bitmap identifies the executed test vectors for an MC/DC
631         // DecisionRegion, all of the information is now available to process.
632         // This is where the bulk of the MC/DC progressing takes place.
633         Expected<MCDCRecord> Record = Ctx.evaluateMCDCRegion(
634             *MCDCDecision, *ExecutedTestVectorBitmap, MCDCBranches);
635         if (auto E = Record.takeError()) {
636           consumeError(std::move(E));
637           return Error::success();
638         }
639 
640         // Save the MC/DC Record so that it can be visualized later.
641         Function.pushMCDCRecord(*Record);
642         MCDCBranches.clear();
643       }
644     }
645   }
646 
647   // Don't create records for (filenames, function) pairs we've already seen.
648   auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
649                                           Record.Filenames.end());
650   if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
651     return Error::success();
652 
653   Functions.push_back(std::move(Function));
654 
655   // Performance optimization: keep track of the indices of the function records
656   // which correspond to each filename. This can be used to substantially speed
657   // up queries for coverage info in a file.
658   unsigned RecordIndex = Functions.size() - 1;
659   for (StringRef Filename : Record.Filenames) {
660     auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)];
661     // Note that there may be duplicates in the filename set for a function
662     // record, because of e.g. macro expansions in the function in which both
663     // the macro and the function are defined in the same file.
664     if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
665       RecordIndices.push_back(RecordIndex);
666   }
667 
668   return Error::success();
669 }
670 
671 // This function is for memory optimization by shortening the lifetimes
672 // of CoverageMappingReader instances.
673 Error CoverageMapping::loadFromReaders(
674     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
675     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage) {
676   for (const auto &CoverageReader : CoverageReaders) {
677     for (auto RecordOrErr : *CoverageReader) {
678       if (Error E = RecordOrErr.takeError())
679         return E;
680       const auto &Record = *RecordOrErr;
681       if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader))
682         return E;
683     }
684   }
685   return Error::success();
686 }
687 
688 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
689     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
690     IndexedInstrProfReader &ProfileReader) {
691   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
692   if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
693     return std::move(E);
694   return std::move(Coverage);
695 }
696 
697 // If E is a no_data_found error, returns success. Otherwise returns E.
698 static Error handleMaybeNoDataFoundError(Error E) {
699   return handleErrors(
700       std::move(E), [](const CoverageMapError &CME) {
701         if (CME.get() == coveragemap_error::no_data_found)
702           return static_cast<Error>(Error::success());
703         return make_error<CoverageMapError>(CME.get(), CME.getMessage());
704       });
705 }
706 
707 Error CoverageMapping::loadFromFile(
708     StringRef Filename, StringRef Arch, StringRef CompilationDir,
709     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage,
710     bool &DataFound, SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
711   auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
712       Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false);
713   if (std::error_code EC = CovMappingBufOrErr.getError())
714     return createFileError(Filename, errorCodeToError(EC));
715   MemoryBufferRef CovMappingBufRef =
716       CovMappingBufOrErr.get()->getMemBufferRef();
717   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
718 
719   SmallVector<object::BuildIDRef> BinaryIDs;
720   auto CoverageReadersOrErr = BinaryCoverageReader::create(
721       CovMappingBufRef, Arch, Buffers, CompilationDir,
722       FoundBinaryIDs ? &BinaryIDs : nullptr);
723   if (Error E = CoverageReadersOrErr.takeError()) {
724     E = handleMaybeNoDataFoundError(std::move(E));
725     if (E)
726       return createFileError(Filename, std::move(E));
727     return E;
728   }
729 
730   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
731   for (auto &Reader : CoverageReadersOrErr.get())
732     Readers.push_back(std::move(Reader));
733   if (FoundBinaryIDs && !Readers.empty()) {
734     llvm::append_range(*FoundBinaryIDs,
735                        llvm::map_range(BinaryIDs, [](object::BuildIDRef BID) {
736                          return object::BuildID(BID);
737                        }));
738   }
739   DataFound |= !Readers.empty();
740   if (Error E = loadFromReaders(Readers, ProfileReader, Coverage))
741     return createFileError(Filename, std::move(E));
742   return Error::success();
743 }
744 
745 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
746     ArrayRef<StringRef> ObjectFilenames, StringRef ProfileFilename,
747     vfs::FileSystem &FS, ArrayRef<StringRef> Arches, StringRef CompilationDir,
748     const object::BuildIDFetcher *BIDFetcher, bool CheckBinaryIDs) {
749   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename, FS);
750   if (Error E = ProfileReaderOrErr.takeError())
751     return createFileError(ProfileFilename, std::move(E));
752   auto ProfileReader = std::move(ProfileReaderOrErr.get());
753   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
754   bool DataFound = false;
755 
756   auto GetArch = [&](size_t Idx) {
757     if (Arches.empty())
758       return StringRef();
759     if (Arches.size() == 1)
760       return Arches.front();
761     return Arches[Idx];
762   };
763 
764   SmallVector<object::BuildID> FoundBinaryIDs;
765   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
766     if (Error E =
767             loadFromFile(File.value(), GetArch(File.index()), CompilationDir,
768                          *ProfileReader, *Coverage, DataFound, &FoundBinaryIDs))
769       return std::move(E);
770   }
771 
772   if (BIDFetcher) {
773     std::vector<object::BuildID> ProfileBinaryIDs;
774     if (Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs))
775       return createFileError(ProfileFilename, std::move(E));
776 
777     SmallVector<object::BuildIDRef> BinaryIDsToFetch;
778     if (!ProfileBinaryIDs.empty()) {
779       const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) {
780         return std::lexicographical_compare(A.begin(), A.end(), B.begin(),
781                                             B.end());
782       };
783       llvm::sort(FoundBinaryIDs, Compare);
784       std::set_difference(
785           ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(),
786           FoundBinaryIDs.begin(), FoundBinaryIDs.end(),
787           std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.end()), Compare);
788     }
789 
790     for (object::BuildIDRef BinaryID : BinaryIDsToFetch) {
791       std::optional<std::string> PathOpt = BIDFetcher->fetch(BinaryID);
792       if (PathOpt) {
793         std::string Path = std::move(*PathOpt);
794         StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef();
795         if (Error E = loadFromFile(Path, Arch, CompilationDir, *ProfileReader,
796                                   *Coverage, DataFound))
797           return std::move(E);
798       } else if (CheckBinaryIDs) {
799         return createFileError(
800             ProfileFilename,
801             createStringError(errc::no_such_file_or_directory,
802                               "Missing binary ID: " +
803                                   llvm::toHex(BinaryID, /*LowerCase=*/true)));
804       }
805     }
806   }
807 
808   if (!DataFound)
809     return createFileError(
810         join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
811         make_error<CoverageMapError>(coveragemap_error::no_data_found));
812   return std::move(Coverage);
813 }
814 
815 namespace {
816 
817 /// Distributes functions into instantiation sets.
818 ///
819 /// An instantiation set is a collection of functions that have the same source
820 /// code, ie, template functions specializations.
821 class FunctionInstantiationSetCollector {
822   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
823   MapT InstantiatedFunctions;
824 
825 public:
826   void insert(const FunctionRecord &Function, unsigned FileID) {
827     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
828     while (I != E && I->FileID != FileID)
829       ++I;
830     assert(I != E && "function does not cover the given file");
831     auto &Functions = InstantiatedFunctions[I->startLoc()];
832     Functions.push_back(&Function);
833   }
834 
835   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
836   MapT::iterator end() { return InstantiatedFunctions.end(); }
837 };
838 
839 class SegmentBuilder {
840   std::vector<CoverageSegment> &Segments;
841   SmallVector<const CountedRegion *, 8> ActiveRegions;
842 
843   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
844 
845   /// Emit a segment with the count from \p Region starting at \p StartLoc.
846   //
847   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
848   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
849   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
850                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
851     bool HasCount = !EmitSkippedRegion &&
852                     (Region.Kind != CounterMappingRegion::SkippedRegion);
853 
854     // If the new segment wouldn't affect coverage rendering, skip it.
855     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
856       const auto &Last = Segments.back();
857       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
858           !Last.IsRegionEntry)
859         return;
860     }
861 
862     if (HasCount)
863       Segments.emplace_back(StartLoc.first, StartLoc.second,
864                             Region.ExecutionCount, IsRegionEntry,
865                             Region.Kind == CounterMappingRegion::GapRegion);
866     else
867       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
868 
869     LLVM_DEBUG({
870       const auto &Last = Segments.back();
871       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
872              << " (count = " << Last.Count << ")"
873              << (Last.IsRegionEntry ? ", RegionEntry" : "")
874              << (!Last.HasCount ? ", Skipped" : "")
875              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
876     });
877   }
878 
879   /// Emit segments for active regions which end before \p Loc.
880   ///
881   /// \p Loc: The start location of the next region. If std::nullopt, all active
882   /// regions are completed.
883   /// \p FirstCompletedRegion: Index of the first completed region.
884   void completeRegionsUntil(std::optional<LineColPair> Loc,
885                             unsigned FirstCompletedRegion) {
886     // Sort the completed regions by end location. This makes it simple to
887     // emit closing segments in sorted order.
888     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
889     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
890                       [](const CountedRegion *L, const CountedRegion *R) {
891                         return L->endLoc() < R->endLoc();
892                       });
893 
894     // Emit segments for all completed regions.
895     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
896          ++I) {
897       const auto *CompletedRegion = ActiveRegions[I];
898       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
899              "Completed region ends after start of new region");
900 
901       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
902       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
903 
904       // Don't emit any more segments if they start where the new region begins.
905       if (Loc && CompletedSegmentLoc == *Loc)
906         break;
907 
908       // Don't emit a segment if the next completed region ends at the same
909       // location as this one.
910       if (CompletedSegmentLoc == CompletedRegion->endLoc())
911         continue;
912 
913       // Use the count from the last completed region which ends at this loc.
914       for (unsigned J = I + 1; J < E; ++J)
915         if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
916           CompletedRegion = ActiveRegions[J];
917 
918       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
919     }
920 
921     auto Last = ActiveRegions.back();
922     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
923       // If there's a gap after the end of the last completed region and the
924       // start of the new region, use the last active region to fill the gap.
925       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
926                    false);
927     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
928       // Emit a skipped segment if there are no more active regions. This
929       // ensures that gaps between functions are marked correctly.
930       startSegment(*Last, Last->endLoc(), false, true);
931     }
932 
933     // Pop the completed regions.
934     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
935   }
936 
937   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
938     for (const auto &CR : enumerate(Regions)) {
939       auto CurStartLoc = CR.value().startLoc();
940 
941       // Active regions which end before the current region need to be popped.
942       auto CompletedRegions =
943           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
944                                 [&](const CountedRegion *Region) {
945                                   return !(Region->endLoc() <= CurStartLoc);
946                                 });
947       if (CompletedRegions != ActiveRegions.end()) {
948         unsigned FirstCompletedRegion =
949             std::distance(ActiveRegions.begin(), CompletedRegions);
950         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
951       }
952 
953       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
954 
955       // Try to emit a segment for the current region.
956       if (CurStartLoc == CR.value().endLoc()) {
957         // Avoid making zero-length regions active. If it's the last region,
958         // emit a skipped segment. Otherwise use its predecessor's count.
959         const bool Skipped =
960             (CR.index() + 1) == Regions.size() ||
961             CR.value().Kind == CounterMappingRegion::SkippedRegion;
962         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
963                      CurStartLoc, !GapRegion, Skipped);
964         // If it is skipped segment, create a segment with last pushed
965         // regions's count at CurStartLoc.
966         if (Skipped && !ActiveRegions.empty())
967           startSegment(*ActiveRegions.back(), CurStartLoc, false);
968         continue;
969       }
970       if (CR.index() + 1 == Regions.size() ||
971           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
972         // Emit a segment if the next region doesn't start at the same location
973         // as this one.
974         startSegment(CR.value(), CurStartLoc, !GapRegion);
975       }
976 
977       // This region is active (i.e not completed).
978       ActiveRegions.push_back(&CR.value());
979     }
980 
981     // Complete any remaining active regions.
982     if (!ActiveRegions.empty())
983       completeRegionsUntil(std::nullopt, 0);
984   }
985 
986   /// Sort a nested sequence of regions from a single file.
987   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
988     llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
989       if (LHS.startLoc() != RHS.startLoc())
990         return LHS.startLoc() < RHS.startLoc();
991       if (LHS.endLoc() != RHS.endLoc())
992         // When LHS completely contains RHS, we sort LHS first.
993         return RHS.endLoc() < LHS.endLoc();
994       // If LHS and RHS cover the same area, we need to sort them according
995       // to their kinds so that the most suitable region will become "active"
996       // in combineRegions(). Because we accumulate counter values only from
997       // regions of the same kind as the first region of the area, prefer
998       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
999       static_assert(CounterMappingRegion::CodeRegion <
1000                             CounterMappingRegion::ExpansionRegion &&
1001                         CounterMappingRegion::ExpansionRegion <
1002                             CounterMappingRegion::SkippedRegion,
1003                     "Unexpected order of region kind values");
1004       return LHS.Kind < RHS.Kind;
1005     });
1006   }
1007 
1008   /// Combine counts of regions which cover the same area.
1009   static ArrayRef<CountedRegion>
1010   combineRegions(MutableArrayRef<CountedRegion> Regions) {
1011     if (Regions.empty())
1012       return Regions;
1013     auto Active = Regions.begin();
1014     auto End = Regions.end();
1015     for (auto I = Regions.begin() + 1; I != End; ++I) {
1016       if (Active->startLoc() != I->startLoc() ||
1017           Active->endLoc() != I->endLoc()) {
1018         // Shift to the next region.
1019         ++Active;
1020         if (Active != I)
1021           *Active = *I;
1022         continue;
1023       }
1024       // Merge duplicate region.
1025       // If CodeRegions and ExpansionRegions cover the same area, it's probably
1026       // a macro which is fully expanded to another macro. In that case, we need
1027       // to accumulate counts only from CodeRegions, or else the area will be
1028       // counted twice.
1029       // On the other hand, a macro may have a nested macro in its body. If the
1030       // outer macro is used several times, the ExpansionRegion for the nested
1031       // macro will also be added several times. These ExpansionRegions cover
1032       // the same source locations and have to be combined to reach the correct
1033       // value for that area.
1034       // We add counts of the regions of the same kind as the active region
1035       // to handle the both situations.
1036       if (I->Kind == Active->Kind)
1037         Active->ExecutionCount += I->ExecutionCount;
1038     }
1039     return Regions.drop_back(std::distance(++Active, End));
1040   }
1041 
1042 public:
1043   /// Build a sorted list of CoverageSegments from a list of Regions.
1044   static std::vector<CoverageSegment>
1045   buildSegments(MutableArrayRef<CountedRegion> Regions) {
1046     std::vector<CoverageSegment> Segments;
1047     SegmentBuilder Builder(Segments);
1048 
1049     sortNestedRegions(Regions);
1050     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
1051 
1052     LLVM_DEBUG({
1053       dbgs() << "Combined regions:\n";
1054       for (const auto &CR : CombinedRegions)
1055         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
1056                << CR.LineEnd << ":" << CR.ColumnEnd
1057                << " (count=" << CR.ExecutionCount << ")\n";
1058     });
1059 
1060     Builder.buildSegmentsImpl(CombinedRegions);
1061 
1062 #ifndef NDEBUG
1063     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
1064       const auto &L = Segments[I - 1];
1065       const auto &R = Segments[I];
1066       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
1067         if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
1068           continue;
1069         LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
1070                           << " followed by " << R.Line << ":" << R.Col << "\n");
1071         assert(false && "Coverage segments not unique or sorted");
1072       }
1073     }
1074 #endif
1075 
1076     return Segments;
1077   }
1078 };
1079 
1080 } // end anonymous namespace
1081 
1082 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
1083   std::vector<StringRef> Filenames;
1084   for (const auto &Function : getCoveredFunctions())
1085     llvm::append_range(Filenames, Function.Filenames);
1086   llvm::sort(Filenames);
1087   auto Last = std::unique(Filenames.begin(), Filenames.end());
1088   Filenames.erase(Last, Filenames.end());
1089   return Filenames;
1090 }
1091 
1092 static SmallBitVector gatherFileIDs(StringRef SourceFile,
1093                                     const FunctionRecord &Function) {
1094   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
1095   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
1096     if (SourceFile == Function.Filenames[I])
1097       FilenameEquivalence[I] = true;
1098   return FilenameEquivalence;
1099 }
1100 
1101 /// Return the ID of the file where the definition of the function is located.
1102 static std::optional<unsigned>
1103 findMainViewFileID(const FunctionRecord &Function) {
1104   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
1105   for (const auto &CR : Function.CountedRegions)
1106     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
1107       IsNotExpandedFile[CR.ExpandedFileID] = false;
1108   int I = IsNotExpandedFile.find_first();
1109   if (I == -1)
1110     return std::nullopt;
1111   return I;
1112 }
1113 
1114 /// Check if SourceFile is the file that contains the definition of
1115 /// the Function. Return the ID of the file in that case or std::nullopt
1116 /// otherwise.
1117 static std::optional<unsigned>
1118 findMainViewFileID(StringRef SourceFile, const FunctionRecord &Function) {
1119   std::optional<unsigned> I = findMainViewFileID(Function);
1120   if (I && SourceFile == Function.Filenames[*I])
1121     return I;
1122   return std::nullopt;
1123 }
1124 
1125 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
1126   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
1127 }
1128 
1129 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
1130   CoverageData FileCoverage(Filename);
1131   std::vector<CountedRegion> Regions;
1132 
1133   // Look up the function records in the given file. Due to hash collisions on
1134   // the filename, we may get back some records that are not in the file.
1135   ArrayRef<unsigned> RecordIndices =
1136       getImpreciseRecordIndicesForFilename(Filename);
1137   for (unsigned RecordIndex : RecordIndices) {
1138     const FunctionRecord &Function = Functions[RecordIndex];
1139     auto MainFileID = findMainViewFileID(Filename, Function);
1140     auto FileIDs = gatherFileIDs(Filename, Function);
1141     for (const auto &CR : Function.CountedRegions)
1142       if (FileIDs.test(CR.FileID)) {
1143         Regions.push_back(CR);
1144         if (MainFileID && isExpansion(CR, *MainFileID))
1145           FileCoverage.Expansions.emplace_back(CR, Function);
1146       }
1147     // Capture branch regions specific to the function (excluding expansions).
1148     for (const auto &CR : Function.CountedBranchRegions)
1149       if (FileIDs.test(CR.FileID) && (CR.FileID == CR.ExpandedFileID))
1150         FileCoverage.BranchRegions.push_back(CR);
1151     // Capture MCDC records specific to the function.
1152     for (const auto &MR : Function.MCDCRecords)
1153       if (FileIDs.test(MR.getDecisionRegion().FileID))
1154         FileCoverage.MCDCRecords.push_back(MR);
1155   }
1156 
1157   LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
1158   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1159 
1160   return FileCoverage;
1161 }
1162 
1163 std::vector<InstantiationGroup>
1164 CoverageMapping::getInstantiationGroups(StringRef Filename) const {
1165   FunctionInstantiationSetCollector InstantiationSetCollector;
1166   // Look up the function records in the given file. Due to hash collisions on
1167   // the filename, we may get back some records that are not in the file.
1168   ArrayRef<unsigned> RecordIndices =
1169       getImpreciseRecordIndicesForFilename(Filename);
1170   for (unsigned RecordIndex : RecordIndices) {
1171     const FunctionRecord &Function = Functions[RecordIndex];
1172     auto MainFileID = findMainViewFileID(Filename, Function);
1173     if (!MainFileID)
1174       continue;
1175     InstantiationSetCollector.insert(Function, *MainFileID);
1176   }
1177 
1178   std::vector<InstantiationGroup> Result;
1179   for (auto &InstantiationSet : InstantiationSetCollector) {
1180     InstantiationGroup IG{InstantiationSet.first.first,
1181                           InstantiationSet.first.second,
1182                           std::move(InstantiationSet.second)};
1183     Result.emplace_back(std::move(IG));
1184   }
1185   return Result;
1186 }
1187 
1188 CoverageData
1189 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
1190   auto MainFileID = findMainViewFileID(Function);
1191   if (!MainFileID)
1192     return CoverageData();
1193 
1194   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
1195   std::vector<CountedRegion> Regions;
1196   for (const auto &CR : Function.CountedRegions)
1197     if (CR.FileID == *MainFileID) {
1198       Regions.push_back(CR);
1199       if (isExpansion(CR, *MainFileID))
1200         FunctionCoverage.Expansions.emplace_back(CR, Function);
1201     }
1202   // Capture branch regions specific to the function (excluding expansions).
1203   for (const auto &CR : Function.CountedBranchRegions)
1204     if (CR.FileID == *MainFileID)
1205       FunctionCoverage.BranchRegions.push_back(CR);
1206 
1207   // Capture MCDC records specific to the function.
1208   for (const auto &MR : Function.MCDCRecords)
1209     if (MR.getDecisionRegion().FileID == *MainFileID)
1210       FunctionCoverage.MCDCRecords.push_back(MR);
1211 
1212   LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
1213                     << "\n");
1214   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1215 
1216   return FunctionCoverage;
1217 }
1218 
1219 CoverageData CoverageMapping::getCoverageForExpansion(
1220     const ExpansionRecord &Expansion) const {
1221   CoverageData ExpansionCoverage(
1222       Expansion.Function.Filenames[Expansion.FileID]);
1223   std::vector<CountedRegion> Regions;
1224   for (const auto &CR : Expansion.Function.CountedRegions)
1225     if (CR.FileID == Expansion.FileID) {
1226       Regions.push_back(CR);
1227       if (isExpansion(CR, Expansion.FileID))
1228         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
1229     }
1230   for (const auto &CR : Expansion.Function.CountedBranchRegions)
1231     // Capture branch regions that only pertain to the corresponding expansion.
1232     if (CR.FileID == Expansion.FileID)
1233       ExpansionCoverage.BranchRegions.push_back(CR);
1234 
1235   LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
1236                     << Expansion.FileID << "\n");
1237   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1238 
1239   return ExpansionCoverage;
1240 }
1241 
1242 LineCoverageStats::LineCoverageStats(
1243     ArrayRef<const CoverageSegment *> LineSegments,
1244     const CoverageSegment *WrappedSegment, unsigned Line)
1245     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
1246       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
1247   // Find the minimum number of regions which start in this line.
1248   unsigned MinRegionCount = 0;
1249   auto isStartOfRegion = [](const CoverageSegment *S) {
1250     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
1251   };
1252   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
1253     if (isStartOfRegion(LineSegments[I]))
1254       ++MinRegionCount;
1255 
1256   bool StartOfSkippedRegion = !LineSegments.empty() &&
1257                               !LineSegments.front()->HasCount &&
1258                               LineSegments.front()->IsRegionEntry;
1259 
1260   HasMultipleRegions = MinRegionCount > 1;
1261   Mapped =
1262       !StartOfSkippedRegion &&
1263       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
1264 
1265   // if there is any starting segment at this line with a counter, it must be
1266   // mapped
1267   Mapped |= std::any_of(
1268       LineSegments.begin(), LineSegments.end(),
1269       [](const auto *Seq) { return Seq->IsRegionEntry && Seq->HasCount; });
1270 
1271   if (!Mapped) {
1272     return;
1273   }
1274 
1275   // Pick the max count from the non-gap, region entry segments and the
1276   // wrapped count.
1277   if (WrappedSegment)
1278     ExecutionCount = WrappedSegment->Count;
1279   if (!MinRegionCount)
1280     return;
1281   for (const auto *LS : LineSegments)
1282     if (isStartOfRegion(LS))
1283       ExecutionCount = std::max(ExecutionCount, LS->Count);
1284 }
1285 
1286 LineCoverageIterator &LineCoverageIterator::operator++() {
1287   if (Next == CD.end()) {
1288     Stats = LineCoverageStats();
1289     Ended = true;
1290     return *this;
1291   }
1292   if (Segments.size())
1293     WrappedSegment = Segments.back();
1294   Segments.clear();
1295   while (Next != CD.end() && Next->Line == Line)
1296     Segments.push_back(&*Next++);
1297   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
1298   ++Line;
1299   return *this;
1300 }
1301 
1302 static std::string getCoverageMapErrString(coveragemap_error Err,
1303                                            const std::string &ErrMsg = "") {
1304   std::string Msg;
1305   raw_string_ostream OS(Msg);
1306 
1307   switch (Err) {
1308   case coveragemap_error::success:
1309     OS << "success";
1310     break;
1311   case coveragemap_error::eof:
1312     OS << "end of File";
1313     break;
1314   case coveragemap_error::no_data_found:
1315     OS << "no coverage data found";
1316     break;
1317   case coveragemap_error::unsupported_version:
1318     OS << "unsupported coverage format version";
1319     break;
1320   case coveragemap_error::truncated:
1321     OS << "truncated coverage data";
1322     break;
1323   case coveragemap_error::malformed:
1324     OS << "malformed coverage data";
1325     break;
1326   case coveragemap_error::decompression_failed:
1327     OS << "failed to decompress coverage data (zlib)";
1328     break;
1329   case coveragemap_error::invalid_or_missing_arch_specifier:
1330     OS << "`-arch` specifier is invalid or missing for universal binary";
1331     break;
1332   }
1333 
1334   // If optional error message is not empty, append it to the message.
1335   if (!ErrMsg.empty())
1336     OS << ": " << ErrMsg;
1337 
1338   return Msg;
1339 }
1340 
1341 namespace {
1342 
1343 // FIXME: This class is only here to support the transition to llvm::Error. It
1344 // will be removed once this transition is complete. Clients should prefer to
1345 // deal with the Error value directly, rather than converting to error_code.
1346 class CoverageMappingErrorCategoryType : public std::error_category {
1347   const char *name() const noexcept override { return "llvm.coveragemap"; }
1348   std::string message(int IE) const override {
1349     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
1350   }
1351 };
1352 
1353 } // end anonymous namespace
1354 
1355 std::string CoverageMapError::message() const {
1356   return getCoverageMapErrString(Err, Msg);
1357 }
1358 
1359 const std::error_category &llvm::coverage::coveragemap_category() {
1360   static CoverageMappingErrorCategoryType ErrorCategory;
1361   return ErrorCategory;
1362 }
1363 
1364 char CoverageMapError::ID = 0;
1365