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