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