1dc707122SEaswaran Raman //=-- CoverageMapping.cpp - Code coverage mapping support ---------*- C++ -*-=//
2dc707122SEaswaran Raman //
3dc707122SEaswaran Raman //                     The LLVM Compiler Infrastructure
4dc707122SEaswaran Raman //
5dc707122SEaswaran Raman // This file is distributed under the University of Illinois Open Source
6dc707122SEaswaran Raman // License. See LICENSE.TXT for details.
7dc707122SEaswaran Raman //
8dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
9dc707122SEaswaran Raman //
10dc707122SEaswaran Raman // This file contains support for clang's and llvm's instrumentation based
11dc707122SEaswaran Raman // code coverage.
12dc707122SEaswaran Raman //
13dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
14dc707122SEaswaran Raman 
15dc707122SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
16dc707122SEaswaran Raman #include "llvm/ADT/DenseMap.h"
17dc707122SEaswaran Raman #include "llvm/ADT/Optional.h"
18dc707122SEaswaran Raman #include "llvm/ADT/SmallBitVector.h"
19dc707122SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
20dc707122SEaswaran Raman #include "llvm/ProfileData/InstrProfReader.h"
21dc707122SEaswaran Raman #include "llvm/Support/Debug.h"
22dc707122SEaswaran Raman #include "llvm/Support/Errc.h"
23dc707122SEaswaran Raman #include "llvm/Support/ErrorHandling.h"
24dc707122SEaswaran Raman #include "llvm/Support/ManagedStatic.h"
25dc707122SEaswaran Raman #include "llvm/Support/Path.h"
26dc707122SEaswaran Raman #include "llvm/Support/raw_ostream.h"
27dc707122SEaswaran Raman 
28dc707122SEaswaran Raman using namespace llvm;
29dc707122SEaswaran Raman using namespace coverage;
30dc707122SEaswaran Raman 
31dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping"
32dc707122SEaswaran Raman 
33dc707122SEaswaran Raman Counter CounterExpressionBuilder::get(const CounterExpression &E) {
34dc707122SEaswaran Raman   auto It = ExpressionIndices.find(E);
35dc707122SEaswaran Raman   if (It != ExpressionIndices.end())
36dc707122SEaswaran Raman     return Counter::getExpression(It->second);
37dc707122SEaswaran Raman   unsigned I = Expressions.size();
38dc707122SEaswaran Raman   Expressions.push_back(E);
39dc707122SEaswaran Raman   ExpressionIndices[E] = I;
40dc707122SEaswaran Raman   return Counter::getExpression(I);
41dc707122SEaswaran Raman }
42dc707122SEaswaran Raman 
43dc707122SEaswaran Raman void CounterExpressionBuilder::extractTerms(
44dc707122SEaswaran Raman     Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
45dc707122SEaswaran Raman   switch (C.getKind()) {
46dc707122SEaswaran Raman   case Counter::Zero:
47dc707122SEaswaran Raman     break;
48dc707122SEaswaran Raman   case Counter::CounterValueReference:
49dc707122SEaswaran Raman     Terms.push_back(std::make_pair(C.getCounterID(), Sign));
50dc707122SEaswaran Raman     break;
51dc707122SEaswaran Raman   case Counter::Expression:
52dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
53dc707122SEaswaran Raman     extractTerms(E.LHS, Sign, Terms);
54dc707122SEaswaran Raman     extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
55dc707122SEaswaran Raman                  Terms);
56dc707122SEaswaran Raman     break;
57dc707122SEaswaran Raman   }
58dc707122SEaswaran Raman }
59dc707122SEaswaran Raman 
60dc707122SEaswaran Raman Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
61dc707122SEaswaran Raman   // Gather constant terms.
62dc707122SEaswaran Raman   llvm::SmallVector<std::pair<unsigned, int>, 32> Terms;
63dc707122SEaswaran Raman   extractTerms(ExpressionTree, +1, Terms);
64dc707122SEaswaran Raman 
65dc707122SEaswaran Raman   // If there are no terms, this is just a zero. The algorithm below assumes at
66dc707122SEaswaran Raman   // least one term.
67dc707122SEaswaran Raman   if (Terms.size() == 0)
68dc707122SEaswaran Raman     return Counter::getZero();
69dc707122SEaswaran Raman 
70dc707122SEaswaran Raman   // Group the terms by counter ID.
71dc707122SEaswaran Raman   std::sort(Terms.begin(), Terms.end(),
72dc707122SEaswaran Raman             [](const std::pair<unsigned, int> &LHS,
73dc707122SEaswaran Raman                const std::pair<unsigned, int> &RHS) {
74dc707122SEaswaran Raman     return LHS.first < RHS.first;
75dc707122SEaswaran Raman   });
76dc707122SEaswaran Raman 
77dc707122SEaswaran Raman   // Combine terms by counter ID to eliminate counters that sum to zero.
78dc707122SEaswaran Raman   auto Prev = Terms.begin();
79dc707122SEaswaran Raman   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
80dc707122SEaswaran Raman     if (I->first == Prev->first) {
81dc707122SEaswaran Raman       Prev->second += I->second;
82dc707122SEaswaran Raman       continue;
83dc707122SEaswaran Raman     }
84dc707122SEaswaran Raman     ++Prev;
85dc707122SEaswaran Raman     *Prev = *I;
86dc707122SEaswaran Raman   }
87dc707122SEaswaran Raman   Terms.erase(++Prev, Terms.end());
88dc707122SEaswaran Raman 
89dc707122SEaswaran Raman   Counter C;
90dc707122SEaswaran Raman   // Create additions. We do this before subtractions to avoid constructs like
91dc707122SEaswaran Raman   // ((0 - X) + Y), as opposed to (Y - X).
92dc707122SEaswaran Raman   for (auto Term : Terms) {
93dc707122SEaswaran Raman     if (Term.second <= 0)
94dc707122SEaswaran Raman       continue;
95dc707122SEaswaran Raman     for (int I = 0; I < Term.second; ++I)
96dc707122SEaswaran Raman       if (C.isZero())
97dc707122SEaswaran Raman         C = Counter::getCounter(Term.first);
98dc707122SEaswaran Raman       else
99dc707122SEaswaran Raman         C = get(CounterExpression(CounterExpression::Add, C,
100dc707122SEaswaran Raman                                   Counter::getCounter(Term.first)));
101dc707122SEaswaran Raman   }
102dc707122SEaswaran Raman 
103dc707122SEaswaran Raman   // Create subtractions.
104dc707122SEaswaran Raman   for (auto Term : Terms) {
105dc707122SEaswaran Raman     if (Term.second >= 0)
106dc707122SEaswaran Raman       continue;
107dc707122SEaswaran Raman     for (int I = 0; I < -Term.second; ++I)
108dc707122SEaswaran Raman       C = get(CounterExpression(CounterExpression::Subtract, C,
109dc707122SEaswaran Raman                                 Counter::getCounter(Term.first)));
110dc707122SEaswaran Raman   }
111dc707122SEaswaran Raman   return C;
112dc707122SEaswaran Raman }
113dc707122SEaswaran Raman 
114dc707122SEaswaran Raman Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
115dc707122SEaswaran Raman   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
116dc707122SEaswaran Raman }
117dc707122SEaswaran Raman 
118dc707122SEaswaran Raman Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
119dc707122SEaswaran Raman   return simplify(
120dc707122SEaswaran Raman       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
121dc707122SEaswaran Raman }
122dc707122SEaswaran Raman 
123dc707122SEaswaran Raman void CounterMappingContext::dump(const Counter &C,
124dc707122SEaswaran Raman                                  llvm::raw_ostream &OS) const {
125dc707122SEaswaran Raman   switch (C.getKind()) {
126dc707122SEaswaran Raman   case Counter::Zero:
127dc707122SEaswaran Raman     OS << '0';
128dc707122SEaswaran Raman     return;
129dc707122SEaswaran Raman   case Counter::CounterValueReference:
130dc707122SEaswaran Raman     OS << '#' << C.getCounterID();
131dc707122SEaswaran Raman     break;
132dc707122SEaswaran Raman   case Counter::Expression: {
133dc707122SEaswaran Raman     if (C.getExpressionID() >= Expressions.size())
134dc707122SEaswaran Raman       return;
135dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
136dc707122SEaswaran Raman     OS << '(';
137dc707122SEaswaran Raman     dump(E.LHS, OS);
138dc707122SEaswaran Raman     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
139dc707122SEaswaran Raman     dump(E.RHS, OS);
140dc707122SEaswaran Raman     OS << ')';
141dc707122SEaswaran Raman     break;
142dc707122SEaswaran Raman   }
143dc707122SEaswaran Raman   }
144dc707122SEaswaran Raman   if (CounterValues.empty())
145dc707122SEaswaran Raman     return;
1469152fd17SVedant Kumar   Expected<int64_t> Value = evaluate(C);
1479152fd17SVedant Kumar   if (auto E = Value.takeError()) {
1489152fd17SVedant Kumar     llvm::consumeError(std::move(E));
149dc707122SEaswaran Raman     return;
1509152fd17SVedant Kumar   }
151dc707122SEaswaran Raman   OS << '[' << *Value << ']';
152dc707122SEaswaran Raman }
153dc707122SEaswaran Raman 
1549152fd17SVedant Kumar Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
155dc707122SEaswaran Raman   switch (C.getKind()) {
156dc707122SEaswaran Raman   case Counter::Zero:
157dc707122SEaswaran Raman     return 0;
158dc707122SEaswaran Raman   case Counter::CounterValueReference:
159dc707122SEaswaran Raman     if (C.getCounterID() >= CounterValues.size())
1609152fd17SVedant Kumar       return errorCodeToError(errc::argument_out_of_domain);
161dc707122SEaswaran Raman     return CounterValues[C.getCounterID()];
162dc707122SEaswaran Raman   case Counter::Expression: {
163dc707122SEaswaran Raman     if (C.getExpressionID() >= Expressions.size())
1649152fd17SVedant Kumar       return errorCodeToError(errc::argument_out_of_domain);
165dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
1669152fd17SVedant Kumar     Expected<int64_t> LHS = evaluate(E.LHS);
167dc707122SEaswaran Raman     if (!LHS)
168dc707122SEaswaran Raman       return LHS;
1699152fd17SVedant Kumar     Expected<int64_t> RHS = evaluate(E.RHS);
170dc707122SEaswaran Raman     if (!RHS)
171dc707122SEaswaran Raman       return RHS;
172dc707122SEaswaran Raman     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
173dc707122SEaswaran Raman   }
174dc707122SEaswaran Raman   }
175dc707122SEaswaran Raman   llvm_unreachable("Unhandled CounterKind");
176dc707122SEaswaran Raman }
177dc707122SEaswaran Raman 
178dc707122SEaswaran Raman void FunctionRecordIterator::skipOtherFiles() {
179dc707122SEaswaran Raman   while (Current != Records.end() && !Filename.empty() &&
180dc707122SEaswaran Raman          Filename != Current->Filenames[0])
181dc707122SEaswaran Raman     ++Current;
182dc707122SEaswaran Raman   if (Current == Records.end())
183dc707122SEaswaran Raman     *this = FunctionRecordIterator();
184dc707122SEaswaran Raman }
185dc707122SEaswaran Raman 
18668216d7bSVedant Kumar Error CoverageMapping::loadFunctionRecord(
18768216d7bSVedant Kumar     const CoverageMappingRecord &Record,
188dc707122SEaswaran Raman     IndexedInstrProfReader &ProfileReader) {
189743574b8SVedant Kumar   StringRef OrigFuncName = Record.FunctionName;
190743574b8SVedant Kumar   if (Record.Filenames.empty())
191743574b8SVedant Kumar     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
192743574b8SVedant Kumar   else
193743574b8SVedant Kumar     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
194743574b8SVedant Kumar 
195743574b8SVedant Kumar   // Don't load records for functions we've already seen.
196743574b8SVedant Kumar   if (!FunctionNames.insert(OrigFuncName).second)
197743574b8SVedant Kumar     return Error::success();
198743574b8SVedant Kumar 
199dc707122SEaswaran Raman   CounterMappingContext Ctx(Record.Expressions);
200dc707122SEaswaran Raman 
20168216d7bSVedant Kumar   std::vector<uint64_t> Counts;
20268216d7bSVedant Kumar   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
20368216d7bSVedant Kumar                                                 Record.FunctionHash, Counts)) {
2049152fd17SVedant Kumar     instrprof_error IPE = InstrProfError::take(std::move(E));
2059152fd17SVedant Kumar     if (IPE == instrprof_error::hash_mismatch) {
20668216d7bSVedant Kumar       MismatchedFunctionCount++;
20768216d7bSVedant Kumar       return Error::success();
2089152fd17SVedant Kumar     } else if (IPE != instrprof_error::unknown_function)
2099152fd17SVedant Kumar       return make_error<InstrProfError>(IPE);
210dc707122SEaswaran Raman     Counts.assign(Record.MappingRegions.size(), 0);
211dc707122SEaswaran Raman   }
212dc707122SEaswaran Raman   Ctx.setCounts(Counts);
213dc707122SEaswaran Raman 
214dc707122SEaswaran Raman   assert(!Record.MappingRegions.empty() && "Function has no regions");
215dc707122SEaswaran Raman 
216dc707122SEaswaran Raman   FunctionRecord Function(OrigFuncName, Record.Filenames);
217dc707122SEaswaran Raman   for (const auto &Region : Record.MappingRegions) {
2189152fd17SVedant Kumar     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
2199152fd17SVedant Kumar     if (auto E = ExecutionCount.takeError()) {
2209152fd17SVedant Kumar       llvm::consumeError(std::move(E));
22168216d7bSVedant Kumar       return Error::success();
2229152fd17SVedant Kumar     }
223dc707122SEaswaran Raman     Function.pushRegion(Region, *ExecutionCount);
224dc707122SEaswaran Raman   }
225dc707122SEaswaran Raman   if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
22668216d7bSVedant Kumar     MismatchedFunctionCount++;
22768216d7bSVedant Kumar     return Error::success();
228dc707122SEaswaran Raman   }
229dc707122SEaswaran Raman 
23068216d7bSVedant Kumar   Functions.push_back(std::move(Function));
23168216d7bSVedant Kumar   return Error::success();
232dc707122SEaswaran Raman }
233dc707122SEaswaran Raman 
23468216d7bSVedant Kumar Expected<std::unique_ptr<CoverageMapping>>
23568216d7bSVedant Kumar CoverageMapping::load(CoverageMappingReader &CoverageReader,
23668216d7bSVedant Kumar                       IndexedInstrProfReader &ProfileReader) {
23768216d7bSVedant Kumar   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
23868216d7bSVedant Kumar 
23968216d7bSVedant Kumar   for (const auto &Record : CoverageReader)
24068216d7bSVedant Kumar     if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
24168216d7bSVedant Kumar       return std::move(E);
24268216d7bSVedant Kumar 
243dc707122SEaswaran Raman   return std::move(Coverage);
244dc707122SEaswaran Raman }
245dc707122SEaswaran Raman 
246743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
247743574b8SVedant Kumar     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
248743574b8SVedant Kumar     IndexedInstrProfReader &ProfileReader) {
249743574b8SVedant Kumar   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
250743574b8SVedant Kumar 
251743574b8SVedant Kumar   for (const auto &CoverageReader : CoverageReaders)
252743574b8SVedant Kumar     for (const auto &Record : *CoverageReader)
253743574b8SVedant Kumar       if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
2549152fd17SVedant Kumar         return std::move(E);
255743574b8SVedant Kumar 
256743574b8SVedant Kumar   return std::move(Coverage);
257743574b8SVedant Kumar }
258743574b8SVedant Kumar 
259743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>>
260743574b8SVedant Kumar CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
261743574b8SVedant Kumar                       StringRef ProfileFilename, StringRef Arch) {
262dc707122SEaswaran Raman   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
2639152fd17SVedant Kumar   if (Error E = ProfileReaderOrErr.takeError())
2649152fd17SVedant Kumar     return std::move(E);
265dc707122SEaswaran Raman   auto ProfileReader = std::move(ProfileReaderOrErr.get());
266743574b8SVedant Kumar 
267743574b8SVedant Kumar   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
268743574b8SVedant Kumar   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
269743574b8SVedant Kumar   for (StringRef ObjectFilename : ObjectFilenames) {
270743574b8SVedant Kumar     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
271743574b8SVedant Kumar     if (std::error_code EC = CovMappingBufOrErr.getError())
272743574b8SVedant Kumar       return errorCodeToError(EC);
273743574b8SVedant Kumar     auto CoverageReaderOrErr =
274743574b8SVedant Kumar         BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
275743574b8SVedant Kumar     if (Error E = CoverageReaderOrErr.takeError())
276743574b8SVedant Kumar       return std::move(E);
277743574b8SVedant Kumar     Readers.push_back(std::move(CoverageReaderOrErr.get()));
278743574b8SVedant Kumar     Buffers.push_back(std::move(CovMappingBufOrErr.get()));
279743574b8SVedant Kumar   }
280743574b8SVedant Kumar   return load(Readers, *ProfileReader);
281dc707122SEaswaran Raman }
282dc707122SEaswaran Raman 
283dc707122SEaswaran Raman namespace {
284dc707122SEaswaran Raman /// \brief Distributes functions into instantiation sets.
285dc707122SEaswaran Raman ///
286dc707122SEaswaran Raman /// An instantiation set is a collection of functions that have the same source
287dc707122SEaswaran Raman /// code, ie, template functions specializations.
288dc707122SEaswaran Raman class FunctionInstantiationSetCollector {
289dc707122SEaswaran Raman   typedef DenseMap<std::pair<unsigned, unsigned>,
290dc707122SEaswaran Raman                    std::vector<const FunctionRecord *>> MapT;
291dc707122SEaswaran Raman   MapT InstantiatedFunctions;
292dc707122SEaswaran Raman 
293dc707122SEaswaran Raman public:
294dc707122SEaswaran Raman   void insert(const FunctionRecord &Function, unsigned FileID) {
295dc707122SEaswaran Raman     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
296dc707122SEaswaran Raman     while (I != E && I->FileID != FileID)
297dc707122SEaswaran Raman       ++I;
298dc707122SEaswaran Raman     assert(I != E && "function does not cover the given file");
299dc707122SEaswaran Raman     auto &Functions = InstantiatedFunctions[I->startLoc()];
300dc707122SEaswaran Raman     Functions.push_back(&Function);
301dc707122SEaswaran Raman   }
302dc707122SEaswaran Raman 
303dc707122SEaswaran Raman   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
304dc707122SEaswaran Raman 
305dc707122SEaswaran Raman   MapT::iterator end() { return InstantiatedFunctions.end(); }
306dc707122SEaswaran Raman };
307dc707122SEaswaran Raman 
308dc707122SEaswaran Raman class SegmentBuilder {
309dc707122SEaswaran Raman   std::vector<CoverageSegment> &Segments;
310dc707122SEaswaran Raman   SmallVector<const CountedRegion *, 8> ActiveRegions;
311dc707122SEaswaran Raman 
312dc707122SEaswaran Raman   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
313dc707122SEaswaran Raman 
314dc707122SEaswaran Raman   /// Start a segment with no count specified.
315dc707122SEaswaran Raman   void startSegment(unsigned Line, unsigned Col) {
316dc707122SEaswaran Raman     DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
317dc707122SEaswaran Raman     Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
318dc707122SEaswaran Raman   }
319dc707122SEaswaran Raman 
320dc707122SEaswaran Raman   /// Start a segment with the given Region's count.
321dc707122SEaswaran Raman   void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
322dc707122SEaswaran Raman                     const CountedRegion &Region) {
323dc707122SEaswaran Raman     // Avoid creating empty regions.
324dc707122SEaswaran Raman     if (!Segments.empty() && Segments.back().Line == Line &&
325dc707122SEaswaran Raman         Segments.back().Col == Col)
326dc707122SEaswaran Raman       Segments.pop_back();
327dc707122SEaswaran Raman     DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
328dc707122SEaswaran Raman     // Set this region's count.
329dc707122SEaswaran Raman     if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
330dc707122SEaswaran Raman       DEBUG(dbgs() << " with count " << Region.ExecutionCount);
331dc707122SEaswaran Raman       Segments.emplace_back(Line, Col, Region.ExecutionCount, IsRegionEntry);
332dc707122SEaswaran Raman     } else
333dc707122SEaswaran Raman       Segments.emplace_back(Line, Col, IsRegionEntry);
334dc707122SEaswaran Raman     DEBUG(dbgs() << "\n");
335dc707122SEaswaran Raman   }
336dc707122SEaswaran Raman 
337dc707122SEaswaran Raman   /// Start a segment for the given region.
338dc707122SEaswaran Raman   void startSegment(const CountedRegion &Region) {
339dc707122SEaswaran Raman     startSegment(Region.LineStart, Region.ColumnStart, true, Region);
340dc707122SEaswaran Raman   }
341dc707122SEaswaran Raman 
342dc707122SEaswaran Raman   /// Pop the top region off of the active stack, starting a new segment with
343dc707122SEaswaran Raman   /// the containing Region's count.
344dc707122SEaswaran Raman   void popRegion() {
345dc707122SEaswaran Raman     const CountedRegion *Active = ActiveRegions.back();
346dc707122SEaswaran Raman     unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
347dc707122SEaswaran Raman     ActiveRegions.pop_back();
348dc707122SEaswaran Raman     if (ActiveRegions.empty())
349dc707122SEaswaran Raman       startSegment(Line, Col);
350dc707122SEaswaran Raman     else
351dc707122SEaswaran Raman       startSegment(Line, Col, false, *ActiveRegions.back());
352dc707122SEaswaran Raman   }
353dc707122SEaswaran Raman 
354dc707122SEaswaran Raman   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
355dc707122SEaswaran Raman     for (const auto &Region : Regions) {
356dc707122SEaswaran Raman       // Pop any regions that end before this one starts.
357dc707122SEaswaran Raman       while (!ActiveRegions.empty() &&
358dc707122SEaswaran Raman              ActiveRegions.back()->endLoc() <= Region.startLoc())
359dc707122SEaswaran Raman         popRegion();
360dc707122SEaswaran Raman       // Add this region to the stack.
361dc707122SEaswaran Raman       ActiveRegions.push_back(&Region);
362dc707122SEaswaran Raman       startSegment(Region);
363dc707122SEaswaran Raman     }
364dc707122SEaswaran Raman     // Pop any regions that are left in the stack.
365dc707122SEaswaran Raman     while (!ActiveRegions.empty())
366dc707122SEaswaran Raman       popRegion();
367dc707122SEaswaran Raman   }
368dc707122SEaswaran Raman 
369dc707122SEaswaran Raman   /// Sort a nested sequence of regions from a single file.
370dc707122SEaswaran Raman   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
37127d8dd39SIgor Kudrin     std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
37227d8dd39SIgor Kudrin                                                  const CountedRegion &RHS) {
37327d8dd39SIgor Kudrin       if (LHS.startLoc() != RHS.startLoc())
37427d8dd39SIgor Kudrin         return LHS.startLoc() < RHS.startLoc();
37527d8dd39SIgor Kudrin       if (LHS.endLoc() != RHS.endLoc())
376dc707122SEaswaran Raman         // When LHS completely contains RHS, we sort LHS first.
377dc707122SEaswaran Raman         return RHS.endLoc() < LHS.endLoc();
37827d8dd39SIgor Kudrin       // If LHS and RHS cover the same area, we need to sort them according
37927d8dd39SIgor Kudrin       // to their kinds so that the most suitable region will become "active"
38027d8dd39SIgor Kudrin       // in combineRegions(). Because we accumulate counter values only from
38127d8dd39SIgor Kudrin       // regions of the same kind as the first region of the area, prefer
38227d8dd39SIgor Kudrin       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
38327d8dd39SIgor Kudrin       static_assert(coverage::CounterMappingRegion::CodeRegion <
38427d8dd39SIgor Kudrin                             coverage::CounterMappingRegion::ExpansionRegion &&
38527d8dd39SIgor Kudrin                         coverage::CounterMappingRegion::ExpansionRegion <
38627d8dd39SIgor Kudrin                             coverage::CounterMappingRegion::SkippedRegion,
38727d8dd39SIgor Kudrin                     "Unexpected order of region kind values");
38827d8dd39SIgor Kudrin       return LHS.Kind < RHS.Kind;
389dc707122SEaswaran Raman     });
390dc707122SEaswaran Raman   }
391dc707122SEaswaran Raman 
392dc707122SEaswaran Raman   /// Combine counts of regions which cover the same area.
393dc707122SEaswaran Raman   static ArrayRef<CountedRegion>
394dc707122SEaswaran Raman   combineRegions(MutableArrayRef<CountedRegion> Regions) {
395dc707122SEaswaran Raman     if (Regions.empty())
396dc707122SEaswaran Raman       return Regions;
397dc707122SEaswaran Raman     auto Active = Regions.begin();
398dc707122SEaswaran Raman     auto End = Regions.end();
399dc707122SEaswaran Raman     for (auto I = Regions.begin() + 1; I != End; ++I) {
400dc707122SEaswaran Raman       if (Active->startLoc() != I->startLoc() ||
401dc707122SEaswaran Raman           Active->endLoc() != I->endLoc()) {
402dc707122SEaswaran Raman         // Shift to the next region.
403dc707122SEaswaran Raman         ++Active;
404dc707122SEaswaran Raman         if (Active != I)
405dc707122SEaswaran Raman           *Active = *I;
406dc707122SEaswaran Raman         continue;
407dc707122SEaswaran Raman       }
408dc707122SEaswaran Raman       // Merge duplicate region.
40927d8dd39SIgor Kudrin       // If CodeRegions and ExpansionRegions cover the same area, it's probably
41027d8dd39SIgor Kudrin       // a macro which is fully expanded to another macro. In that case, we need
41127d8dd39SIgor Kudrin       // to accumulate counts only from CodeRegions, or else the area will be
41227d8dd39SIgor Kudrin       // counted twice.
41327d8dd39SIgor Kudrin       // On the other hand, a macro may have a nested macro in its body. If the
41427d8dd39SIgor Kudrin       // outer macro is used several times, the ExpansionRegion for the nested
41527d8dd39SIgor Kudrin       // macro will also be added several times. These ExpansionRegions cover
41627d8dd39SIgor Kudrin       // the same source locations and have to be combined to reach the correct
41727d8dd39SIgor Kudrin       // value for that area.
41827d8dd39SIgor Kudrin       // We add counts of the regions of the same kind as the active region
41927d8dd39SIgor Kudrin       // to handle the both situations.
42027d8dd39SIgor Kudrin       if (I->Kind == Active->Kind)
421dc707122SEaswaran Raman         Active->ExecutionCount += I->ExecutionCount;
422dc707122SEaswaran Raman     }
423dc707122SEaswaran Raman     return Regions.drop_back(std::distance(++Active, End));
424dc707122SEaswaran Raman   }
425dc707122SEaswaran Raman 
426dc707122SEaswaran Raman public:
427dc707122SEaswaran Raman   /// Build a list of CoverageSegments from a list of Regions.
428dc707122SEaswaran Raman   static std::vector<CoverageSegment>
429dc707122SEaswaran Raman   buildSegments(MutableArrayRef<CountedRegion> Regions) {
430dc707122SEaswaran Raman     std::vector<CoverageSegment> Segments;
431dc707122SEaswaran Raman     SegmentBuilder Builder(Segments);
432dc707122SEaswaran Raman 
433dc707122SEaswaran Raman     sortNestedRegions(Regions);
434dc707122SEaswaran Raman     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
435dc707122SEaswaran Raman 
436dc707122SEaswaran Raman     Builder.buildSegmentsImpl(CombinedRegions);
437dc707122SEaswaran Raman     return Segments;
438dc707122SEaswaran Raman   }
439dc707122SEaswaran Raman };
440dc707122SEaswaran Raman }
441dc707122SEaswaran Raman 
442dc707122SEaswaran Raman std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
443dc707122SEaswaran Raman   std::vector<StringRef> Filenames;
444dc707122SEaswaran Raman   for (const auto &Function : getCoveredFunctions())
445dc707122SEaswaran Raman     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
446dc707122SEaswaran Raman                      Function.Filenames.end());
447dc707122SEaswaran Raman   std::sort(Filenames.begin(), Filenames.end());
448dc707122SEaswaran Raman   auto Last = std::unique(Filenames.begin(), Filenames.end());
449dc707122SEaswaran Raman   Filenames.erase(Last, Filenames.end());
450dc707122SEaswaran Raman   return Filenames;
451dc707122SEaswaran Raman }
452dc707122SEaswaran Raman 
453dc707122SEaswaran Raman static SmallBitVector gatherFileIDs(StringRef SourceFile,
454dc707122SEaswaran Raman                                     const FunctionRecord &Function) {
455dc707122SEaswaran Raman   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
456dc707122SEaswaran Raman   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
457dc707122SEaswaran Raman     if (SourceFile == Function.Filenames[I])
458dc707122SEaswaran Raman       FilenameEquivalence[I] = true;
459dc707122SEaswaran Raman   return FilenameEquivalence;
460dc707122SEaswaran Raman }
461dc707122SEaswaran Raman 
462dc707122SEaswaran Raman /// Return the ID of the file where the definition of the function is located.
463dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
464dc707122SEaswaran Raman   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
465dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
466dc707122SEaswaran Raman     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
467dc707122SEaswaran Raman       IsNotExpandedFile[CR.ExpandedFileID] = false;
468dc707122SEaswaran Raman   int I = IsNotExpandedFile.find_first();
469dc707122SEaswaran Raman   if (I == -1)
470dc707122SEaswaran Raman     return None;
471dc707122SEaswaran Raman   return I;
472dc707122SEaswaran Raman }
473dc707122SEaswaran Raman 
474dc707122SEaswaran Raman /// Check if SourceFile is the file that contains the definition of
475dc707122SEaswaran Raman /// the Function. Return the ID of the file in that case or None otherwise.
476dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
477dc707122SEaswaran Raman                                              const FunctionRecord &Function) {
478dc707122SEaswaran Raman   Optional<unsigned> I = findMainViewFileID(Function);
479dc707122SEaswaran Raman   if (I && SourceFile == Function.Filenames[*I])
480dc707122SEaswaran Raman     return I;
481dc707122SEaswaran Raman   return None;
482dc707122SEaswaran Raman }
483dc707122SEaswaran Raman 
484dc707122SEaswaran Raman static bool isExpansion(const CountedRegion &R, unsigned FileID) {
485dc707122SEaswaran Raman   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
486dc707122SEaswaran Raman }
487dc707122SEaswaran Raman 
4887fcc5472SVedant Kumar CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
489dc707122SEaswaran Raman   CoverageData FileCoverage(Filename);
490dc707122SEaswaran Raman   std::vector<coverage::CountedRegion> Regions;
491dc707122SEaswaran Raman 
492dc707122SEaswaran Raman   for (const auto &Function : Functions) {
493dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
494dc707122SEaswaran Raman     auto FileIDs = gatherFileIDs(Filename, Function);
495dc707122SEaswaran Raman     for (const auto &CR : Function.CountedRegions)
496dc707122SEaswaran Raman       if (FileIDs.test(CR.FileID)) {
497dc707122SEaswaran Raman         Regions.push_back(CR);
498dc707122SEaswaran Raman         if (MainFileID && isExpansion(CR, *MainFileID))
499dc707122SEaswaran Raman           FileCoverage.Expansions.emplace_back(CR, Function);
500dc707122SEaswaran Raman       }
501dc707122SEaswaran Raman   }
502dc707122SEaswaran Raman 
503dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
504dc707122SEaswaran Raman   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
505dc707122SEaswaran Raman 
506dc707122SEaswaran Raman   return FileCoverage;
507dc707122SEaswaran Raman }
508dc707122SEaswaran Raman 
509dc707122SEaswaran Raman std::vector<const FunctionRecord *>
510f681e2e5SVedant Kumar CoverageMapping::getInstantiations(StringRef Filename) const {
511dc707122SEaswaran Raman   FunctionInstantiationSetCollector InstantiationSetCollector;
512dc707122SEaswaran Raman   for (const auto &Function : Functions) {
513dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
514dc707122SEaswaran Raman     if (!MainFileID)
515dc707122SEaswaran Raman       continue;
516dc707122SEaswaran Raman     InstantiationSetCollector.insert(Function, *MainFileID);
517dc707122SEaswaran Raman   }
518dc707122SEaswaran Raman 
519dc707122SEaswaran Raman   std::vector<const FunctionRecord *> Result;
520dc707122SEaswaran Raman   for (const auto &InstantiationSet : InstantiationSetCollector) {
521dc707122SEaswaran Raman     if (InstantiationSet.second.size() < 2)
522dc707122SEaswaran Raman       continue;
523dc707122SEaswaran Raman     Result.insert(Result.end(), InstantiationSet.second.begin(),
524dc707122SEaswaran Raman                   InstantiationSet.second.end());
525dc707122SEaswaran Raman   }
526dc707122SEaswaran Raman   return Result;
527dc707122SEaswaran Raman }
528dc707122SEaswaran Raman 
529dc707122SEaswaran Raman CoverageData
530f681e2e5SVedant Kumar CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
531dc707122SEaswaran Raman   auto MainFileID = findMainViewFileID(Function);
532dc707122SEaswaran Raman   if (!MainFileID)
533dc707122SEaswaran Raman     return CoverageData();
534dc707122SEaswaran Raman 
535dc707122SEaswaran Raman   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
536dc707122SEaswaran Raman   std::vector<coverage::CountedRegion> Regions;
537dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
538dc707122SEaswaran Raman     if (CR.FileID == *MainFileID) {
539dc707122SEaswaran Raman       Regions.push_back(CR);
540dc707122SEaswaran Raman       if (isExpansion(CR, *MainFileID))
541dc707122SEaswaran Raman         FunctionCoverage.Expansions.emplace_back(CR, Function);
542dc707122SEaswaran Raman     }
543dc707122SEaswaran Raman 
544dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
545dc707122SEaswaran Raman   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
546dc707122SEaswaran Raman 
547dc707122SEaswaran Raman   return FunctionCoverage;
548dc707122SEaswaran Raman }
549dc707122SEaswaran Raman 
550f681e2e5SVedant Kumar CoverageData CoverageMapping::getCoverageForExpansion(
551f681e2e5SVedant Kumar     const ExpansionRecord &Expansion) const {
552dc707122SEaswaran Raman   CoverageData ExpansionCoverage(
553dc707122SEaswaran Raman       Expansion.Function.Filenames[Expansion.FileID]);
554dc707122SEaswaran Raman   std::vector<coverage::CountedRegion> Regions;
555dc707122SEaswaran Raman   for (const auto &CR : Expansion.Function.CountedRegions)
556dc707122SEaswaran Raman     if (CR.FileID == Expansion.FileID) {
557dc707122SEaswaran Raman       Regions.push_back(CR);
558dc707122SEaswaran Raman       if (isExpansion(CR, Expansion.FileID))
559dc707122SEaswaran Raman         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
560dc707122SEaswaran Raman     }
561dc707122SEaswaran Raman 
562dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
563dc707122SEaswaran Raman                << "\n");
564dc707122SEaswaran Raman   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
565dc707122SEaswaran Raman 
566dc707122SEaswaran Raman   return ExpansionCoverage;
567dc707122SEaswaran Raman }
568dc707122SEaswaran Raman 
569dc707122SEaswaran Raman namespace {
5709152fd17SVedant Kumar std::string getCoverageMapErrString(coveragemap_error Err) {
5719152fd17SVedant Kumar   switch (Err) {
572dc707122SEaswaran Raman   case coveragemap_error::success:
573dc707122SEaswaran Raman     return "Success";
574dc707122SEaswaran Raman   case coveragemap_error::eof:
575dc707122SEaswaran Raman     return "End of File";
576dc707122SEaswaran Raman   case coveragemap_error::no_data_found:
577dc707122SEaswaran Raman     return "No coverage data found";
578dc707122SEaswaran Raman   case coveragemap_error::unsupported_version:
579dc707122SEaswaran Raman     return "Unsupported coverage format version";
580dc707122SEaswaran Raman   case coveragemap_error::truncated:
581dc707122SEaswaran Raman     return "Truncated coverage data";
582dc707122SEaswaran Raman   case coveragemap_error::malformed:
583dc707122SEaswaran Raman     return "Malformed coverage data";
584dc707122SEaswaran Raman   }
585dc707122SEaswaran Raman   llvm_unreachable("A value of coveragemap_error has no message.");
586dc707122SEaswaran Raman }
5879152fd17SVedant Kumar 
5884718f8b5SPeter Collingbourne // FIXME: This class is only here to support the transition to llvm::Error. It
5894718f8b5SPeter Collingbourne // will be removed once this transition is complete. Clients should prefer to
5904718f8b5SPeter Collingbourne // deal with the Error value directly, rather than converting to error_code.
5919152fd17SVedant Kumar class CoverageMappingErrorCategoryType : public std::error_category {
592*990504e6SReid Kleckner   const char *name() const noexcept override { return "llvm.coveragemap"; }
5939152fd17SVedant Kumar   std::string message(int IE) const override {
5949152fd17SVedant Kumar     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
5959152fd17SVedant Kumar   }
596dc707122SEaswaran Raman };
5979152fd17SVedant Kumar } // end anonymous namespace
5989152fd17SVedant Kumar 
5999152fd17SVedant Kumar std::string CoverageMapError::message() const {
6009152fd17SVedant Kumar   return getCoverageMapErrString(Err);
601dc707122SEaswaran Raman }
602dc707122SEaswaran Raman 
603dc707122SEaswaran Raman static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
604dc707122SEaswaran Raman 
605dc707122SEaswaran Raman const std::error_category &llvm::coverage::coveragemap_category() {
606dc707122SEaswaran Raman   return *ErrorCategory;
607dc707122SEaswaran Raman }
6089152fd17SVedant Kumar 
6099152fd17SVedant Kumar char CoverageMapError::ID = 0;
610