10b57cec5SDimitry Andric //===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains support for clang's and llvm's instrumentation based
100b57cec5SDimitry Andric // code coverage.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/ProfileData/Coverage/CoverageMapping.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
17*b9d9368bSDimitry Andric #include "llvm/ADT/STLExtras.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
20fe013be4SDimitry Andric #include "llvm/ADT/StringExtras.h"
210b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
221ac55f4cSDimitry Andric #include "llvm/Object/BuildID.h"
230b57cec5SDimitry Andric #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
240b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
250b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
260b57cec5SDimitry Andric #include "llvm/Support/Errc.h"
270b57cec5SDimitry Andric #include "llvm/Support/Error.h"
280b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
290b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
30fe013be4SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
310b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
320b57cec5SDimitry Andric #include <algorithm>
330b57cec5SDimitry Andric #include <cassert>
34c9157d92SDimitry Andric #include <cmath>
350b57cec5SDimitry Andric #include <cstdint>
360b57cec5SDimitry Andric #include <iterator>
370b57cec5SDimitry Andric #include <map>
380b57cec5SDimitry Andric #include <memory>
39bdd1243dSDimitry Andric #include <optional>
400b57cec5SDimitry Andric #include <string>
410b57cec5SDimitry Andric #include <system_error>
420b57cec5SDimitry Andric #include <utility>
430b57cec5SDimitry Andric #include <vector>
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric using namespace llvm;
460b57cec5SDimitry Andric using namespace coverage;
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric #define DEBUG_TYPE "coverage-mapping"
490b57cec5SDimitry Andric 
get(const CounterExpression & E)500b57cec5SDimitry Andric Counter CounterExpressionBuilder::get(const CounterExpression &E) {
510b57cec5SDimitry Andric   auto It = ExpressionIndices.find(E);
520b57cec5SDimitry Andric   if (It != ExpressionIndices.end())
530b57cec5SDimitry Andric     return Counter::getExpression(It->second);
540b57cec5SDimitry Andric   unsigned I = Expressions.size();
550b57cec5SDimitry Andric   Expressions.push_back(E);
560b57cec5SDimitry Andric   ExpressionIndices[E] = I;
570b57cec5SDimitry Andric   return Counter::getExpression(I);
580b57cec5SDimitry Andric }
590b57cec5SDimitry Andric 
extractTerms(Counter C,int Factor,SmallVectorImpl<Term> & Terms)600b57cec5SDimitry Andric void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
610b57cec5SDimitry Andric                                             SmallVectorImpl<Term> &Terms) {
620b57cec5SDimitry Andric   switch (C.getKind()) {
630b57cec5SDimitry Andric   case Counter::Zero:
640b57cec5SDimitry Andric     break;
650b57cec5SDimitry Andric   case Counter::CounterValueReference:
660b57cec5SDimitry Andric     Terms.emplace_back(C.getCounterID(), Factor);
670b57cec5SDimitry Andric     break;
680b57cec5SDimitry Andric   case Counter::Expression:
690b57cec5SDimitry Andric     const auto &E = Expressions[C.getExpressionID()];
700b57cec5SDimitry Andric     extractTerms(E.LHS, Factor, Terms);
710b57cec5SDimitry Andric     extractTerms(
720b57cec5SDimitry Andric         E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
730b57cec5SDimitry Andric     break;
740b57cec5SDimitry Andric   }
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric 
simplify(Counter ExpressionTree)770b57cec5SDimitry Andric Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
780b57cec5SDimitry Andric   // Gather constant terms.
790b57cec5SDimitry Andric   SmallVector<Term, 32> Terms;
800b57cec5SDimitry Andric   extractTerms(ExpressionTree, +1, Terms);
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   // If there are no terms, this is just a zero. The algorithm below assumes at
830b57cec5SDimitry Andric   // least one term.
840b57cec5SDimitry Andric   if (Terms.size() == 0)
850b57cec5SDimitry Andric     return Counter::getZero();
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric   // Group the terms by counter ID.
880b57cec5SDimitry Andric   llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
890b57cec5SDimitry Andric     return LHS.CounterID < RHS.CounterID;
900b57cec5SDimitry Andric   });
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   // Combine terms by counter ID to eliminate counters that sum to zero.
930b57cec5SDimitry Andric   auto Prev = Terms.begin();
940b57cec5SDimitry Andric   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
950b57cec5SDimitry Andric     if (I->CounterID == Prev->CounterID) {
960b57cec5SDimitry Andric       Prev->Factor += I->Factor;
970b57cec5SDimitry Andric       continue;
980b57cec5SDimitry Andric     }
990b57cec5SDimitry Andric     ++Prev;
1000b57cec5SDimitry Andric     *Prev = *I;
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric   Terms.erase(++Prev, Terms.end());
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   Counter C;
1050b57cec5SDimitry Andric   // Create additions. We do this before subtractions to avoid constructs like
1060b57cec5SDimitry Andric   // ((0 - X) + Y), as opposed to (Y - X).
1070b57cec5SDimitry Andric   for (auto T : Terms) {
1080b57cec5SDimitry Andric     if (T.Factor <= 0)
1090b57cec5SDimitry Andric       continue;
1100b57cec5SDimitry Andric     for (int I = 0; I < T.Factor; ++I)
1110b57cec5SDimitry Andric       if (C.isZero())
1120b57cec5SDimitry Andric         C = Counter::getCounter(T.CounterID);
1130b57cec5SDimitry Andric       else
1140b57cec5SDimitry Andric         C = get(CounterExpression(CounterExpression::Add, C,
1150b57cec5SDimitry Andric                                   Counter::getCounter(T.CounterID)));
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   // Create subtractions.
1190b57cec5SDimitry Andric   for (auto T : Terms) {
1200b57cec5SDimitry Andric     if (T.Factor >= 0)
1210b57cec5SDimitry Andric       continue;
1220b57cec5SDimitry Andric     for (int I = 0; I < -T.Factor; ++I)
1230b57cec5SDimitry Andric       C = get(CounterExpression(CounterExpression::Subtract, C,
1240b57cec5SDimitry Andric                                 Counter::getCounter(T.CounterID)));
1250b57cec5SDimitry Andric   }
1260b57cec5SDimitry Andric   return C;
1270b57cec5SDimitry Andric }
1280b57cec5SDimitry Andric 
add(Counter LHS,Counter RHS,bool Simplify)12981ad6265SDimitry Andric Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS, bool Simplify) {
13081ad6265SDimitry Andric   auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS));
13181ad6265SDimitry Andric   return Simplify ? simplify(Cnt) : Cnt;
1320b57cec5SDimitry Andric }
1330b57cec5SDimitry Andric 
subtract(Counter LHS,Counter RHS,bool Simplify)13481ad6265SDimitry Andric Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS,
13581ad6265SDimitry Andric                                            bool Simplify) {
13681ad6265SDimitry Andric   auto Cnt = get(CounterExpression(CounterExpression::Subtract, LHS, RHS));
13781ad6265SDimitry Andric   return Simplify ? simplify(Cnt) : Cnt;
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
dump(const Counter & C,raw_ostream & OS) const1400b57cec5SDimitry Andric void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
1410b57cec5SDimitry Andric   switch (C.getKind()) {
1420b57cec5SDimitry Andric   case Counter::Zero:
1430b57cec5SDimitry Andric     OS << '0';
1440b57cec5SDimitry Andric     return;
1450b57cec5SDimitry Andric   case Counter::CounterValueReference:
1460b57cec5SDimitry Andric     OS << '#' << C.getCounterID();
1470b57cec5SDimitry Andric     break;
1480b57cec5SDimitry Andric   case Counter::Expression: {
1490b57cec5SDimitry Andric     if (C.getExpressionID() >= Expressions.size())
1500b57cec5SDimitry Andric       return;
1510b57cec5SDimitry Andric     const auto &E = Expressions[C.getExpressionID()];
1520b57cec5SDimitry Andric     OS << '(';
1530b57cec5SDimitry Andric     dump(E.LHS, OS);
1540b57cec5SDimitry Andric     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
1550b57cec5SDimitry Andric     dump(E.RHS, OS);
1560b57cec5SDimitry Andric     OS << ')';
1570b57cec5SDimitry Andric     break;
1580b57cec5SDimitry Andric   }
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric   if (CounterValues.empty())
1610b57cec5SDimitry Andric     return;
1620b57cec5SDimitry Andric   Expected<int64_t> Value = evaluate(C);
1630b57cec5SDimitry Andric   if (auto E = Value.takeError()) {
1640b57cec5SDimitry Andric     consumeError(std::move(E));
1650b57cec5SDimitry Andric     return;
1660b57cec5SDimitry Andric   }
1670b57cec5SDimitry Andric   OS << '[' << *Value << ']';
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric 
evaluate(const Counter & C) const1700b57cec5SDimitry Andric Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
171c9157d92SDimitry Andric   struct StackElem {
172c9157d92SDimitry Andric     Counter ICounter;
173c9157d92SDimitry Andric     int64_t LHS = 0;
174c9157d92SDimitry Andric     enum {
175c9157d92SDimitry Andric       KNeverVisited = 0,
176c9157d92SDimitry Andric       KVisitedOnce = 1,
177c9157d92SDimitry Andric       KVisitedTwice = 2,
178c9157d92SDimitry Andric     } VisitCount = KNeverVisited;
179c9157d92SDimitry Andric   };
180c9157d92SDimitry Andric 
181c9157d92SDimitry Andric   std::stack<StackElem> CounterStack;
182c9157d92SDimitry Andric   CounterStack.push({C});
183c9157d92SDimitry Andric 
184c9157d92SDimitry Andric   int64_t LastPoppedValue;
185c9157d92SDimitry Andric 
186c9157d92SDimitry Andric   while (!CounterStack.empty()) {
187c9157d92SDimitry Andric     StackElem &Current = CounterStack.top();
188c9157d92SDimitry Andric 
189c9157d92SDimitry Andric     switch (Current.ICounter.getKind()) {
1900b57cec5SDimitry Andric     case Counter::Zero:
191c9157d92SDimitry Andric       LastPoppedValue = 0;
192c9157d92SDimitry Andric       CounterStack.pop();
193c9157d92SDimitry Andric       break;
1940b57cec5SDimitry Andric     case Counter::CounterValueReference:
195c9157d92SDimitry Andric       if (Current.ICounter.getCounterID() >= CounterValues.size())
1960b57cec5SDimitry Andric         return errorCodeToError(errc::argument_out_of_domain);
197c9157d92SDimitry Andric       LastPoppedValue = CounterValues[Current.ICounter.getCounterID()];
198c9157d92SDimitry Andric       CounterStack.pop();
199c9157d92SDimitry Andric       break;
2000b57cec5SDimitry Andric     case Counter::Expression: {
201c9157d92SDimitry Andric       if (Current.ICounter.getExpressionID() >= Expressions.size())
2020b57cec5SDimitry Andric         return errorCodeToError(errc::argument_out_of_domain);
203c9157d92SDimitry Andric       const auto &E = Expressions[Current.ICounter.getExpressionID()];
204c9157d92SDimitry Andric       if (Current.VisitCount == StackElem::KNeverVisited) {
205c9157d92SDimitry Andric         CounterStack.push(StackElem{E.LHS});
206c9157d92SDimitry Andric         Current.VisitCount = StackElem::KVisitedOnce;
207c9157d92SDimitry Andric       } else if (Current.VisitCount == StackElem::KVisitedOnce) {
208c9157d92SDimitry Andric         Current.LHS = LastPoppedValue;
209c9157d92SDimitry Andric         CounterStack.push(StackElem{E.RHS});
210c9157d92SDimitry Andric         Current.VisitCount = StackElem::KVisitedTwice;
211c9157d92SDimitry Andric       } else {
212c9157d92SDimitry Andric         int64_t LHS = Current.LHS;
213c9157d92SDimitry Andric         int64_t RHS = LastPoppedValue;
214c9157d92SDimitry Andric         LastPoppedValue =
215c9157d92SDimitry Andric             E.Kind == CounterExpression::Subtract ? LHS - RHS : LHS + RHS;
216c9157d92SDimitry Andric         CounterStack.pop();
217c9157d92SDimitry Andric       }
218c9157d92SDimitry Andric       break;
2190b57cec5SDimitry Andric     }
2200b57cec5SDimitry Andric     }
221c9157d92SDimitry Andric   }
222c9157d92SDimitry Andric 
223c9157d92SDimitry Andric   return LastPoppedValue;
224c9157d92SDimitry Andric }
225c9157d92SDimitry Andric 
evaluateBitmap(const CounterMappingRegion * MCDCDecision) const226c9157d92SDimitry Andric Expected<BitVector> CounterMappingContext::evaluateBitmap(
227c9157d92SDimitry Andric     const CounterMappingRegion *MCDCDecision) const {
228c9157d92SDimitry Andric   unsigned ID = MCDCDecision->MCDCParams.BitmapIdx;
229c9157d92SDimitry Andric   unsigned NC = MCDCDecision->MCDCParams.NumConditions;
230c9157d92SDimitry Andric   unsigned SizeInBits = llvm::alignTo(uint64_t(1) << NC, CHAR_BIT);
231c9157d92SDimitry Andric   unsigned SizeInBytes = SizeInBits / CHAR_BIT;
232c9157d92SDimitry Andric 
233a58f00eaSDimitry Andric   assert(ID + SizeInBytes <= BitmapBytes.size() && "BitmapBytes overrun");
234c9157d92SDimitry Andric   ArrayRef<uint8_t> Bytes(&BitmapBytes[ID], SizeInBytes);
235c9157d92SDimitry Andric 
236c9157d92SDimitry Andric   // Mask each bitmap byte into the BitVector. Go in reverse so that the
237c9157d92SDimitry Andric   // bitvector can just be shifted over by one byte on each iteration.
238c9157d92SDimitry Andric   BitVector Result(SizeInBits, false);
239c9157d92SDimitry Andric   for (auto Byte = std::rbegin(Bytes); Byte != std::rend(Bytes); ++Byte) {
240c9157d92SDimitry Andric     uint32_t Data = *Byte;
241c9157d92SDimitry Andric     Result <<= CHAR_BIT;
242c9157d92SDimitry Andric     Result.setBitsInMask(&Data, 1);
243c9157d92SDimitry Andric   }
244c9157d92SDimitry Andric   return Result;
245c9157d92SDimitry Andric }
246c9157d92SDimitry Andric 
247c9157d92SDimitry Andric class MCDCRecordProcessor {
248c9157d92SDimitry Andric   /// A bitmap representing the executed test vectors for a boolean expression.
249c9157d92SDimitry Andric   /// Each index of the bitmap corresponds to a possible test vector. An index
250c9157d92SDimitry Andric   /// with a bit value of '1' indicates that the corresponding Test Vector
251c9157d92SDimitry Andric   /// identified by that index was executed.
252a58f00eaSDimitry Andric   const BitVector &ExecutedTestVectorBitmap;
253c9157d92SDimitry Andric 
254c9157d92SDimitry Andric   /// Decision Region to which the ExecutedTestVectorBitmap applies.
255a58f00eaSDimitry Andric   const CounterMappingRegion &Region;
256c9157d92SDimitry Andric 
257c9157d92SDimitry Andric   /// Array of branch regions corresponding each conditions in the boolean
258c9157d92SDimitry Andric   /// expression.
259a58f00eaSDimitry Andric   ArrayRef<const CounterMappingRegion *> Branches;
260c9157d92SDimitry Andric 
261c9157d92SDimitry Andric   /// Total number of conditions in the boolean expression.
262c9157d92SDimitry Andric   unsigned NumConditions;
263c9157d92SDimitry Andric 
264c9157d92SDimitry Andric   /// Mapping of a condition ID to its corresponding branch region.
265c9157d92SDimitry Andric   llvm::DenseMap<unsigned, const CounterMappingRegion *> Map;
266c9157d92SDimitry Andric 
267c9157d92SDimitry Andric   /// Vector used to track whether a condition is constant folded.
268c9157d92SDimitry Andric   MCDCRecord::BoolVector Folded;
269c9157d92SDimitry Andric 
270c9157d92SDimitry Andric   /// Mapping of calculated MC/DC Independence Pairs for each condition.
271c9157d92SDimitry Andric   MCDCRecord::TVPairMap IndependencePairs;
272c9157d92SDimitry Andric 
273c9157d92SDimitry Andric   /// Total number of possible Test Vectors for the boolean expression.
274c9157d92SDimitry Andric   MCDCRecord::TestVectors TestVectors;
275c9157d92SDimitry Andric 
276c9157d92SDimitry Andric   /// Actual executed Test Vectors for the boolean expression, based on
277c9157d92SDimitry Andric   /// ExecutedTestVectorBitmap.
278c9157d92SDimitry Andric   MCDCRecord::TestVectors ExecVectors;
279c9157d92SDimitry Andric 
280c9157d92SDimitry Andric public:
MCDCRecordProcessor(const BitVector & Bitmap,const CounterMappingRegion & Region,ArrayRef<const CounterMappingRegion * > Branches)281a58f00eaSDimitry Andric   MCDCRecordProcessor(const BitVector &Bitmap,
282a58f00eaSDimitry Andric                       const CounterMappingRegion &Region,
283a58f00eaSDimitry Andric                       ArrayRef<const CounterMappingRegion *> Branches)
284c9157d92SDimitry Andric       : ExecutedTestVectorBitmap(Bitmap), Region(Region), Branches(Branches),
285c9157d92SDimitry Andric         NumConditions(Region.MCDCParams.NumConditions),
286c9157d92SDimitry Andric         Folded(NumConditions, false), IndependencePairs(NumConditions),
287c9157d92SDimitry Andric         TestVectors((size_t)1 << NumConditions) {}
288c9157d92SDimitry Andric 
289c9157d92SDimitry Andric private:
recordTestVector(MCDCRecord::TestVector & TV,MCDCRecord::CondState Result)290c9157d92SDimitry Andric   void recordTestVector(MCDCRecord::TestVector &TV,
291c9157d92SDimitry Andric                         MCDCRecord::CondState Result) {
292c9157d92SDimitry Andric     // Calculate an index that is used to identify the test vector in a vector
293c9157d92SDimitry Andric     // of test vectors.  This index also corresponds to the index values of an
294c9157d92SDimitry Andric     // MCDC Region's bitmap (see findExecutedTestVectors()).
295c9157d92SDimitry Andric     unsigned Index = 0;
296c9157d92SDimitry Andric     for (auto Cond = std::rbegin(TV); Cond != std::rend(TV); ++Cond) {
297c9157d92SDimitry Andric       Index <<= 1;
298c9157d92SDimitry Andric       Index |= (*Cond == MCDCRecord::MCDC_True) ? 0x1 : 0x0;
299c9157d92SDimitry Andric     }
300c9157d92SDimitry Andric 
301c9157d92SDimitry Andric     // Copy the completed test vector to the vector of testvectors.
302c9157d92SDimitry Andric     TestVectors[Index] = TV;
303c9157d92SDimitry Andric 
304c9157d92SDimitry Andric     // The final value (T,F) is equal to the last non-dontcare state on the
305c9157d92SDimitry Andric     // path (in a short-circuiting system).
306c9157d92SDimitry Andric     TestVectors[Index].push_back(Result);
307c9157d92SDimitry Andric   }
308c9157d92SDimitry Andric 
shouldCopyOffTestVectorForTruePath(MCDCRecord::TestVector & TV,unsigned ID)309c9157d92SDimitry Andric   void shouldCopyOffTestVectorForTruePath(MCDCRecord::TestVector &TV,
310c9157d92SDimitry Andric                                           unsigned ID) {
311c9157d92SDimitry Andric     // Branch regions are hashed based on an ID.
312c9157d92SDimitry Andric     const CounterMappingRegion *Branch = Map[ID];
313c9157d92SDimitry Andric 
314c9157d92SDimitry Andric     TV[ID - 1] = MCDCRecord::MCDC_True;
315c9157d92SDimitry Andric     if (Branch->MCDCParams.TrueID > 0)
316c9157d92SDimitry Andric       buildTestVector(TV, Branch->MCDCParams.TrueID);
317c9157d92SDimitry Andric     else
318c9157d92SDimitry Andric       recordTestVector(TV, MCDCRecord::MCDC_True);
319c9157d92SDimitry Andric   }
320c9157d92SDimitry Andric 
shouldCopyOffTestVectorForFalsePath(MCDCRecord::TestVector & TV,unsigned ID)321c9157d92SDimitry Andric   void shouldCopyOffTestVectorForFalsePath(MCDCRecord::TestVector &TV,
322c9157d92SDimitry Andric                                            unsigned ID) {
323c9157d92SDimitry Andric     // Branch regions are hashed based on an ID.
324c9157d92SDimitry Andric     const CounterMappingRegion *Branch = Map[ID];
325c9157d92SDimitry Andric 
326c9157d92SDimitry Andric     TV[ID - 1] = MCDCRecord::MCDC_False;
327c9157d92SDimitry Andric     if (Branch->MCDCParams.FalseID > 0)
328c9157d92SDimitry Andric       buildTestVector(TV, Branch->MCDCParams.FalseID);
329c9157d92SDimitry Andric     else
330c9157d92SDimitry Andric       recordTestVector(TV, MCDCRecord::MCDC_False);
331c9157d92SDimitry Andric   }
332c9157d92SDimitry Andric 
333c9157d92SDimitry Andric   /// Starting with the base test vector, build a comprehensive list of
334c9157d92SDimitry Andric   /// possible test vectors by recursively walking the branch condition IDs
335c9157d92SDimitry Andric   /// provided. Once an end node is reached, record the test vector in a vector
336c9157d92SDimitry Andric   /// of test vectors that can be matched against during MC/DC analysis, and
337c9157d92SDimitry Andric   /// then reset the positions to 'DontCare'.
buildTestVector(MCDCRecord::TestVector & TV,unsigned ID=1)338c9157d92SDimitry Andric   void buildTestVector(MCDCRecord::TestVector &TV, unsigned ID = 1) {
339c9157d92SDimitry Andric     shouldCopyOffTestVectorForTruePath(TV, ID);
340c9157d92SDimitry Andric     shouldCopyOffTestVectorForFalsePath(TV, ID);
341c9157d92SDimitry Andric 
342c9157d92SDimitry Andric     // Reset back to DontCare.
343c9157d92SDimitry Andric     TV[ID - 1] = MCDCRecord::MCDC_DontCare;
344c9157d92SDimitry Andric   }
345c9157d92SDimitry Andric 
346c9157d92SDimitry Andric   /// Walk the bits in the bitmap.  A bit set to '1' indicates that the test
347c9157d92SDimitry Andric   /// vector at the corresponding index was executed during a test run.
findExecutedTestVectors(const BitVector & ExecutedTestVectorBitmap)348a58f00eaSDimitry Andric   void findExecutedTestVectors(const BitVector &ExecutedTestVectorBitmap) {
349c9157d92SDimitry Andric     for (unsigned Idx = 0; Idx < ExecutedTestVectorBitmap.size(); ++Idx) {
350c9157d92SDimitry Andric       if (ExecutedTestVectorBitmap[Idx] == 0)
351c9157d92SDimitry Andric         continue;
352c9157d92SDimitry Andric       assert(!TestVectors[Idx].empty() && "Test Vector doesn't exist.");
353c9157d92SDimitry Andric       ExecVectors.push_back(TestVectors[Idx]);
354c9157d92SDimitry Andric     }
355c9157d92SDimitry Andric   }
356c9157d92SDimitry Andric 
357c9157d92SDimitry Andric   /// For a given condition and two executed Test Vectors, A and B, see if the
358c9157d92SDimitry Andric   /// two test vectors match forming an Independence Pair for the condition.
359c9157d92SDimitry Andric   /// For two test vectors to match, the following must be satisfied:
360c9157d92SDimitry Andric   /// - The condition's value in each test vector must be opposite.
361c9157d92SDimitry Andric   /// - The result's value in each test vector must be opposite.
362c9157d92SDimitry Andric   /// - All other conditions' values must be equal or marked as "don't care".
matchTestVectors(unsigned Aidx,unsigned Bidx,unsigned ConditionIdx)363c9157d92SDimitry Andric   bool matchTestVectors(unsigned Aidx, unsigned Bidx, unsigned ConditionIdx) {
364c9157d92SDimitry Andric     const MCDCRecord::TestVector &A = ExecVectors[Aidx];
365c9157d92SDimitry Andric     const MCDCRecord::TestVector &B = ExecVectors[Bidx];
366c9157d92SDimitry Andric 
367c9157d92SDimitry Andric     // If condition values in both A and B aren't opposites, no match.
368c9157d92SDimitry Andric     // Because a value can be 0 (false), 1 (true), or -1 (DontCare), a check
369c9157d92SDimitry Andric     // that "XOR != 1" will ensure that the values are opposites and that
370c9157d92SDimitry Andric     // neither of them is a DontCare.
371c9157d92SDimitry Andric     //  1 XOR  0 ==  1 | 0 XOR  0 ==  0 | -1 XOR  0 == -1
372c9157d92SDimitry Andric     //  1 XOR  1 ==  0 | 0 XOR  1 ==  1 | -1 XOR  1 == -2
373c9157d92SDimitry Andric     //  1 XOR -1 == -2 | 0 XOR -1 == -1 | -1 XOR -1 ==  0
374c9157d92SDimitry Andric     if ((A[ConditionIdx] ^ B[ConditionIdx]) != 1)
375c9157d92SDimitry Andric       return false;
376c9157d92SDimitry Andric 
377c9157d92SDimitry Andric     // If the results of both A and B aren't opposites, no match.
378c9157d92SDimitry Andric     if ((A[NumConditions] ^ B[NumConditions]) != 1)
379c9157d92SDimitry Andric       return false;
380c9157d92SDimitry Andric 
381c9157d92SDimitry Andric     for (unsigned Idx = 0; Idx < NumConditions; ++Idx) {
382c9157d92SDimitry Andric       // Look for other conditions that don't match. Skip over the given
383c9157d92SDimitry Andric       // Condition as well as any conditions marked as "don't care".
384c9157d92SDimitry Andric       const auto ARecordTyForCond = A[Idx];
385c9157d92SDimitry Andric       const auto BRecordTyForCond = B[Idx];
386c9157d92SDimitry Andric       if (Idx == ConditionIdx ||
387c9157d92SDimitry Andric           ARecordTyForCond == MCDCRecord::MCDC_DontCare ||
388c9157d92SDimitry Andric           BRecordTyForCond == MCDCRecord::MCDC_DontCare)
389c9157d92SDimitry Andric         continue;
390c9157d92SDimitry Andric 
391c9157d92SDimitry Andric       // If there is a condition mismatch with any of the other conditions,
392c9157d92SDimitry Andric       // there is no match for the test vectors.
393c9157d92SDimitry Andric       if (ARecordTyForCond != BRecordTyForCond)
394c9157d92SDimitry Andric         return false;
395c9157d92SDimitry Andric     }
396c9157d92SDimitry Andric 
397c9157d92SDimitry Andric     // Otherwise, match.
398c9157d92SDimitry Andric     return true;
399c9157d92SDimitry Andric   }
400c9157d92SDimitry Andric 
401c9157d92SDimitry Andric   /// Find all possible Independence Pairs for a boolean expression given its
402c9157d92SDimitry Andric   /// executed Test Vectors.  This process involves looking at each condition
403c9157d92SDimitry Andric   /// and attempting to find two Test Vectors that "match", giving us a pair.
findIndependencePairs()404c9157d92SDimitry Andric   void findIndependencePairs() {
405c9157d92SDimitry Andric     unsigned NumTVs = ExecVectors.size();
406c9157d92SDimitry Andric 
407c9157d92SDimitry Andric     // For each condition.
408c9157d92SDimitry Andric     for (unsigned C = 0; C < NumConditions; ++C) {
409c9157d92SDimitry Andric       bool PairFound = false;
410c9157d92SDimitry Andric 
411c9157d92SDimitry Andric       // For each executed test vector.
412c9157d92SDimitry Andric       for (unsigned I = 0; !PairFound && I < NumTVs; ++I) {
413c9157d92SDimitry Andric         // Compared to every other executed test vector.
414c9157d92SDimitry Andric         for (unsigned J = 0; !PairFound && J < NumTVs; ++J) {
415c9157d92SDimitry Andric           if (I == J)
416c9157d92SDimitry Andric             continue;
417c9157d92SDimitry Andric 
418c9157d92SDimitry Andric           // If a matching pair of vectors is found, record them.
419c9157d92SDimitry Andric           if ((PairFound = matchTestVectors(I, J, C)))
420c9157d92SDimitry Andric             IndependencePairs[C] = std::make_pair(I + 1, J + 1);
421c9157d92SDimitry Andric         }
422c9157d92SDimitry Andric       }
423c9157d92SDimitry Andric     }
424c9157d92SDimitry Andric   }
425c9157d92SDimitry Andric 
426c9157d92SDimitry Andric public:
427c9157d92SDimitry Andric   /// Process the MC/DC Record in order to produce a result for a boolean
428c9157d92SDimitry Andric   /// expression. This process includes tracking the conditions that comprise
429c9157d92SDimitry Andric   /// the decision region, calculating the list of all possible test vectors,
430c9157d92SDimitry Andric   /// marking the executed test vectors, and then finding an Independence Pair
431c9157d92SDimitry Andric   /// out of the executed test vectors for each condition in the boolean
432c9157d92SDimitry Andric   /// expression. A condition is tracked to ensure that its ID can be mapped to
433c9157d92SDimitry Andric   /// its ordinal position in the boolean expression. The condition's source
434c9157d92SDimitry Andric   /// location is also tracked, as well as whether it is constant folded (in
435c9157d92SDimitry Andric   /// which case it is excuded from the metric).
processMCDCRecord()436c9157d92SDimitry Andric   MCDCRecord processMCDCRecord() {
437c9157d92SDimitry Andric     unsigned I = 0;
438c9157d92SDimitry Andric     MCDCRecord::CondIDMap PosToID;
439c9157d92SDimitry Andric     MCDCRecord::LineColPairMap CondLoc;
440c9157d92SDimitry Andric 
441c9157d92SDimitry Andric     // Walk the Record's BranchRegions (representing Conditions) in order to:
442c9157d92SDimitry Andric     // - Hash the condition based on its corresponding ID. This will be used to
443c9157d92SDimitry Andric     //   calculate the test vectors.
444c9157d92SDimitry Andric     // - Keep a map of the condition's ordinal position (1, 2, 3, 4) to its
445c9157d92SDimitry Andric     //   actual ID.  This will be used to visualize the conditions in the
446c9157d92SDimitry Andric     //   correct order.
447c9157d92SDimitry Andric     // - Keep track of the condition source location. This will be used to
448c9157d92SDimitry Andric     //   visualize where the condition is.
449c9157d92SDimitry Andric     // - Record whether the condition is constant folded so that we exclude it
450c9157d92SDimitry Andric     //   from being measured.
451a58f00eaSDimitry Andric     for (const auto *B : Branches) {
452a58f00eaSDimitry Andric       Map[B->MCDCParams.ID] = B;
453a58f00eaSDimitry Andric       PosToID[I] = B->MCDCParams.ID - 1;
454a58f00eaSDimitry Andric       CondLoc[I] = B->startLoc();
455a58f00eaSDimitry Andric       Folded[I++] = (B->Count.isZero() && B->FalseCount.isZero());
456c9157d92SDimitry Andric     }
457c9157d92SDimitry Andric 
458c9157d92SDimitry Andric     // Initialize a base test vector as 'DontCare'.
459c9157d92SDimitry Andric     MCDCRecord::TestVector TV(NumConditions, MCDCRecord::MCDC_DontCare);
460c9157d92SDimitry Andric 
461c9157d92SDimitry Andric     // Use the base test vector to build the list of all possible test vectors.
462c9157d92SDimitry Andric     buildTestVector(TV);
463c9157d92SDimitry Andric 
464c9157d92SDimitry Andric     // Using Profile Bitmap from runtime, mark the executed test vectors.
465c9157d92SDimitry Andric     findExecutedTestVectors(ExecutedTestVectorBitmap);
466c9157d92SDimitry Andric 
467c9157d92SDimitry Andric     // Compare executed test vectors against each other to find an independence
468c9157d92SDimitry Andric     // pairs for each condition.  This processing takes the most time.
469c9157d92SDimitry Andric     findIndependencePairs();
470c9157d92SDimitry Andric 
471c9157d92SDimitry Andric     // Record Test vectors, executed vectors, and independence pairs.
472c9157d92SDimitry Andric     MCDCRecord Res(Region, ExecVectors, IndependencePairs, Folded, PosToID,
473c9157d92SDimitry Andric                    CondLoc);
474c9157d92SDimitry Andric     return Res;
475c9157d92SDimitry Andric   }
476c9157d92SDimitry Andric };
477c9157d92SDimitry Andric 
evaluateMCDCRegion(const CounterMappingRegion & Region,const BitVector & ExecutedTestVectorBitmap,ArrayRef<const CounterMappingRegion * > Branches)478c9157d92SDimitry Andric Expected<MCDCRecord> CounterMappingContext::evaluateMCDCRegion(
479a58f00eaSDimitry Andric     const CounterMappingRegion &Region,
480a58f00eaSDimitry Andric     const BitVector &ExecutedTestVectorBitmap,
481a58f00eaSDimitry Andric     ArrayRef<const CounterMappingRegion *> Branches) {
482c9157d92SDimitry Andric 
483c9157d92SDimitry Andric   MCDCRecordProcessor MCDCProcessor(ExecutedTestVectorBitmap, Region, Branches);
484c9157d92SDimitry Andric   return MCDCProcessor.processMCDCRecord();
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
getMaxCounterID(const Counter & C) const487fe6060f1SDimitry Andric unsigned CounterMappingContext::getMaxCounterID(const Counter &C) const {
488c9157d92SDimitry Andric   struct StackElem {
489c9157d92SDimitry Andric     Counter ICounter;
490c9157d92SDimitry Andric     int64_t LHS = 0;
491c9157d92SDimitry Andric     enum {
492c9157d92SDimitry Andric       KNeverVisited = 0,
493c9157d92SDimitry Andric       KVisitedOnce = 1,
494c9157d92SDimitry Andric       KVisitedTwice = 2,
495c9157d92SDimitry Andric     } VisitCount = KNeverVisited;
496c9157d92SDimitry Andric   };
497c9157d92SDimitry Andric 
498c9157d92SDimitry Andric   std::stack<StackElem> CounterStack;
499c9157d92SDimitry Andric   CounterStack.push({C});
500c9157d92SDimitry Andric 
501c9157d92SDimitry Andric   int64_t LastPoppedValue;
502c9157d92SDimitry Andric 
503c9157d92SDimitry Andric   while (!CounterStack.empty()) {
504c9157d92SDimitry Andric     StackElem &Current = CounterStack.top();
505c9157d92SDimitry Andric 
506c9157d92SDimitry Andric     switch (Current.ICounter.getKind()) {
507fe6060f1SDimitry Andric     case Counter::Zero:
508c9157d92SDimitry Andric       LastPoppedValue = 0;
509c9157d92SDimitry Andric       CounterStack.pop();
510c9157d92SDimitry Andric       break;
511fe6060f1SDimitry Andric     case Counter::CounterValueReference:
512c9157d92SDimitry Andric       LastPoppedValue = Current.ICounter.getCounterID();
513c9157d92SDimitry Andric       CounterStack.pop();
514c9157d92SDimitry Andric       break;
515fe6060f1SDimitry Andric     case Counter::Expression: {
516c9157d92SDimitry Andric       if (Current.ICounter.getExpressionID() >= Expressions.size()) {
517c9157d92SDimitry Andric         LastPoppedValue = 0;
518c9157d92SDimitry Andric         CounterStack.pop();
519c9157d92SDimitry Andric       } else {
520c9157d92SDimitry Andric         const auto &E = Expressions[Current.ICounter.getExpressionID()];
521c9157d92SDimitry Andric         if (Current.VisitCount == StackElem::KNeverVisited) {
522c9157d92SDimitry Andric           CounterStack.push(StackElem{E.LHS});
523c9157d92SDimitry Andric           Current.VisitCount = StackElem::KVisitedOnce;
524c9157d92SDimitry Andric         } else if (Current.VisitCount == StackElem::KVisitedOnce) {
525c9157d92SDimitry Andric           Current.LHS = LastPoppedValue;
526c9157d92SDimitry Andric           CounterStack.push(StackElem{E.RHS});
527c9157d92SDimitry Andric           Current.VisitCount = StackElem::KVisitedTwice;
528c9157d92SDimitry Andric         } else {
529c9157d92SDimitry Andric           int64_t LHS = Current.LHS;
530c9157d92SDimitry Andric           int64_t RHS = LastPoppedValue;
531c9157d92SDimitry Andric           LastPoppedValue = std::max(LHS, RHS);
532c9157d92SDimitry Andric           CounterStack.pop();
533fe6060f1SDimitry Andric         }
534fe6060f1SDimitry Andric       }
535c9157d92SDimitry Andric       break;
536c9157d92SDimitry Andric     }
537c9157d92SDimitry Andric     }
538c9157d92SDimitry Andric   }
539c9157d92SDimitry Andric 
540c9157d92SDimitry Andric   return LastPoppedValue;
541fe6060f1SDimitry Andric }
542fe6060f1SDimitry Andric 
skipOtherFiles()5430b57cec5SDimitry Andric void FunctionRecordIterator::skipOtherFiles() {
5440b57cec5SDimitry Andric   while (Current != Records.end() && !Filename.empty() &&
5450b57cec5SDimitry Andric          Filename != Current->Filenames[0])
5460b57cec5SDimitry Andric     ++Current;
5470b57cec5SDimitry Andric   if (Current == Records.end())
5480b57cec5SDimitry Andric     *this = FunctionRecordIterator();
5490b57cec5SDimitry Andric }
5500b57cec5SDimitry Andric 
getImpreciseRecordIndicesForFilename(StringRef Filename) const5518bcb0991SDimitry Andric ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename(
5528bcb0991SDimitry Andric     StringRef Filename) const {
5538bcb0991SDimitry Andric   size_t FilenameHash = hash_value(Filename);
5548bcb0991SDimitry Andric   auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
5558bcb0991SDimitry Andric   if (RecordIt == FilenameHash2RecordIndices.end())
5568bcb0991SDimitry Andric     return {};
5578bcb0991SDimitry Andric   return RecordIt->second;
5588bcb0991SDimitry Andric }
5598bcb0991SDimitry Andric 
getMaxCounterID(const CounterMappingContext & Ctx,const CoverageMappingRecord & Record)560fe6060f1SDimitry Andric static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
561fe6060f1SDimitry Andric                                 const CoverageMappingRecord &Record) {
562fe6060f1SDimitry Andric   unsigned MaxCounterID = 0;
563fe6060f1SDimitry Andric   for (const auto &Region : Record.MappingRegions) {
564fe6060f1SDimitry Andric     MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count));
565fe6060f1SDimitry Andric   }
566fe6060f1SDimitry Andric   return MaxCounterID;
567fe6060f1SDimitry Andric }
568fe6060f1SDimitry Andric 
getMaxBitmapSize(const CounterMappingContext & Ctx,const CoverageMappingRecord & Record)569c9157d92SDimitry Andric static unsigned getMaxBitmapSize(const CounterMappingContext &Ctx,
570c9157d92SDimitry Andric                                  const CoverageMappingRecord &Record) {
571c9157d92SDimitry Andric   unsigned MaxBitmapID = 0;
572c9157d92SDimitry Andric   unsigned NumConditions = 0;
573a58f00eaSDimitry Andric   // Scan max(BitmapIdx).
574a58f00eaSDimitry Andric   // Note that `<=` is used insted of `<`, because `BitmapIdx == 0` is valid
575a58f00eaSDimitry Andric   // and `MaxBitmapID is `unsigned`. `BitmapIdx` is unique in the record.
576c9157d92SDimitry Andric   for (const auto &Region : reverse(Record.MappingRegions)) {
577a58f00eaSDimitry Andric     if (Region.Kind == CounterMappingRegion::MCDCDecisionRegion &&
578a58f00eaSDimitry Andric         MaxBitmapID <= Region.MCDCParams.BitmapIdx) {
579c9157d92SDimitry Andric       MaxBitmapID = Region.MCDCParams.BitmapIdx;
580c9157d92SDimitry Andric       NumConditions = Region.MCDCParams.NumConditions;
581c9157d92SDimitry Andric     }
582c9157d92SDimitry Andric   }
583c9157d92SDimitry Andric   unsigned SizeInBits = llvm::alignTo(uint64_t(1) << NumConditions, CHAR_BIT);
584c9157d92SDimitry Andric   return MaxBitmapID + (SizeInBits / CHAR_BIT);
585c9157d92SDimitry Andric }
586c9157d92SDimitry Andric 
587*b9d9368bSDimitry Andric namespace {
588*b9d9368bSDimitry Andric 
589*b9d9368bSDimitry Andric /// Collect Decisions, Branchs, and Expansions and associate them.
590*b9d9368bSDimitry Andric class MCDCDecisionRecorder {
591*b9d9368bSDimitry Andric private:
592*b9d9368bSDimitry Andric   /// This holds the DecisionRegion and MCDCBranches under it.
593*b9d9368bSDimitry Andric   /// Also traverses Expansion(s).
594*b9d9368bSDimitry Andric   /// The Decision has the number of MCDCBranches and will complete
595*b9d9368bSDimitry Andric   /// when it is filled with unique ConditionID of MCDCBranches.
596*b9d9368bSDimitry Andric   struct DecisionRecord {
597*b9d9368bSDimitry Andric     const CounterMappingRegion *DecisionRegion;
598*b9d9368bSDimitry Andric 
599*b9d9368bSDimitry Andric     /// They are reflected from DecisionRegion for convenience.
600*b9d9368bSDimitry Andric     LineColPair DecisionStartLoc;
601*b9d9368bSDimitry Andric     LineColPair DecisionEndLoc;
602*b9d9368bSDimitry Andric 
603*b9d9368bSDimitry Andric     /// This is passed to `MCDCRecordProcessor`, so this should be compatible
604*b9d9368bSDimitry Andric     /// to`ArrayRef<const CounterMappingRegion *>`.
605*b9d9368bSDimitry Andric     SmallVector<const CounterMappingRegion *> MCDCBranches;
606*b9d9368bSDimitry Andric 
607*b9d9368bSDimitry Andric     /// IDs that are stored in MCDCBranches
608*b9d9368bSDimitry Andric     /// Complete when all IDs (1 to NumConditions) are met.
609*b9d9368bSDimitry Andric     DenseSet<CounterMappingRegion::MCDCConditionID> ConditionIDs;
610*b9d9368bSDimitry Andric 
611*b9d9368bSDimitry Andric     /// Set of IDs of Expansion(s) that are relevant to DecisionRegion
612*b9d9368bSDimitry Andric     /// and its children (via expansions).
613*b9d9368bSDimitry Andric     /// FileID  pointed by ExpandedFileID is dedicated to the expansion, so
614*b9d9368bSDimitry Andric     /// the location in the expansion doesn't matter.
615*b9d9368bSDimitry Andric     DenseSet<unsigned> ExpandedFileIDs;
616*b9d9368bSDimitry Andric 
DecisionRecord__anonaf66dd530411::MCDCDecisionRecorder::DecisionRecord617*b9d9368bSDimitry Andric     DecisionRecord(const CounterMappingRegion &Decision)
618*b9d9368bSDimitry Andric         : DecisionRegion(&Decision), DecisionStartLoc(Decision.startLoc()),
619*b9d9368bSDimitry Andric           DecisionEndLoc(Decision.endLoc()) {
620*b9d9368bSDimitry Andric       assert(Decision.Kind == CounterMappingRegion::MCDCDecisionRegion);
621*b9d9368bSDimitry Andric     }
622*b9d9368bSDimitry Andric 
623*b9d9368bSDimitry Andric     /// Determine whether DecisionRecord dominates `R`.
dominates__anonaf66dd530411::MCDCDecisionRecorder::DecisionRecord624*b9d9368bSDimitry Andric     bool dominates(const CounterMappingRegion &R) const {
625*b9d9368bSDimitry Andric       // Determine whether `R` is included in `DecisionRegion`.
626*b9d9368bSDimitry Andric       if (R.FileID == DecisionRegion->FileID &&
627*b9d9368bSDimitry Andric           R.startLoc() >= DecisionStartLoc && R.endLoc() <= DecisionEndLoc)
628*b9d9368bSDimitry Andric         return true;
629*b9d9368bSDimitry Andric 
630*b9d9368bSDimitry Andric       // Determine whether `R` is pointed by any of Expansions.
631*b9d9368bSDimitry Andric       return ExpandedFileIDs.contains(R.FileID);
632*b9d9368bSDimitry Andric     }
633*b9d9368bSDimitry Andric 
634*b9d9368bSDimitry Andric     enum Result {
635*b9d9368bSDimitry Andric       NotProcessed = 0, /// Irrelevant to this Decision
636*b9d9368bSDimitry Andric       Processed,        /// Added to this Decision
637*b9d9368bSDimitry Andric       Completed,        /// Added and filled this Decision
638*b9d9368bSDimitry Andric     };
639*b9d9368bSDimitry Andric 
640*b9d9368bSDimitry Andric     /// Add Branch into the Decision
641*b9d9368bSDimitry Andric     /// \param Branch expects MCDCBranchRegion
642*b9d9368bSDimitry Andric     /// \returns NotProcessed/Processed/Completed
addBranch__anonaf66dd530411::MCDCDecisionRecorder::DecisionRecord643*b9d9368bSDimitry Andric     Result addBranch(const CounterMappingRegion &Branch) {
644*b9d9368bSDimitry Andric       assert(Branch.Kind == CounterMappingRegion::MCDCBranchRegion);
645*b9d9368bSDimitry Andric 
646*b9d9368bSDimitry Andric       auto ConditionID = Branch.MCDCParams.ID;
647*b9d9368bSDimitry Andric       assert(ConditionID > 0 && "ConditionID should begin with 1");
648*b9d9368bSDimitry Andric 
649*b9d9368bSDimitry Andric       if (ConditionIDs.contains(ConditionID) ||
650*b9d9368bSDimitry Andric           ConditionID > DecisionRegion->MCDCParams.NumConditions)
651*b9d9368bSDimitry Andric         return NotProcessed;
652*b9d9368bSDimitry Andric 
653*b9d9368bSDimitry Andric       if (!this->dominates(Branch))
654*b9d9368bSDimitry Andric         return NotProcessed;
655*b9d9368bSDimitry Andric 
656*b9d9368bSDimitry Andric       assert(MCDCBranches.size() < DecisionRegion->MCDCParams.NumConditions);
657*b9d9368bSDimitry Andric 
658*b9d9368bSDimitry Andric       // Put `ID=1` in front of `MCDCBranches` for convenience
659*b9d9368bSDimitry Andric       // even if `MCDCBranches` is not topological.
660*b9d9368bSDimitry Andric       if (ConditionID == 1)
661*b9d9368bSDimitry Andric         MCDCBranches.insert(MCDCBranches.begin(), &Branch);
662*b9d9368bSDimitry Andric       else
663*b9d9368bSDimitry Andric         MCDCBranches.push_back(&Branch);
664*b9d9368bSDimitry Andric 
665*b9d9368bSDimitry Andric       // Mark `ID` as `assigned`.
666*b9d9368bSDimitry Andric       ConditionIDs.insert(ConditionID);
667*b9d9368bSDimitry Andric 
668*b9d9368bSDimitry Andric       // `Completed` when `MCDCBranches` is full
669*b9d9368bSDimitry Andric       return (MCDCBranches.size() == DecisionRegion->MCDCParams.NumConditions
670*b9d9368bSDimitry Andric                   ? Completed
671*b9d9368bSDimitry Andric                   : Processed);
672*b9d9368bSDimitry Andric     }
673*b9d9368bSDimitry Andric 
674*b9d9368bSDimitry Andric     /// Record Expansion if it is relevant to this Decision.
675*b9d9368bSDimitry Andric     /// Each `Expansion` may nest.
676*b9d9368bSDimitry Andric     /// \returns true if recorded.
recordExpansion__anonaf66dd530411::MCDCDecisionRecorder::DecisionRecord677*b9d9368bSDimitry Andric     bool recordExpansion(const CounterMappingRegion &Expansion) {
678*b9d9368bSDimitry Andric       if (!this->dominates(Expansion))
679*b9d9368bSDimitry Andric         return false;
680*b9d9368bSDimitry Andric 
681*b9d9368bSDimitry Andric       ExpandedFileIDs.insert(Expansion.ExpandedFileID);
682*b9d9368bSDimitry Andric       return true;
683*b9d9368bSDimitry Andric     }
684*b9d9368bSDimitry Andric   };
685*b9d9368bSDimitry Andric 
686*b9d9368bSDimitry Andric private:
687*b9d9368bSDimitry Andric   /// Decisions in progress
688*b9d9368bSDimitry Andric   /// DecisionRecord is added for each MCDCDecisionRegion.
689*b9d9368bSDimitry Andric   /// DecisionRecord is removed when Decision is completed.
690*b9d9368bSDimitry Andric   SmallVector<DecisionRecord> Decisions;
691*b9d9368bSDimitry Andric 
692*b9d9368bSDimitry Andric public:
~MCDCDecisionRecorder()693*b9d9368bSDimitry Andric   ~MCDCDecisionRecorder() {
694*b9d9368bSDimitry Andric     assert(Decisions.empty() && "All Decisions have not been resolved");
695*b9d9368bSDimitry Andric   }
696*b9d9368bSDimitry Andric 
697*b9d9368bSDimitry Andric   /// Register Region and start recording.
registerDecision(const CounterMappingRegion & Decision)698*b9d9368bSDimitry Andric   void registerDecision(const CounterMappingRegion &Decision) {
699*b9d9368bSDimitry Andric     Decisions.emplace_back(Decision);
700*b9d9368bSDimitry Andric   }
701*b9d9368bSDimitry Andric 
recordExpansion(const CounterMappingRegion & Expansion)702*b9d9368bSDimitry Andric   void recordExpansion(const CounterMappingRegion &Expansion) {
703*b9d9368bSDimitry Andric     any_of(Decisions, [&Expansion](auto &Decision) {
704*b9d9368bSDimitry Andric       return Decision.recordExpansion(Expansion);
705*b9d9368bSDimitry Andric     });
706*b9d9368bSDimitry Andric   }
707*b9d9368bSDimitry Andric 
708*b9d9368bSDimitry Andric   using DecisionAndBranches =
709*b9d9368bSDimitry Andric       std::pair<const CounterMappingRegion *,             /// Decision
710*b9d9368bSDimitry Andric                 SmallVector<const CounterMappingRegion *> /// Branches
711*b9d9368bSDimitry Andric                 >;
712*b9d9368bSDimitry Andric 
713*b9d9368bSDimitry Andric   /// Add MCDCBranchRegion to DecisionRecord.
714*b9d9368bSDimitry Andric   /// \param Branch to be processed
715*b9d9368bSDimitry Andric   /// \returns DecisionsAndBranches if DecisionRecord completed.
716*b9d9368bSDimitry Andric   ///     Or returns nullopt.
717*b9d9368bSDimitry Andric   std::optional<DecisionAndBranches>
processBranch(const CounterMappingRegion & Branch)718*b9d9368bSDimitry Andric   processBranch(const CounterMappingRegion &Branch) {
719*b9d9368bSDimitry Andric     // Seek each Decision and apply Region to it.
720*b9d9368bSDimitry Andric     for (auto DecisionIter = Decisions.begin(), DecisionEnd = Decisions.end();
721*b9d9368bSDimitry Andric          DecisionIter != DecisionEnd; ++DecisionIter)
722*b9d9368bSDimitry Andric       switch (DecisionIter->addBranch(Branch)) {
723*b9d9368bSDimitry Andric       case DecisionRecord::NotProcessed:
724*b9d9368bSDimitry Andric         continue;
725*b9d9368bSDimitry Andric       case DecisionRecord::Processed:
726*b9d9368bSDimitry Andric         return std::nullopt;
727*b9d9368bSDimitry Andric       case DecisionRecord::Completed:
728*b9d9368bSDimitry Andric         DecisionAndBranches Result =
729*b9d9368bSDimitry Andric             std::make_pair(DecisionIter->DecisionRegion,
730*b9d9368bSDimitry Andric                            std::move(DecisionIter->MCDCBranches));
731*b9d9368bSDimitry Andric         Decisions.erase(DecisionIter); // No longer used.
732*b9d9368bSDimitry Andric         return Result;
733*b9d9368bSDimitry Andric       }
734*b9d9368bSDimitry Andric 
735*b9d9368bSDimitry Andric     llvm_unreachable("Branch not found in Decisions");
736*b9d9368bSDimitry Andric   }
737*b9d9368bSDimitry Andric };
738*b9d9368bSDimitry Andric 
739*b9d9368bSDimitry Andric } // namespace
740*b9d9368bSDimitry Andric 
loadFunctionRecord(const CoverageMappingRecord & Record,IndexedInstrProfReader & ProfileReader)7410b57cec5SDimitry Andric Error CoverageMapping::loadFunctionRecord(
7420b57cec5SDimitry Andric     const CoverageMappingRecord &Record,
7430b57cec5SDimitry Andric     IndexedInstrProfReader &ProfileReader) {
7440b57cec5SDimitry Andric   StringRef OrigFuncName = Record.FunctionName;
7450b57cec5SDimitry Andric   if (OrigFuncName.empty())
746c9157d92SDimitry Andric     return make_error<CoverageMapError>(coveragemap_error::malformed,
747c9157d92SDimitry Andric                                         "record function name is empty");
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   if (Record.Filenames.empty())
7500b57cec5SDimitry Andric     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
7510b57cec5SDimitry Andric   else
7520b57cec5SDimitry Andric     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric   CounterMappingContext Ctx(Record.Expressions);
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   std::vector<uint64_t> Counts;
7570b57cec5SDimitry Andric   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
7580b57cec5SDimitry Andric                                                 Record.FunctionHash, Counts)) {
759fe013be4SDimitry Andric     instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
7600b57cec5SDimitry Andric     if (IPE == instrprof_error::hash_mismatch) {
7615ffd83dbSDimitry Andric       FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
7625ffd83dbSDimitry Andric                                       Record.FunctionHash);
7630b57cec5SDimitry Andric       return Error::success();
764c9157d92SDimitry Andric     }
765c9157d92SDimitry Andric     if (IPE != instrprof_error::unknown_function)
7660b57cec5SDimitry Andric       return make_error<InstrProfError>(IPE);
767fe6060f1SDimitry Andric     Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric   Ctx.setCounts(Counts);
7700b57cec5SDimitry Andric 
771c9157d92SDimitry Andric   std::vector<uint8_t> BitmapBytes;
772c9157d92SDimitry Andric   if (Error E = ProfileReader.getFunctionBitmapBytes(
773c9157d92SDimitry Andric           Record.FunctionName, Record.FunctionHash, BitmapBytes)) {
774c9157d92SDimitry Andric     instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
775c9157d92SDimitry Andric     if (IPE == instrprof_error::hash_mismatch) {
776c9157d92SDimitry Andric       FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
777c9157d92SDimitry Andric                                       Record.FunctionHash);
778c9157d92SDimitry Andric       return Error::success();
779c9157d92SDimitry Andric     }
780c9157d92SDimitry Andric     if (IPE != instrprof_error::unknown_function)
781c9157d92SDimitry Andric       return make_error<InstrProfError>(IPE);
782c9157d92SDimitry Andric     BitmapBytes.assign(getMaxBitmapSize(Ctx, Record) + 1, 0);
783c9157d92SDimitry Andric   }
784c9157d92SDimitry Andric   Ctx.setBitmapBytes(BitmapBytes);
785c9157d92SDimitry Andric 
7860b57cec5SDimitry Andric   assert(!Record.MappingRegions.empty() && "Function has no regions");
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   // This coverage record is a zero region for a function that's unused in
7890b57cec5SDimitry Andric   // some TU, but used in a different TU. Ignore it. The coverage maps from the
7900b57cec5SDimitry Andric   // the other TU will either be loaded (providing full region counts) or they
7910b57cec5SDimitry Andric   // won't (in which case we don't unintuitively report functions as uncovered
7920b57cec5SDimitry Andric   // when they have non-zero counts in the profile).
7930b57cec5SDimitry Andric   if (Record.MappingRegions.size() == 1 &&
7940b57cec5SDimitry Andric       Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
7950b57cec5SDimitry Andric     return Error::success();
7960b57cec5SDimitry Andric 
797*b9d9368bSDimitry Andric   MCDCDecisionRecorder MCDCDecisions;
7980b57cec5SDimitry Andric   FunctionRecord Function(OrigFuncName, Record.Filenames);
7990b57cec5SDimitry Andric   for (const auto &Region : Record.MappingRegions) {
800*b9d9368bSDimitry Andric     // MCDCDecisionRegion should be handled first since it overlaps with
801*b9d9368bSDimitry Andric     // others inside.
802c9157d92SDimitry Andric     if (Region.Kind == CounterMappingRegion::MCDCDecisionRegion) {
803*b9d9368bSDimitry Andric       MCDCDecisions.registerDecision(Region);
804c9157d92SDimitry Andric       continue;
805c9157d92SDimitry Andric     }
8060b57cec5SDimitry Andric     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
8070b57cec5SDimitry Andric     if (auto E = ExecutionCount.takeError()) {
8080b57cec5SDimitry Andric       consumeError(std::move(E));
8090b57cec5SDimitry Andric       return Error::success();
8100b57cec5SDimitry Andric     }
811e8d8bef9SDimitry Andric     Expected<int64_t> AltExecutionCount = Ctx.evaluate(Region.FalseCount);
812e8d8bef9SDimitry Andric     if (auto E = AltExecutionCount.takeError()) {
813e8d8bef9SDimitry Andric       consumeError(std::move(E));
814e8d8bef9SDimitry Andric       return Error::success();
815e8d8bef9SDimitry Andric     }
816e8d8bef9SDimitry Andric     Function.pushRegion(Region, *ExecutionCount, *AltExecutionCount);
817c9157d92SDimitry Andric 
818*b9d9368bSDimitry Andric     // Record ExpansionRegion.
819*b9d9368bSDimitry Andric     if (Region.Kind == CounterMappingRegion::ExpansionRegion) {
820*b9d9368bSDimitry Andric       MCDCDecisions.recordExpansion(Region);
821*b9d9368bSDimitry Andric       continue;
822*b9d9368bSDimitry Andric     }
823c9157d92SDimitry Andric 
824*b9d9368bSDimitry Andric     // Do nothing unless MCDCBranchRegion.
825*b9d9368bSDimitry Andric     if (Region.Kind != CounterMappingRegion::MCDCBranchRegion)
826*b9d9368bSDimitry Andric       continue;
827*b9d9368bSDimitry Andric 
828*b9d9368bSDimitry Andric     auto Result = MCDCDecisions.processBranch(Region);
829*b9d9368bSDimitry Andric     if (!Result) // Any Decision doesn't complete.
830*b9d9368bSDimitry Andric       continue;
831*b9d9368bSDimitry Andric 
832*b9d9368bSDimitry Andric     auto MCDCDecision = Result->first;
833*b9d9368bSDimitry Andric     auto &MCDCBranches = Result->second;
834*b9d9368bSDimitry Andric 
835c9157d92SDimitry Andric     // Evaluating the test vector bitmap for the decision region entails
836c9157d92SDimitry Andric     // calculating precisely what bits are pertinent to this region alone.
837c9157d92SDimitry Andric     // This is calculated based on the recorded offset into the global
838c9157d92SDimitry Andric     // profile bitmap; the length is calculated based on the recorded
839c9157d92SDimitry Andric     // number of conditions.
840c9157d92SDimitry Andric     Expected<BitVector> ExecutedTestVectorBitmap =
841c9157d92SDimitry Andric         Ctx.evaluateBitmap(MCDCDecision);
842c9157d92SDimitry Andric     if (auto E = ExecutedTestVectorBitmap.takeError()) {
843c9157d92SDimitry Andric       consumeError(std::move(E));
844c9157d92SDimitry Andric       return Error::success();
845c9157d92SDimitry Andric     }
846c9157d92SDimitry Andric 
847c9157d92SDimitry Andric     // Since the bitmap identifies the executed test vectors for an MC/DC
848c9157d92SDimitry Andric     // DecisionRegion, all of the information is now available to process.
849c9157d92SDimitry Andric     // This is where the bulk of the MC/DC progressing takes place.
850c9157d92SDimitry Andric     Expected<MCDCRecord> Record = Ctx.evaluateMCDCRegion(
851c9157d92SDimitry Andric         *MCDCDecision, *ExecutedTestVectorBitmap, MCDCBranches);
852c9157d92SDimitry Andric     if (auto E = Record.takeError()) {
853c9157d92SDimitry Andric       consumeError(std::move(E));
854c9157d92SDimitry Andric       return Error::success();
855c9157d92SDimitry Andric     }
856c9157d92SDimitry Andric 
857c9157d92SDimitry Andric     // Save the MC/DC Record so that it can be visualized later.
858c9157d92SDimitry Andric     Function.pushMCDCRecord(*Record);
8590b57cec5SDimitry Andric   }
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   // Don't create records for (filenames, function) pairs we've already seen.
8620b57cec5SDimitry Andric   auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
8630b57cec5SDimitry Andric                                           Record.Filenames.end());
8640b57cec5SDimitry Andric   if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
8650b57cec5SDimitry Andric     return Error::success();
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric   Functions.push_back(std::move(Function));
8688bcb0991SDimitry Andric 
8698bcb0991SDimitry Andric   // Performance optimization: keep track of the indices of the function records
8708bcb0991SDimitry Andric   // which correspond to each filename. This can be used to substantially speed
8718bcb0991SDimitry Andric   // up queries for coverage info in a file.
8728bcb0991SDimitry Andric   unsigned RecordIndex = Functions.size() - 1;
8738bcb0991SDimitry Andric   for (StringRef Filename : Record.Filenames) {
8748bcb0991SDimitry Andric     auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)];
8758bcb0991SDimitry Andric     // Note that there may be duplicates in the filename set for a function
8768bcb0991SDimitry Andric     // record, because of e.g. macro expansions in the function in which both
8778bcb0991SDimitry Andric     // the macro and the function are defined in the same file.
8788bcb0991SDimitry Andric     if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
8798bcb0991SDimitry Andric       RecordIndices.push_back(RecordIndex);
8808bcb0991SDimitry Andric   }
8818bcb0991SDimitry Andric 
8820b57cec5SDimitry Andric   return Error::success();
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
885fe6060f1SDimitry Andric // This function is for memory optimization by shortening the lifetimes
886fe6060f1SDimitry Andric // of CoverageMappingReader instances.
loadFromReaders(ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,IndexedInstrProfReader & ProfileReader,CoverageMapping & Coverage)887fe6060f1SDimitry Andric Error CoverageMapping::loadFromReaders(
888fe6060f1SDimitry Andric     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
889fe6060f1SDimitry Andric     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage) {
890fe6060f1SDimitry Andric   for (const auto &CoverageReader : CoverageReaders) {
891fe6060f1SDimitry Andric     for (auto RecordOrErr : *CoverageReader) {
892fe6060f1SDimitry Andric       if (Error E = RecordOrErr.takeError())
893fe6060f1SDimitry Andric         return E;
894fe6060f1SDimitry Andric       const auto &Record = *RecordOrErr;
895fe6060f1SDimitry Andric       if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader))
896fe6060f1SDimitry Andric         return E;
897fe6060f1SDimitry Andric     }
898fe6060f1SDimitry Andric   }
899fe6060f1SDimitry Andric   return Error::success();
900fe6060f1SDimitry Andric }
901fe6060f1SDimitry Andric 
load(ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,IndexedInstrProfReader & ProfileReader)9020b57cec5SDimitry Andric Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
9030b57cec5SDimitry Andric     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
9040b57cec5SDimitry Andric     IndexedInstrProfReader &ProfileReader) {
9050b57cec5SDimitry Andric   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
906fe6060f1SDimitry Andric   if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
9070b57cec5SDimitry Andric     return std::move(E);
9080b57cec5SDimitry Andric   return std::move(Coverage);
9090b57cec5SDimitry Andric }
9100b57cec5SDimitry Andric 
9118bcb0991SDimitry Andric // If E is a no_data_found error, returns success. Otherwise returns E.
handleMaybeNoDataFoundError(Error E)9128bcb0991SDimitry Andric static Error handleMaybeNoDataFoundError(Error E) {
9138bcb0991SDimitry Andric   return handleErrors(
9148bcb0991SDimitry Andric       std::move(E), [](const CoverageMapError &CME) {
9158bcb0991SDimitry Andric         if (CME.get() == coveragemap_error::no_data_found)
9168bcb0991SDimitry Andric           return static_cast<Error>(Error::success());
917c9157d92SDimitry Andric         return make_error<CoverageMapError>(CME.get(), CME.getMessage());
9188bcb0991SDimitry Andric       });
9198bcb0991SDimitry Andric }
9208bcb0991SDimitry Andric 
loadFromFile(StringRef Filename,StringRef Arch,StringRef CompilationDir,IndexedInstrProfReader & ProfileReader,CoverageMapping & Coverage,bool & DataFound,SmallVectorImpl<object::BuildID> * FoundBinaryIDs)9211ac55f4cSDimitry Andric Error CoverageMapping::loadFromFile(
9221ac55f4cSDimitry Andric     StringRef Filename, StringRef Arch, StringRef CompilationDir,
9231ac55f4cSDimitry Andric     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage,
9241ac55f4cSDimitry Andric     bool &DataFound, SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
9251ac55f4cSDimitry Andric   auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
9261ac55f4cSDimitry Andric       Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false);
9271ac55f4cSDimitry Andric   if (std::error_code EC = CovMappingBufOrErr.getError())
9281ac55f4cSDimitry Andric     return createFileError(Filename, errorCodeToError(EC));
9291ac55f4cSDimitry Andric   MemoryBufferRef CovMappingBufRef =
9301ac55f4cSDimitry Andric       CovMappingBufOrErr.get()->getMemBufferRef();
9311ac55f4cSDimitry Andric   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
9321ac55f4cSDimitry Andric 
9331ac55f4cSDimitry Andric   SmallVector<object::BuildIDRef> BinaryIDs;
9341ac55f4cSDimitry Andric   auto CoverageReadersOrErr = BinaryCoverageReader::create(
9351ac55f4cSDimitry Andric       CovMappingBufRef, Arch, Buffers, CompilationDir,
9361ac55f4cSDimitry Andric       FoundBinaryIDs ? &BinaryIDs : nullptr);
9371ac55f4cSDimitry Andric   if (Error E = CoverageReadersOrErr.takeError()) {
9381ac55f4cSDimitry Andric     E = handleMaybeNoDataFoundError(std::move(E));
9391ac55f4cSDimitry Andric     if (E)
9401ac55f4cSDimitry Andric       return createFileError(Filename, std::move(E));
9411ac55f4cSDimitry Andric     return E;
9421ac55f4cSDimitry Andric   }
9431ac55f4cSDimitry Andric 
9441ac55f4cSDimitry Andric   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
9451ac55f4cSDimitry Andric   for (auto &Reader : CoverageReadersOrErr.get())
9461ac55f4cSDimitry Andric     Readers.push_back(std::move(Reader));
9471ac55f4cSDimitry Andric   if (FoundBinaryIDs && !Readers.empty()) {
9481ac55f4cSDimitry Andric     llvm::append_range(*FoundBinaryIDs,
9491ac55f4cSDimitry Andric                        llvm::map_range(BinaryIDs, [](object::BuildIDRef BID) {
9501ac55f4cSDimitry Andric                          return object::BuildID(BID);
9511ac55f4cSDimitry Andric                        }));
9521ac55f4cSDimitry Andric   }
9531ac55f4cSDimitry Andric   DataFound |= !Readers.empty();
9541ac55f4cSDimitry Andric   if (Error E = loadFromReaders(Readers, ProfileReader, Coverage))
9551ac55f4cSDimitry Andric     return createFileError(Filename, std::move(E));
9561ac55f4cSDimitry Andric   return Error::success();
9571ac55f4cSDimitry Andric }
9581ac55f4cSDimitry Andric 
load(ArrayRef<StringRef> ObjectFilenames,StringRef ProfileFilename,vfs::FileSystem & FS,ArrayRef<StringRef> Arches,StringRef CompilationDir,const object::BuildIDFetcher * BIDFetcher,bool CheckBinaryIDs)959fe013be4SDimitry Andric Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
960fe013be4SDimitry Andric     ArrayRef<StringRef> ObjectFilenames, StringRef ProfileFilename,
961fe013be4SDimitry Andric     vfs::FileSystem &FS, ArrayRef<StringRef> Arches, StringRef CompilationDir,
962fe013be4SDimitry Andric     const object::BuildIDFetcher *BIDFetcher, bool CheckBinaryIDs) {
963fe013be4SDimitry Andric   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename, FS);
9640b57cec5SDimitry Andric   if (Error E = ProfileReaderOrErr.takeError())
965fcaf7f86SDimitry Andric     return createFileError(ProfileFilename, std::move(E));
9660b57cec5SDimitry Andric   auto ProfileReader = std::move(ProfileReaderOrErr.get());
967fe6060f1SDimitry Andric   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
968fe6060f1SDimitry Andric   bool DataFound = false;
9690b57cec5SDimitry Andric 
9701ac55f4cSDimitry Andric   auto GetArch = [&](size_t Idx) {
9711ac55f4cSDimitry Andric     if (Arches.empty())
9721ac55f4cSDimitry Andric       return StringRef();
9731ac55f4cSDimitry Andric     if (Arches.size() == 1)
9741ac55f4cSDimitry Andric       return Arches.front();
9751ac55f4cSDimitry Andric     return Arches[Idx];
9761ac55f4cSDimitry Andric   };
9771ac55f4cSDimitry Andric 
9781ac55f4cSDimitry Andric   SmallVector<object::BuildID> FoundBinaryIDs;
9790b57cec5SDimitry Andric   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
9801ac55f4cSDimitry Andric     if (Error E =
9811ac55f4cSDimitry Andric             loadFromFile(File.value(), GetArch(File.index()), CompilationDir,
9821ac55f4cSDimitry Andric                          *ProfileReader, *Coverage, DataFound, &FoundBinaryIDs))
9831ac55f4cSDimitry Andric       return std::move(E);
9848bcb0991SDimitry Andric   }
985fe6060f1SDimitry Andric 
9861ac55f4cSDimitry Andric   if (BIDFetcher) {
9871ac55f4cSDimitry Andric     std::vector<object::BuildID> ProfileBinaryIDs;
9881ac55f4cSDimitry Andric     if (Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs))
9891ac55f4cSDimitry Andric       return createFileError(ProfileFilename, std::move(E));
9901ac55f4cSDimitry Andric 
9911ac55f4cSDimitry Andric     SmallVector<object::BuildIDRef> BinaryIDsToFetch;
9921ac55f4cSDimitry Andric     if (!ProfileBinaryIDs.empty()) {
9931ac55f4cSDimitry Andric       const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) {
9941ac55f4cSDimitry Andric         return std::lexicographical_compare(A.begin(), A.end(), B.begin(),
9951ac55f4cSDimitry Andric                                             B.end());
9961ac55f4cSDimitry Andric       };
9971ac55f4cSDimitry Andric       llvm::sort(FoundBinaryIDs, Compare);
9981ac55f4cSDimitry Andric       std::set_difference(
9991ac55f4cSDimitry Andric           ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(),
10001ac55f4cSDimitry Andric           FoundBinaryIDs.begin(), FoundBinaryIDs.end(),
10011ac55f4cSDimitry Andric           std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.end()), Compare);
10020b57cec5SDimitry Andric     }
10031ac55f4cSDimitry Andric 
10041ac55f4cSDimitry Andric     for (object::BuildIDRef BinaryID : BinaryIDsToFetch) {
10051ac55f4cSDimitry Andric       std::optional<std::string> PathOpt = BIDFetcher->fetch(BinaryID);
1006fe013be4SDimitry Andric       if (PathOpt) {
10071ac55f4cSDimitry Andric         std::string Path = std::move(*PathOpt);
10081ac55f4cSDimitry Andric         StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef();
10091ac55f4cSDimitry Andric         if (Error E = loadFromFile(Path, Arch, CompilationDir, *ProfileReader,
10101ac55f4cSDimitry Andric                                   *Coverage, DataFound))
10111ac55f4cSDimitry Andric           return std::move(E);
1012fe013be4SDimitry Andric       } else if (CheckBinaryIDs) {
1013fe013be4SDimitry Andric         return createFileError(
1014fe013be4SDimitry Andric             ProfileFilename,
1015fe013be4SDimitry Andric             createStringError(errc::no_such_file_or_directory,
1016fe013be4SDimitry Andric                               "Missing binary ID: " +
1017fe013be4SDimitry Andric                                   llvm::toHex(BinaryID, /*LowerCase=*/true)));
1018fe013be4SDimitry Andric       }
10191ac55f4cSDimitry Andric     }
10201ac55f4cSDimitry Andric   }
10211ac55f4cSDimitry Andric 
10221ac55f4cSDimitry Andric   if (!DataFound)
1023fcaf7f86SDimitry Andric     return createFileError(
1024fcaf7f86SDimitry Andric         join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
1025fcaf7f86SDimitry Andric         make_error<CoverageMapError>(coveragemap_error::no_data_found));
1026fe6060f1SDimitry Andric   return std::move(Coverage);
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric namespace {
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric /// Distributes functions into instantiation sets.
10320b57cec5SDimitry Andric ///
10330b57cec5SDimitry Andric /// An instantiation set is a collection of functions that have the same source
10340b57cec5SDimitry Andric /// code, ie, template functions specializations.
10350b57cec5SDimitry Andric class FunctionInstantiationSetCollector {
10360b57cec5SDimitry Andric   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
10370b57cec5SDimitry Andric   MapT InstantiatedFunctions;
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric public:
insert(const FunctionRecord & Function,unsigned FileID)10400b57cec5SDimitry Andric   void insert(const FunctionRecord &Function, unsigned FileID) {
10410b57cec5SDimitry Andric     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
10420b57cec5SDimitry Andric     while (I != E && I->FileID != FileID)
10430b57cec5SDimitry Andric       ++I;
10440b57cec5SDimitry Andric     assert(I != E && "function does not cover the given file");
10450b57cec5SDimitry Andric     auto &Functions = InstantiatedFunctions[I->startLoc()];
10460b57cec5SDimitry Andric     Functions.push_back(&Function);
10470b57cec5SDimitry Andric   }
10480b57cec5SDimitry Andric 
begin()10490b57cec5SDimitry Andric   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
end()10500b57cec5SDimitry Andric   MapT::iterator end() { return InstantiatedFunctions.end(); }
10510b57cec5SDimitry Andric };
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric class SegmentBuilder {
10540b57cec5SDimitry Andric   std::vector<CoverageSegment> &Segments;
10550b57cec5SDimitry Andric   SmallVector<const CountedRegion *, 8> ActiveRegions;
10560b57cec5SDimitry Andric 
SegmentBuilder(std::vector<CoverageSegment> & Segments)10570b57cec5SDimitry Andric   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   /// Emit a segment with the count from \p Region starting at \p StartLoc.
10600b57cec5SDimitry Andric   //
10610b57cec5SDimitry Andric   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
10620b57cec5SDimitry Andric   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
startSegment(const CountedRegion & Region,LineColPair StartLoc,bool IsRegionEntry,bool EmitSkippedRegion=false)10630b57cec5SDimitry Andric   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
10640b57cec5SDimitry Andric                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
10650b57cec5SDimitry Andric     bool HasCount = !EmitSkippedRegion &&
10660b57cec5SDimitry Andric                     (Region.Kind != CounterMappingRegion::SkippedRegion);
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric     // If the new segment wouldn't affect coverage rendering, skip it.
10690b57cec5SDimitry Andric     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
10700b57cec5SDimitry Andric       const auto &Last = Segments.back();
10710b57cec5SDimitry Andric       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
10720b57cec5SDimitry Andric           !Last.IsRegionEntry)
10730b57cec5SDimitry Andric         return;
10740b57cec5SDimitry Andric     }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric     if (HasCount)
10770b57cec5SDimitry Andric       Segments.emplace_back(StartLoc.first, StartLoc.second,
10780b57cec5SDimitry Andric                             Region.ExecutionCount, IsRegionEntry,
10790b57cec5SDimitry Andric                             Region.Kind == CounterMappingRegion::GapRegion);
10800b57cec5SDimitry Andric     else
10810b57cec5SDimitry Andric       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric     LLVM_DEBUG({
10840b57cec5SDimitry Andric       const auto &Last = Segments.back();
10850b57cec5SDimitry Andric       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
10860b57cec5SDimitry Andric              << " (count = " << Last.Count << ")"
10870b57cec5SDimitry Andric              << (Last.IsRegionEntry ? ", RegionEntry" : "")
10880b57cec5SDimitry Andric              << (!Last.HasCount ? ", Skipped" : "")
10890b57cec5SDimitry Andric              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
10900b57cec5SDimitry Andric     });
10910b57cec5SDimitry Andric   }
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric   /// Emit segments for active regions which end before \p Loc.
10940b57cec5SDimitry Andric   ///
1095bdd1243dSDimitry Andric   /// \p Loc: The start location of the next region. If std::nullopt, all active
10960b57cec5SDimitry Andric   /// regions are completed.
10970b57cec5SDimitry Andric   /// \p FirstCompletedRegion: Index of the first completed region.
completeRegionsUntil(std::optional<LineColPair> Loc,unsigned FirstCompletedRegion)1098bdd1243dSDimitry Andric   void completeRegionsUntil(std::optional<LineColPair> Loc,
10990b57cec5SDimitry Andric                             unsigned FirstCompletedRegion) {
11000b57cec5SDimitry Andric     // Sort the completed regions by end location. This makes it simple to
11010b57cec5SDimitry Andric     // emit closing segments in sorted order.
11020b57cec5SDimitry Andric     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
11030b57cec5SDimitry Andric     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
11040b57cec5SDimitry Andric                       [](const CountedRegion *L, const CountedRegion *R) {
11050b57cec5SDimitry Andric                         return L->endLoc() < R->endLoc();
11060b57cec5SDimitry Andric                       });
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric     // Emit segments for all completed regions.
11090b57cec5SDimitry Andric     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
11100b57cec5SDimitry Andric          ++I) {
11110b57cec5SDimitry Andric       const auto *CompletedRegion = ActiveRegions[I];
11120b57cec5SDimitry Andric       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
11130b57cec5SDimitry Andric              "Completed region ends after start of new region");
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
11160b57cec5SDimitry Andric       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric       // Don't emit any more segments if they start where the new region begins.
11190b57cec5SDimitry Andric       if (Loc && CompletedSegmentLoc == *Loc)
11200b57cec5SDimitry Andric         break;
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric       // Don't emit a segment if the next completed region ends at the same
11230b57cec5SDimitry Andric       // location as this one.
11240b57cec5SDimitry Andric       if (CompletedSegmentLoc == CompletedRegion->endLoc())
11250b57cec5SDimitry Andric         continue;
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric       // Use the count from the last completed region which ends at this loc.
11280b57cec5SDimitry Andric       for (unsigned J = I + 1; J < E; ++J)
11290b57cec5SDimitry Andric         if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
11300b57cec5SDimitry Andric           CompletedRegion = ActiveRegions[J];
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
11330b57cec5SDimitry Andric     }
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric     auto Last = ActiveRegions.back();
11360b57cec5SDimitry Andric     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
11370b57cec5SDimitry Andric       // If there's a gap after the end of the last completed region and the
11380b57cec5SDimitry Andric       // start of the new region, use the last active region to fill the gap.
11390b57cec5SDimitry Andric       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
11400b57cec5SDimitry Andric                    false);
11410b57cec5SDimitry Andric     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
11420b57cec5SDimitry Andric       // Emit a skipped segment if there are no more active regions. This
11430b57cec5SDimitry Andric       // ensures that gaps between functions are marked correctly.
11440b57cec5SDimitry Andric       startSegment(*Last, Last->endLoc(), false, true);
11450b57cec5SDimitry Andric     }
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric     // Pop the completed regions.
11480b57cec5SDimitry Andric     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
11490b57cec5SDimitry Andric   }
11500b57cec5SDimitry Andric 
buildSegmentsImpl(ArrayRef<CountedRegion> Regions)11510b57cec5SDimitry Andric   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
11520b57cec5SDimitry Andric     for (const auto &CR : enumerate(Regions)) {
11530b57cec5SDimitry Andric       auto CurStartLoc = CR.value().startLoc();
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric       // Active regions which end before the current region need to be popped.
11560b57cec5SDimitry Andric       auto CompletedRegions =
11570b57cec5SDimitry Andric           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
11580b57cec5SDimitry Andric                                 [&](const CountedRegion *Region) {
11590b57cec5SDimitry Andric                                   return !(Region->endLoc() <= CurStartLoc);
11600b57cec5SDimitry Andric                                 });
11610b57cec5SDimitry Andric       if (CompletedRegions != ActiveRegions.end()) {
11620b57cec5SDimitry Andric         unsigned FirstCompletedRegion =
11630b57cec5SDimitry Andric             std::distance(ActiveRegions.begin(), CompletedRegions);
11640b57cec5SDimitry Andric         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
11650b57cec5SDimitry Andric       }
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric       // Try to emit a segment for the current region.
11700b57cec5SDimitry Andric       if (CurStartLoc == CR.value().endLoc()) {
11710b57cec5SDimitry Andric         // Avoid making zero-length regions active. If it's the last region,
11720b57cec5SDimitry Andric         // emit a skipped segment. Otherwise use its predecessor's count.
1173e8d8bef9SDimitry Andric         const bool Skipped =
1174e8d8bef9SDimitry Andric             (CR.index() + 1) == Regions.size() ||
1175e8d8bef9SDimitry Andric             CR.value().Kind == CounterMappingRegion::SkippedRegion;
11760b57cec5SDimitry Andric         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
11770b57cec5SDimitry Andric                      CurStartLoc, !GapRegion, Skipped);
1178e8d8bef9SDimitry Andric         // If it is skipped segment, create a segment with last pushed
1179e8d8bef9SDimitry Andric         // regions's count at CurStartLoc.
1180e8d8bef9SDimitry Andric         if (Skipped && !ActiveRegions.empty())
1181e8d8bef9SDimitry Andric           startSegment(*ActiveRegions.back(), CurStartLoc, false);
11820b57cec5SDimitry Andric         continue;
11830b57cec5SDimitry Andric       }
11840b57cec5SDimitry Andric       if (CR.index() + 1 == Regions.size() ||
11850b57cec5SDimitry Andric           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
11860b57cec5SDimitry Andric         // Emit a segment if the next region doesn't start at the same location
11870b57cec5SDimitry Andric         // as this one.
11880b57cec5SDimitry Andric         startSegment(CR.value(), CurStartLoc, !GapRegion);
11890b57cec5SDimitry Andric       }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric       // This region is active (i.e not completed).
11920b57cec5SDimitry Andric       ActiveRegions.push_back(&CR.value());
11930b57cec5SDimitry Andric     }
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric     // Complete any remaining active regions.
11960b57cec5SDimitry Andric     if (!ActiveRegions.empty())
1197bdd1243dSDimitry Andric       completeRegionsUntil(std::nullopt, 0);
11980b57cec5SDimitry Andric   }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric   /// Sort a nested sequence of regions from a single file.
sortNestedRegions(MutableArrayRef<CountedRegion> Regions)12010b57cec5SDimitry Andric   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
12020b57cec5SDimitry Andric     llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
12030b57cec5SDimitry Andric       if (LHS.startLoc() != RHS.startLoc())
12040b57cec5SDimitry Andric         return LHS.startLoc() < RHS.startLoc();
12050b57cec5SDimitry Andric       if (LHS.endLoc() != RHS.endLoc())
12060b57cec5SDimitry Andric         // When LHS completely contains RHS, we sort LHS first.
12070b57cec5SDimitry Andric         return RHS.endLoc() < LHS.endLoc();
12080b57cec5SDimitry Andric       // If LHS and RHS cover the same area, we need to sort them according
12090b57cec5SDimitry Andric       // to their kinds so that the most suitable region will become "active"
12100b57cec5SDimitry Andric       // in combineRegions(). Because we accumulate counter values only from
12110b57cec5SDimitry Andric       // regions of the same kind as the first region of the area, prefer
12120b57cec5SDimitry Andric       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
12130b57cec5SDimitry Andric       static_assert(CounterMappingRegion::CodeRegion <
12140b57cec5SDimitry Andric                             CounterMappingRegion::ExpansionRegion &&
12150b57cec5SDimitry Andric                         CounterMappingRegion::ExpansionRegion <
12160b57cec5SDimitry Andric                             CounterMappingRegion::SkippedRegion,
12170b57cec5SDimitry Andric                     "Unexpected order of region kind values");
12180b57cec5SDimitry Andric       return LHS.Kind < RHS.Kind;
12190b57cec5SDimitry Andric     });
12200b57cec5SDimitry Andric   }
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   /// Combine counts of regions which cover the same area.
12230b57cec5SDimitry Andric   static ArrayRef<CountedRegion>
combineRegions(MutableArrayRef<CountedRegion> Regions)12240b57cec5SDimitry Andric   combineRegions(MutableArrayRef<CountedRegion> Regions) {
12250b57cec5SDimitry Andric     if (Regions.empty())
12260b57cec5SDimitry Andric       return Regions;
12270b57cec5SDimitry Andric     auto Active = Regions.begin();
12280b57cec5SDimitry Andric     auto End = Regions.end();
12290b57cec5SDimitry Andric     for (auto I = Regions.begin() + 1; I != End; ++I) {
12300b57cec5SDimitry Andric       if (Active->startLoc() != I->startLoc() ||
12310b57cec5SDimitry Andric           Active->endLoc() != I->endLoc()) {
12320b57cec5SDimitry Andric         // Shift to the next region.
12330b57cec5SDimitry Andric         ++Active;
12340b57cec5SDimitry Andric         if (Active != I)
12350b57cec5SDimitry Andric           *Active = *I;
12360b57cec5SDimitry Andric         continue;
12370b57cec5SDimitry Andric       }
12380b57cec5SDimitry Andric       // Merge duplicate region.
12390b57cec5SDimitry Andric       // If CodeRegions and ExpansionRegions cover the same area, it's probably
12400b57cec5SDimitry Andric       // a macro which is fully expanded to another macro. In that case, we need
12410b57cec5SDimitry Andric       // to accumulate counts only from CodeRegions, or else the area will be
12420b57cec5SDimitry Andric       // counted twice.
12430b57cec5SDimitry Andric       // On the other hand, a macro may have a nested macro in its body. If the
12440b57cec5SDimitry Andric       // outer macro is used several times, the ExpansionRegion for the nested
12450b57cec5SDimitry Andric       // macro will also be added several times. These ExpansionRegions cover
12460b57cec5SDimitry Andric       // the same source locations and have to be combined to reach the correct
12470b57cec5SDimitry Andric       // value for that area.
12480b57cec5SDimitry Andric       // We add counts of the regions of the same kind as the active region
12490b57cec5SDimitry Andric       // to handle the both situations.
12500b57cec5SDimitry Andric       if (I->Kind == Active->Kind)
12510b57cec5SDimitry Andric         Active->ExecutionCount += I->ExecutionCount;
12520b57cec5SDimitry Andric     }
12530b57cec5SDimitry Andric     return Regions.drop_back(std::distance(++Active, End));
12540b57cec5SDimitry Andric   }
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric public:
12570b57cec5SDimitry Andric   /// Build a sorted list of CoverageSegments from a list of Regions.
12580b57cec5SDimitry Andric   static std::vector<CoverageSegment>
buildSegments(MutableArrayRef<CountedRegion> Regions)12590b57cec5SDimitry Andric   buildSegments(MutableArrayRef<CountedRegion> Regions) {
12600b57cec5SDimitry Andric     std::vector<CoverageSegment> Segments;
12610b57cec5SDimitry Andric     SegmentBuilder Builder(Segments);
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric     sortNestedRegions(Regions);
12640b57cec5SDimitry Andric     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
12650b57cec5SDimitry Andric 
12660b57cec5SDimitry Andric     LLVM_DEBUG({
12670b57cec5SDimitry Andric       dbgs() << "Combined regions:\n";
12680b57cec5SDimitry Andric       for (const auto &CR : CombinedRegions)
12690b57cec5SDimitry Andric         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
12700b57cec5SDimitry Andric                << CR.LineEnd << ":" << CR.ColumnEnd
12710b57cec5SDimitry Andric                << " (count=" << CR.ExecutionCount << ")\n";
12720b57cec5SDimitry Andric     });
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric     Builder.buildSegmentsImpl(CombinedRegions);
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric #ifndef NDEBUG
12770b57cec5SDimitry Andric     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
12780b57cec5SDimitry Andric       const auto &L = Segments[I - 1];
12790b57cec5SDimitry Andric       const auto &R = Segments[I];
12800b57cec5SDimitry Andric       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
1281e8d8bef9SDimitry Andric         if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
1282e8d8bef9SDimitry Andric           continue;
12830b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
12840b57cec5SDimitry Andric                           << " followed by " << R.Line << ":" << R.Col << "\n");
12850b57cec5SDimitry Andric         assert(false && "Coverage segments not unique or sorted");
12860b57cec5SDimitry Andric       }
12870b57cec5SDimitry Andric     }
12880b57cec5SDimitry Andric #endif
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric     return Segments;
12910b57cec5SDimitry Andric   }
12920b57cec5SDimitry Andric };
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric } // end anonymous namespace
12950b57cec5SDimitry Andric 
getUniqueSourceFiles() const12960b57cec5SDimitry Andric std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
12970b57cec5SDimitry Andric   std::vector<StringRef> Filenames;
12980b57cec5SDimitry Andric   for (const auto &Function : getCoveredFunctions())
1299e8d8bef9SDimitry Andric     llvm::append_range(Filenames, Function.Filenames);
13000b57cec5SDimitry Andric   llvm::sort(Filenames);
13010b57cec5SDimitry Andric   auto Last = std::unique(Filenames.begin(), Filenames.end());
13020b57cec5SDimitry Andric   Filenames.erase(Last, Filenames.end());
13030b57cec5SDimitry Andric   return Filenames;
13040b57cec5SDimitry Andric }
13050b57cec5SDimitry Andric 
gatherFileIDs(StringRef SourceFile,const FunctionRecord & Function)13060b57cec5SDimitry Andric static SmallBitVector gatherFileIDs(StringRef SourceFile,
13070b57cec5SDimitry Andric                                     const FunctionRecord &Function) {
13080b57cec5SDimitry Andric   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
13090b57cec5SDimitry Andric   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
13100b57cec5SDimitry Andric     if (SourceFile == Function.Filenames[I])
13110b57cec5SDimitry Andric       FilenameEquivalence[I] = true;
13120b57cec5SDimitry Andric   return FilenameEquivalence;
13130b57cec5SDimitry Andric }
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric /// Return the ID of the file where the definition of the function is located.
1316bdd1243dSDimitry Andric static std::optional<unsigned>
findMainViewFileID(const FunctionRecord & Function)1317bdd1243dSDimitry Andric findMainViewFileID(const FunctionRecord &Function) {
13180b57cec5SDimitry Andric   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
13190b57cec5SDimitry Andric   for (const auto &CR : Function.CountedRegions)
13200b57cec5SDimitry Andric     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
13210b57cec5SDimitry Andric       IsNotExpandedFile[CR.ExpandedFileID] = false;
13220b57cec5SDimitry Andric   int I = IsNotExpandedFile.find_first();
13230b57cec5SDimitry Andric   if (I == -1)
1324bdd1243dSDimitry Andric     return std::nullopt;
13250b57cec5SDimitry Andric   return I;
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric /// Check if SourceFile is the file that contains the definition of
1329bdd1243dSDimitry Andric /// the Function. Return the ID of the file in that case or std::nullopt
1330bdd1243dSDimitry Andric /// otherwise.
1331bdd1243dSDimitry Andric static std::optional<unsigned>
findMainViewFileID(StringRef SourceFile,const FunctionRecord & Function)1332bdd1243dSDimitry Andric findMainViewFileID(StringRef SourceFile, const FunctionRecord &Function) {
1333bdd1243dSDimitry Andric   std::optional<unsigned> I = findMainViewFileID(Function);
13340b57cec5SDimitry Andric   if (I && SourceFile == Function.Filenames[*I])
13350b57cec5SDimitry Andric     return I;
1336bdd1243dSDimitry Andric   return std::nullopt;
13370b57cec5SDimitry Andric }
13380b57cec5SDimitry Andric 
isExpansion(const CountedRegion & R,unsigned FileID)13390b57cec5SDimitry Andric static bool isExpansion(const CountedRegion &R, unsigned FileID) {
13400b57cec5SDimitry Andric   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
13410b57cec5SDimitry Andric }
13420b57cec5SDimitry Andric 
getCoverageForFile(StringRef Filename) const13430b57cec5SDimitry Andric CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
13440b57cec5SDimitry Andric   CoverageData FileCoverage(Filename);
13450b57cec5SDimitry Andric   std::vector<CountedRegion> Regions;
13460b57cec5SDimitry Andric 
13478bcb0991SDimitry Andric   // Look up the function records in the given file. Due to hash collisions on
13488bcb0991SDimitry Andric   // the filename, we may get back some records that are not in the file.
13498bcb0991SDimitry Andric   ArrayRef<unsigned> RecordIndices =
13508bcb0991SDimitry Andric       getImpreciseRecordIndicesForFilename(Filename);
13518bcb0991SDimitry Andric   for (unsigned RecordIndex : RecordIndices) {
13528bcb0991SDimitry Andric     const FunctionRecord &Function = Functions[RecordIndex];
13530b57cec5SDimitry Andric     auto MainFileID = findMainViewFileID(Filename, Function);
13540b57cec5SDimitry Andric     auto FileIDs = gatherFileIDs(Filename, Function);
13550b57cec5SDimitry Andric     for (const auto &CR : Function.CountedRegions)
13560b57cec5SDimitry Andric       if (FileIDs.test(CR.FileID)) {
13570b57cec5SDimitry Andric         Regions.push_back(CR);
13580b57cec5SDimitry Andric         if (MainFileID && isExpansion(CR, *MainFileID))
13590b57cec5SDimitry Andric           FileCoverage.Expansions.emplace_back(CR, Function);
13600b57cec5SDimitry Andric       }
1361e8d8bef9SDimitry Andric     // Capture branch regions specific to the function (excluding expansions).
1362e8d8bef9SDimitry Andric     for (const auto &CR : Function.CountedBranchRegions)
1363e8d8bef9SDimitry Andric       if (FileIDs.test(CR.FileID) && (CR.FileID == CR.ExpandedFileID))
1364e8d8bef9SDimitry Andric         FileCoverage.BranchRegions.push_back(CR);
1365c9157d92SDimitry Andric     // Capture MCDC records specific to the function.
1366c9157d92SDimitry Andric     for (const auto &MR : Function.MCDCRecords)
1367c9157d92SDimitry Andric       if (FileIDs.test(MR.getDecisionRegion().FileID))
1368c9157d92SDimitry Andric         FileCoverage.MCDCRecords.push_back(MR);
13690b57cec5SDimitry Andric   }
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
13720b57cec5SDimitry Andric   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric   return FileCoverage;
13750b57cec5SDimitry Andric }
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric std::vector<InstantiationGroup>
getInstantiationGroups(StringRef Filename) const13780b57cec5SDimitry Andric CoverageMapping::getInstantiationGroups(StringRef Filename) const {
13790b57cec5SDimitry Andric   FunctionInstantiationSetCollector InstantiationSetCollector;
13808bcb0991SDimitry Andric   // Look up the function records in the given file. Due to hash collisions on
13818bcb0991SDimitry Andric   // the filename, we may get back some records that are not in the file.
13828bcb0991SDimitry Andric   ArrayRef<unsigned> RecordIndices =
13838bcb0991SDimitry Andric       getImpreciseRecordIndicesForFilename(Filename);
13848bcb0991SDimitry Andric   for (unsigned RecordIndex : RecordIndices) {
13858bcb0991SDimitry Andric     const FunctionRecord &Function = Functions[RecordIndex];
13860b57cec5SDimitry Andric     auto MainFileID = findMainViewFileID(Filename, Function);
13870b57cec5SDimitry Andric     if (!MainFileID)
13880b57cec5SDimitry Andric       continue;
13890b57cec5SDimitry Andric     InstantiationSetCollector.insert(Function, *MainFileID);
13900b57cec5SDimitry Andric   }
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric   std::vector<InstantiationGroup> Result;
13930b57cec5SDimitry Andric   for (auto &InstantiationSet : InstantiationSetCollector) {
13940b57cec5SDimitry Andric     InstantiationGroup IG{InstantiationSet.first.first,
13950b57cec5SDimitry Andric                           InstantiationSet.first.second,
13960b57cec5SDimitry Andric                           std::move(InstantiationSet.second)};
13970b57cec5SDimitry Andric     Result.emplace_back(std::move(IG));
13980b57cec5SDimitry Andric   }
13990b57cec5SDimitry Andric   return Result;
14000b57cec5SDimitry Andric }
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric CoverageData
getCoverageForFunction(const FunctionRecord & Function) const14030b57cec5SDimitry Andric CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
14040b57cec5SDimitry Andric   auto MainFileID = findMainViewFileID(Function);
14050b57cec5SDimitry Andric   if (!MainFileID)
14060b57cec5SDimitry Andric     return CoverageData();
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
14090b57cec5SDimitry Andric   std::vector<CountedRegion> Regions;
14100b57cec5SDimitry Andric   for (const auto &CR : Function.CountedRegions)
14110b57cec5SDimitry Andric     if (CR.FileID == *MainFileID) {
14120b57cec5SDimitry Andric       Regions.push_back(CR);
14130b57cec5SDimitry Andric       if (isExpansion(CR, *MainFileID))
14140b57cec5SDimitry Andric         FunctionCoverage.Expansions.emplace_back(CR, Function);
14150b57cec5SDimitry Andric     }
1416e8d8bef9SDimitry Andric   // Capture branch regions specific to the function (excluding expansions).
1417e8d8bef9SDimitry Andric   for (const auto &CR : Function.CountedBranchRegions)
1418e8d8bef9SDimitry Andric     if (CR.FileID == *MainFileID)
1419e8d8bef9SDimitry Andric       FunctionCoverage.BranchRegions.push_back(CR);
14200b57cec5SDimitry Andric 
1421c9157d92SDimitry Andric   // Capture MCDC records specific to the function.
1422c9157d92SDimitry Andric   for (const auto &MR : Function.MCDCRecords)
1423c9157d92SDimitry Andric     if (MR.getDecisionRegion().FileID == *MainFileID)
1424c9157d92SDimitry Andric       FunctionCoverage.MCDCRecords.push_back(MR);
1425c9157d92SDimitry Andric 
14260b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
14270b57cec5SDimitry Andric                     << "\n");
14280b57cec5SDimitry Andric   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric   return FunctionCoverage;
14310b57cec5SDimitry Andric }
14320b57cec5SDimitry Andric 
getCoverageForExpansion(const ExpansionRecord & Expansion) const14330b57cec5SDimitry Andric CoverageData CoverageMapping::getCoverageForExpansion(
14340b57cec5SDimitry Andric     const ExpansionRecord &Expansion) const {
14350b57cec5SDimitry Andric   CoverageData ExpansionCoverage(
14360b57cec5SDimitry Andric       Expansion.Function.Filenames[Expansion.FileID]);
14370b57cec5SDimitry Andric   std::vector<CountedRegion> Regions;
14380b57cec5SDimitry Andric   for (const auto &CR : Expansion.Function.CountedRegions)
14390b57cec5SDimitry Andric     if (CR.FileID == Expansion.FileID) {
14400b57cec5SDimitry Andric       Regions.push_back(CR);
14410b57cec5SDimitry Andric       if (isExpansion(CR, Expansion.FileID))
14420b57cec5SDimitry Andric         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
14430b57cec5SDimitry Andric     }
1444e8d8bef9SDimitry Andric   for (const auto &CR : Expansion.Function.CountedBranchRegions)
1445e8d8bef9SDimitry Andric     // Capture branch regions that only pertain to the corresponding expansion.
1446e8d8bef9SDimitry Andric     if (CR.FileID == Expansion.FileID)
1447e8d8bef9SDimitry Andric       ExpansionCoverage.BranchRegions.push_back(CR);
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
14500b57cec5SDimitry Andric                     << Expansion.FileID << "\n");
14510b57cec5SDimitry Andric   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   return ExpansionCoverage;
14540b57cec5SDimitry Andric }
14550b57cec5SDimitry Andric 
LineCoverageStats(ArrayRef<const CoverageSegment * > LineSegments,const CoverageSegment * WrappedSegment,unsigned Line)14560b57cec5SDimitry Andric LineCoverageStats::LineCoverageStats(
14570b57cec5SDimitry Andric     ArrayRef<const CoverageSegment *> LineSegments,
14580b57cec5SDimitry Andric     const CoverageSegment *WrappedSegment, unsigned Line)
14590b57cec5SDimitry Andric     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
14600b57cec5SDimitry Andric       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
14610b57cec5SDimitry Andric   // Find the minimum number of regions which start in this line.
14620b57cec5SDimitry Andric   unsigned MinRegionCount = 0;
14630b57cec5SDimitry Andric   auto isStartOfRegion = [](const CoverageSegment *S) {
14640b57cec5SDimitry Andric     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
14650b57cec5SDimitry Andric   };
14660b57cec5SDimitry Andric   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
14670b57cec5SDimitry Andric     if (isStartOfRegion(LineSegments[I]))
14680b57cec5SDimitry Andric       ++MinRegionCount;
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   bool StartOfSkippedRegion = !LineSegments.empty() &&
14710b57cec5SDimitry Andric                               !LineSegments.front()->HasCount &&
14720b57cec5SDimitry Andric                               LineSegments.front()->IsRegionEntry;
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   HasMultipleRegions = MinRegionCount > 1;
14750b57cec5SDimitry Andric   Mapped =
14760b57cec5SDimitry Andric       !StartOfSkippedRegion &&
14770b57cec5SDimitry Andric       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
14780b57cec5SDimitry Andric 
1479a58f00eaSDimitry Andric   // if there is any starting segment at this line with a counter, it must be
1480a58f00eaSDimitry Andric   // mapped
1481a58f00eaSDimitry Andric   Mapped |= std::any_of(
1482a58f00eaSDimitry Andric       LineSegments.begin(), LineSegments.end(),
1483a58f00eaSDimitry Andric       [](const auto *Seq) { return Seq->IsRegionEntry && Seq->HasCount; });
1484a58f00eaSDimitry Andric 
1485a58f00eaSDimitry Andric   if (!Mapped) {
14860b57cec5SDimitry Andric     return;
1487a58f00eaSDimitry Andric   }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   // Pick the max count from the non-gap, region entry segments and the
14900b57cec5SDimitry Andric   // wrapped count.
14910b57cec5SDimitry Andric   if (WrappedSegment)
14920b57cec5SDimitry Andric     ExecutionCount = WrappedSegment->Count;
14930b57cec5SDimitry Andric   if (!MinRegionCount)
14940b57cec5SDimitry Andric     return;
14950b57cec5SDimitry Andric   for (const auto *LS : LineSegments)
14960b57cec5SDimitry Andric     if (isStartOfRegion(LS))
14970b57cec5SDimitry Andric       ExecutionCount = std::max(ExecutionCount, LS->Count);
14980b57cec5SDimitry Andric }
14990b57cec5SDimitry Andric 
operator ++()15000b57cec5SDimitry Andric LineCoverageIterator &LineCoverageIterator::operator++() {
15010b57cec5SDimitry Andric   if (Next == CD.end()) {
15020b57cec5SDimitry Andric     Stats = LineCoverageStats();
15030b57cec5SDimitry Andric     Ended = true;
15040b57cec5SDimitry Andric     return *this;
15050b57cec5SDimitry Andric   }
15060b57cec5SDimitry Andric   if (Segments.size())
15070b57cec5SDimitry Andric     WrappedSegment = Segments.back();
15080b57cec5SDimitry Andric   Segments.clear();
15090b57cec5SDimitry Andric   while (Next != CD.end() && Next->Line == Line)
15100b57cec5SDimitry Andric     Segments.push_back(&*Next++);
15110b57cec5SDimitry Andric   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
15120b57cec5SDimitry Andric   ++Line;
15130b57cec5SDimitry Andric   return *this;
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric 
getCoverageMapErrString(coveragemap_error Err,const std::string & ErrMsg="")1516c9157d92SDimitry Andric static std::string getCoverageMapErrString(coveragemap_error Err,
1517c9157d92SDimitry Andric                                            const std::string &ErrMsg = "") {
1518c9157d92SDimitry Andric   std::string Msg;
1519c9157d92SDimitry Andric   raw_string_ostream OS(Msg);
1520c9157d92SDimitry Andric 
15210b57cec5SDimitry Andric   switch (Err) {
15220b57cec5SDimitry Andric   case coveragemap_error::success:
1523c9157d92SDimitry Andric     OS << "success";
1524c9157d92SDimitry Andric     break;
15250b57cec5SDimitry Andric   case coveragemap_error::eof:
1526c9157d92SDimitry Andric     OS << "end of File";
1527c9157d92SDimitry Andric     break;
15280b57cec5SDimitry Andric   case coveragemap_error::no_data_found:
1529c9157d92SDimitry Andric     OS << "no coverage data found";
1530c9157d92SDimitry Andric     break;
15310b57cec5SDimitry Andric   case coveragemap_error::unsupported_version:
1532c9157d92SDimitry Andric     OS << "unsupported coverage format version";
1533c9157d92SDimitry Andric     break;
15340b57cec5SDimitry Andric   case coveragemap_error::truncated:
1535c9157d92SDimitry Andric     OS << "truncated coverage data";
1536c9157d92SDimitry Andric     break;
15370b57cec5SDimitry Andric   case coveragemap_error::malformed:
1538c9157d92SDimitry Andric     OS << "malformed coverage data";
1539c9157d92SDimitry Andric     break;
15405ffd83dbSDimitry Andric   case coveragemap_error::decompression_failed:
1541c9157d92SDimitry Andric     OS << "failed to decompress coverage data (zlib)";
1542c9157d92SDimitry Andric     break;
1543e8d8bef9SDimitry Andric   case coveragemap_error::invalid_or_missing_arch_specifier:
1544c9157d92SDimitry Andric     OS << "`-arch` specifier is invalid or missing for universal binary";
1545c9157d92SDimitry Andric     break;
15460b57cec5SDimitry Andric   }
1547c9157d92SDimitry Andric 
1548c9157d92SDimitry Andric   // If optional error message is not empty, append it to the message.
1549c9157d92SDimitry Andric   if (!ErrMsg.empty())
1550c9157d92SDimitry Andric     OS << ": " << ErrMsg;
1551c9157d92SDimitry Andric 
1552c9157d92SDimitry Andric   return Msg;
15530b57cec5SDimitry Andric }
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric namespace {
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
15580b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
15590b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
15600b57cec5SDimitry Andric class CoverageMappingErrorCategoryType : public std::error_category {
name() const15610b57cec5SDimitry Andric   const char *name() const noexcept override { return "llvm.coveragemap"; }
message(int IE) const15620b57cec5SDimitry Andric   std::string message(int IE) const override {
15630b57cec5SDimitry Andric     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
15640b57cec5SDimitry Andric   }
15650b57cec5SDimitry Andric };
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric } // end anonymous namespace
15680b57cec5SDimitry Andric 
message() const15690b57cec5SDimitry Andric std::string CoverageMapError::message() const {
1570c9157d92SDimitry Andric   return getCoverageMapErrString(Err, Msg);
15710b57cec5SDimitry Andric }
15720b57cec5SDimitry Andric 
coveragemap_category()15730b57cec5SDimitry Andric const std::error_category &llvm::coverage::coveragemap_category() {
1574753f127fSDimitry Andric   static CoverageMappingErrorCategoryType ErrorCategory;
1575753f127fSDimitry Andric   return ErrorCategory;
15760b57cec5SDimitry Andric }
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric char CoverageMapError::ID = 0;
1579