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