blob: e130565500f5a81ffdfe51e2d316b25f8962929e [file] [log] [blame]
Alex Lorenza20a5d52014-07-24 23:57:54 +00001//=-- CoverageMapping.cpp - Code coverage mapping support ---------*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for clang's and llvm's instrumentation based
11// code coverage.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ProfileData/CoverageMapping.h"
Justin Bogner953e2402014-09-20 15:31:56 +000016#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/Optional.h"
Benjamin Kramer71e1eb52015-02-12 16:18:07 +000018#include "llvm/ADT/SmallBitVector.h"
Justin Bogner953e2402014-09-20 15:31:56 +000019#include "llvm/ProfileData/CoverageMappingReader.h"
20#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb35a72a2014-09-25 00:34:18 +000021#include "llvm/Support/Debug.h"
Rafael Espindola74f29322015-06-13 17:23:04 +000022#include "llvm/Support/Errc.h"
Justin Bogner85b0a032014-09-08 21:04:00 +000023#include "llvm/Support/ErrorHandling.h"
Justin Bogner367a9f22015-05-06 23:19:35 +000024#include "llvm/Support/ManagedStatic.h"
Justin Bogner0b4c4842015-05-05 23:44:48 +000025#include "llvm/Support/Path.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000026#include "llvm/Support/raw_ostream.h"
Alex Lorenza20a5d52014-07-24 23:57:54 +000027
28using namespace llvm;
29using namespace coverage;
30
Justin Bognerb35a72a2014-09-25 00:34:18 +000031#define DEBUG_TYPE "coverage-mapping"
32
Alex Lorenza20a5d52014-07-24 23:57:54 +000033Counter CounterExpressionBuilder::get(const CounterExpression &E) {
Justin Bognerad69e642014-10-02 17:14:18 +000034 auto It = ExpressionIndices.find(E);
35 if (It != ExpressionIndices.end())
36 return Counter::getExpression(It->second);
37 unsigned I = Expressions.size();
Alex Lorenza20a5d52014-07-24 23:57:54 +000038 Expressions.push_back(E);
Justin Bognerad69e642014-10-02 17:14:18 +000039 ExpressionIndices[E] = I;
40 return Counter::getExpression(I);
Alex Lorenza20a5d52014-07-24 23:57:54 +000041}
42
Justin Bognerf9535c42014-10-02 16:43:31 +000043void CounterExpressionBuilder::extractTerms(
44 Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
Alex Lorenza20a5d52014-07-24 23:57:54 +000045 switch (C.getKind()) {
46 case Counter::Zero:
47 break;
48 case Counter::CounterValueReference:
Justin Bognerf9535c42014-10-02 16:43:31 +000049 Terms.push_back(std::make_pair(C.getCounterID(), Sign));
Alex Lorenza20a5d52014-07-24 23:57:54 +000050 break;
51 case Counter::Expression:
52 const auto &E = Expressions[C.getExpressionID()];
Justin Bognerf9535c42014-10-02 16:43:31 +000053 extractTerms(E.LHS, Sign, Terms);
54 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
55 Terms);
Alex Lorenza20a5d52014-07-24 23:57:54 +000056 break;
57 }
58}
59
60Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
61 // Gather constant terms.
Justin Bognerf9535c42014-10-02 16:43:31 +000062 llvm::SmallVector<std::pair<unsigned, int>, 32> Terms;
63 extractTerms(ExpressionTree, +1, Terms);
64
65 // If there are no terms, this is just a zero. The algorithm below assumes at
66 // least one term.
67 if (Terms.size() == 0)
68 return Counter::getZero();
69
70 // Group the terms by counter ID.
71 std::sort(Terms.begin(), Terms.end(),
72 [](const std::pair<unsigned, int> &LHS,
73 const std::pair<unsigned, int> &RHS) {
74 return LHS.first < RHS.first;
75 });
76
77 // Combine terms by counter ID to eliminate counters that sum to zero.
78 auto Prev = Terms.begin();
79 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
80 if (I->first == Prev->first) {
81 Prev->second += I->second;
82 continue;
83 }
84 ++Prev;
85 *Prev = *I;
86 }
87 Terms.erase(++Prev, Terms.end());
Alex Lorenza20a5d52014-07-24 23:57:54 +000088
89 Counter C;
Justin Bognerf9535c42014-10-02 16:43:31 +000090 // Create additions. We do this before subtractions to avoid constructs like
91 // ((0 - X) + Y), as opposed to (Y - X).
92 for (auto Term : Terms) {
93 if (Term.second <= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +000094 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +000095 for (int I = 0; I < Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +000096 if (C.isZero())
Justin Bognerf9535c42014-10-02 16:43:31 +000097 C = Counter::getCounter(Term.first);
Alex Lorenza20a5d52014-07-24 23:57:54 +000098 else
99 C = get(CounterExpression(CounterExpression::Add, C,
Justin Bognerf9535c42014-10-02 16:43:31 +0000100 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000101 }
102
103 // Create subtractions.
Justin Bognerf9535c42014-10-02 16:43:31 +0000104 for (auto Term : Terms) {
105 if (Term.second >= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000106 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +0000107 for (int I = 0; I < -Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000108 C = get(CounterExpression(CounterExpression::Subtract, C,
Justin Bognerf9535c42014-10-02 16:43:31 +0000109 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000110 }
111 return C;
112}
113
114Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
115 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
116}
117
118Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
119 return simplify(
120 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
121}
122
123void CounterMappingContext::dump(const Counter &C,
124 llvm::raw_ostream &OS) const {
125 switch (C.getKind()) {
126 case Counter::Zero:
127 OS << '0';
128 return;
129 case Counter::CounterValueReference:
130 OS << '#' << C.getCounterID();
131 break;
132 case Counter::Expression: {
133 if (C.getExpressionID() >= Expressions.size())
134 return;
135 const auto &E = Expressions[C.getExpressionID()];
136 OS << '(';
Alex Lorenza422911c2014-07-29 19:58:16 +0000137 dump(E.LHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000138 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
Alex Lorenza422911c2014-07-29 19:58:16 +0000139 dump(E.RHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000140 OS << ')';
141 break;
142 }
143 }
144 if (CounterValues.empty())
145 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000146 ErrorOr<int64_t> Value = evaluate(C);
147 if (!Value)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000148 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000149 OS << '[' << *Value << ']';
Alex Lorenza20a5d52014-07-24 23:57:54 +0000150}
151
Justin Bogner85b0a032014-09-08 21:04:00 +0000152ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000153 switch (C.getKind()) {
154 case Counter::Zero:
155 return 0;
156 case Counter::CounterValueReference:
Justin Bogner85b0a032014-09-08 21:04:00 +0000157 if (C.getCounterID() >= CounterValues.size())
Rafael Espindola74f29322015-06-13 17:23:04 +0000158 return make_error_code(errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000159 return CounterValues[C.getCounterID()];
160 case Counter::Expression: {
Justin Bogner85b0a032014-09-08 21:04:00 +0000161 if (C.getExpressionID() >= Expressions.size())
Rafael Espindola74f29322015-06-13 17:23:04 +0000162 return make_error_code(errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000163 const auto &E = Expressions[C.getExpressionID()];
Justin Bogner85b0a032014-09-08 21:04:00 +0000164 ErrorOr<int64_t> LHS = evaluate(E.LHS);
165 if (!LHS)
166 return LHS;
167 ErrorOr<int64_t> RHS = evaluate(E.RHS);
168 if (!RHS)
169 return RHS;
170 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000171 }
172 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000173 llvm_unreachable("Unhandled CounterKind");
Alex Lorenza20a5d52014-07-24 23:57:54 +0000174}
Justin Bogner953e2402014-09-20 15:31:56 +0000175
Justin Bognerd5fca922014-11-14 01:50:32 +0000176void FunctionRecordIterator::skipOtherFiles() {
177 while (Current != Records.end() && !Filename.empty() &&
178 Filename != Current->Filenames[0])
179 ++Current;
180 if (Current == Records.end())
181 *this = FunctionRecordIterator();
182}
183
Justin Bogner953e2402014-09-20 15:31:56 +0000184ErrorOr<std::unique_ptr<CoverageMapping>>
Justin Bogner1d29c082015-02-18 18:01:14 +0000185CoverageMapping::load(CoverageMappingReader &CoverageReader,
Justin Bogner953e2402014-09-20 15:31:56 +0000186 IndexedInstrProfReader &ProfileReader) {
187 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
188
189 std::vector<uint64_t> Counts;
190 for (const auto &Record : CoverageReader) {
Justin Bogner428c6052015-02-18 18:40:46 +0000191 CounterMappingContext Ctx(Record.Expressions);
192
Justin Bogner953e2402014-09-20 15:31:56 +0000193 Counts.clear();
194 if (std::error_code EC = ProfileReader.getFunctionCounts(
195 Record.FunctionName, Record.FunctionHash, Counts)) {
Justin Bogner428c6052015-02-18 18:40:46 +0000196 if (EC == instrprof_error::hash_mismatch) {
197 Coverage->MismatchedFunctionCount++;
198 continue;
199 } else if (EC != instrprof_error::unknown_function)
Justin Bogner953e2402014-09-20 15:31:56 +0000200 return EC;
Justin Bogner82a64512015-05-13 22:03:04 +0000201 Counts.assign(Record.MappingRegions.size(), 0);
202 }
203 Ctx.setCounts(Counts);
Justin Bogner953e2402014-09-20 15:31:56 +0000204
Justin Bogner428c6052015-02-18 18:40:46 +0000205 assert(!Record.MappingRegions.empty() && "Function has no regions");
Justin Bogner0b4c4842015-05-05 23:44:48 +0000206
Xinliang David Li4ec40142015-12-15 19:44:45 +0000207 StringRef OrigFuncName = Record.FunctionName;
Vedant Kumar43a85652016-03-28 15:49:08 +0000208 if (Record.Filenames.empty())
209 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
210 else
Xinliang David Li4ec40142015-12-15 19:44:45 +0000211 OrigFuncName =
212 getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
213 FunctionRecord Function(OrigFuncName, Record.Filenames);
Justin Bogner953e2402014-09-20 15:31:56 +0000214 for (const auto &Region : Record.MappingRegions) {
215 ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
216 if (!ExecutionCount)
217 break;
Justin Bogner428c6052015-02-18 18:40:46 +0000218 Function.pushRegion(Region, *ExecutionCount);
Justin Bogner953e2402014-09-20 15:31:56 +0000219 }
220 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
221 Coverage->MismatchedFunctionCount++;
222 continue;
223 }
224
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000225 Coverage->Functions.push_back(std::move(Function));
Justin Bogner953e2402014-09-20 15:31:56 +0000226 }
227
228 return std::move(Coverage);
229}
230
Justin Bogner19a93ba2014-09-20 17:19:52 +0000231ErrorOr<std::unique_ptr<CoverageMapping>>
Justin Bogner43795352015-03-11 02:30:51 +0000232CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename,
Frederic Rissebc162a2015-06-22 21:33:24 +0000233 StringRef Arch) {
Justin Bogner19a93ba2014-09-20 17:19:52 +0000234 auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
Justin Bogner43e51632015-02-26 20:06:28 +0000235 if (std::error_code EC = CounterMappingBuff.getError())
Justin Bogner19a93ba2014-09-20 17:19:52 +0000236 return EC;
Justin Bogner43e51632015-02-26 20:06:28 +0000237 auto CoverageReaderOrErr =
Justin Bogner43795352015-03-11 02:30:51 +0000238 BinaryCoverageReader::create(CounterMappingBuff.get(), Arch);
Justin Bogner43e51632015-02-26 20:06:28 +0000239 if (std::error_code EC = CoverageReaderOrErr.getError())
Justin Bogner19a93ba2014-09-20 17:19:52 +0000240 return EC;
Justin Bogner43e51632015-02-26 20:06:28 +0000241 auto CoverageReader = std::move(CoverageReaderOrErr.get());
Justin Bognerab89ed72015-02-16 21:28:58 +0000242 auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
243 if (auto EC = ProfileReaderOrErr.getError())
Justin Bogner19a93ba2014-09-20 17:19:52 +0000244 return EC;
Justin Bognerab89ed72015-02-16 21:28:58 +0000245 auto ProfileReader = std::move(ProfileReaderOrErr.get());
Justin Bogner43e51632015-02-26 20:06:28 +0000246 return load(*CoverageReader, *ProfileReader);
Justin Bogner19a93ba2014-09-20 17:19:52 +0000247}
248
Justin Bogner953e2402014-09-20 15:31:56 +0000249namespace {
250/// \brief Distributes functions into instantiation sets.
251///
252/// An instantiation set is a collection of functions that have the same source
253/// code, ie, template functions specializations.
254class FunctionInstantiationSetCollector {
255 typedef DenseMap<std::pair<unsigned, unsigned>,
256 std::vector<const FunctionRecord *>> MapT;
257 MapT InstantiatedFunctions;
258
259public:
260 void insert(const FunctionRecord &Function, unsigned FileID) {
261 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
262 while (I != E && I->FileID != FileID)
263 ++I;
264 assert(I != E && "function does not cover the given file");
265 auto &Functions = InstantiatedFunctions[I->startLoc()];
266 Functions.push_back(&Function);
267 }
268
269 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
270
271 MapT::iterator end() { return InstantiatedFunctions.end(); }
272};
273
274class SegmentBuilder {
Igor Kudrinc0774e62016-04-14 09:10:00 +0000275 std::vector<CoverageSegment> &Segments;
Justin Bogner953e2402014-09-20 15:31:56 +0000276 SmallVector<const CountedRegion *, 8> ActiveRegions;
277
Igor Kudrinc0774e62016-04-14 09:10:00 +0000278 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
279
Justin Bogner953e2402014-09-20 15:31:56 +0000280 /// Start a segment with no count specified.
281 void startSegment(unsigned Line, unsigned Col) {
Justin Bognerb35a72a2014-09-25 00:34:18 +0000282 DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000283 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
284 }
285
286 /// Start a segment with the given Region's count.
287 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
288 const CountedRegion &Region) {
289 if (Segments.empty())
290 Segments.emplace_back(Line, Col, IsRegionEntry);
291 CoverageSegment S = Segments.back();
292 // Avoid creating empty regions.
293 if (S.Line != Line || S.Col != Col) {
294 Segments.emplace_back(Line, Col, IsRegionEntry);
295 S = Segments.back();
296 }
Justin Bognerb35a72a2014-09-25 00:34:18 +0000297 DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
Justin Bogner953e2402014-09-20 15:31:56 +0000298 // Set this region's count.
Justin Bognerb35a72a2014-09-25 00:34:18 +0000299 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
300 DEBUG(dbgs() << " with count " << Region.ExecutionCount);
Justin Bogner953e2402014-09-20 15:31:56 +0000301 Segments.back().setCount(Region.ExecutionCount);
Justin Bognerb35a72a2014-09-25 00:34:18 +0000302 }
303 DEBUG(dbgs() << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000304 }
305
306 /// Start a segment for the given region.
307 void startSegment(const CountedRegion &Region) {
308 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
309 }
310
311 /// Pop the top region off of the active stack, starting a new segment with
312 /// the containing Region's count.
313 void popRegion() {
314 const CountedRegion *Active = ActiveRegions.back();
315 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
316 ActiveRegions.pop_back();
317 if (ActiveRegions.empty())
318 startSegment(Line, Col);
319 else
320 startSegment(Line, Col, false, *ActiveRegions.back());
321 }
322
Igor Kudrinc0774e62016-04-14 09:10:00 +0000323 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
Justin Bogner3c0f1242015-01-24 20:58:52 +0000324 const CountedRegion *PrevRegion = nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000325 for (const auto &Region : Regions) {
326 // Pop any regions that end before this one starts.
327 while (!ActiveRegions.empty() &&
328 ActiveRegions.back()->endLoc() <= Region.startLoc())
329 popRegion();
Justin Bogner3c0f1242015-01-24 20:58:52 +0000330 if (PrevRegion && PrevRegion->startLoc() == Region.startLoc() &&
331 PrevRegion->endLoc() == Region.endLoc()) {
Justin Bogner11ae7782015-02-18 19:01:06 +0000332 if (Region.Kind == coverage::CounterMappingRegion::CodeRegion)
Justin Bognerb35a72a2014-09-25 00:34:18 +0000333 Segments.back().addCount(Region.ExecutionCount);
334 } else {
335 // Add this region to the stack.
336 ActiveRegions.push_back(&Region);
337 startSegment(Region);
338 }
Justin Bogner3c0f1242015-01-24 20:58:52 +0000339 PrevRegion = &Region;
Justin Bogner953e2402014-09-20 15:31:56 +0000340 }
341 // Pop any regions that are left in the stack.
342 while (!ActiveRegions.empty())
343 popRegion();
Igor Kudrinc0774e62016-04-14 09:10:00 +0000344 }
345
346public:
347 /// Build a list of CoverageSegments from a sorted list of Regions.
348 static std::vector<CoverageSegment>
349 buildSegments(ArrayRef<CountedRegion> Regions) {
350 std::vector<CoverageSegment> Segments;
351 SegmentBuilder Builder(Segments);
352 Builder.buildSegmentsImpl(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000353 return Segments;
354 }
355};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000356}
Justin Bogner953e2402014-09-20 15:31:56 +0000357
Justin Bognerd5fca922014-11-14 01:50:32 +0000358std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
Justin Bogner953e2402014-09-20 15:31:56 +0000359 std::vector<StringRef> Filenames;
360 for (const auto &Function : getCoveredFunctions())
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000361 Filenames.insert(Filenames.end(), Function.Filenames.begin(),
362 Function.Filenames.end());
Justin Bogner953e2402014-09-20 15:31:56 +0000363 std::sort(Filenames.begin(), Filenames.end());
364 auto Last = std::unique(Filenames.begin(), Filenames.end());
365 Filenames.erase(Last, Filenames.end());
366 return Filenames;
367}
368
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000369static SmallBitVector gatherFileIDs(StringRef SourceFile,
370 const FunctionRecord &Function) {
371 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
Justin Bogner953e2402014-09-20 15:31:56 +0000372 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
373 if (SourceFile == Function.Filenames[I])
374 FilenameEquivalence[I] = true;
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000375 return FilenameEquivalence;
376}
377
378static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
379 const FunctionRecord &Function) {
380 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
381 SmallBitVector FilenameEquivalence = gatherFileIDs(SourceFile, Function);
Justin Bogner953e2402014-09-20 15:31:56 +0000382 for (const auto &CR : Function.CountedRegions)
383 if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
384 FilenameEquivalence[CR.FileID])
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000385 IsNotExpandedFile[CR.ExpandedFileID] = false;
386 IsNotExpandedFile &= FilenameEquivalence;
387 int I = IsNotExpandedFile.find_first();
Justin Bognerc4f5a5e2015-02-20 07:28:28 +0000388 if (I == -1)
389 return None;
390 return I;
Justin Bogner953e2402014-09-20 15:31:56 +0000391}
392
393static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
Benjamin Kramer40957cc2015-02-12 16:30:00 +0000394 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
Justin Bogner953e2402014-09-20 15:31:56 +0000395 for (const auto &CR : Function.CountedRegions)
396 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
Benjamin Kramer40957cc2015-02-12 16:30:00 +0000397 IsNotExpandedFile[CR.ExpandedFileID] = false;
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000398 int I = IsNotExpandedFile.find_first();
Justin Bognerc4f5a5e2015-02-20 07:28:28 +0000399 if (I == -1)
400 return None;
401 return I;
Justin Bogner953e2402014-09-20 15:31:56 +0000402}
403
404/// Sort a nested sequence of regions from a single file.
405template <class It> static void sortNestedRegions(It First, It Last) {
406 std::sort(First, Last,
407 [](const CountedRegion &LHS, const CountedRegion &RHS) {
408 if (LHS.startLoc() == RHS.startLoc())
409 // When LHS completely contains RHS, we sort LHS first.
410 return RHS.endLoc() < LHS.endLoc();
411 return LHS.startLoc() < RHS.startLoc();
412 });
413}
414
415static bool isExpansion(const CountedRegion &R, unsigned FileID) {
416 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
417}
418
419CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
420 CoverageData FileCoverage(Filename);
421 std::vector<coverage::CountedRegion> Regions;
422
423 for (const auto &Function : Functions) {
424 auto MainFileID = findMainViewFileID(Filename, Function);
425 if (!MainFileID)
426 continue;
427 auto FileIDs = gatherFileIDs(Filename, Function);
428 for (const auto &CR : Function.CountedRegions)
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000429 if (FileIDs.test(CR.FileID)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000430 Regions.push_back(CR);
431 if (isExpansion(CR, *MainFileID))
432 FileCoverage.Expansions.emplace_back(CR, Function);
433 }
434 }
435
436 sortNestedRegions(Regions.begin(), Regions.end());
Justin Bogner3c0f1242015-01-24 20:58:52 +0000437 DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000438 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000439
440 return FileCoverage;
441}
442
443std::vector<const FunctionRecord *>
444CoverageMapping::getInstantiations(StringRef Filename) {
445 FunctionInstantiationSetCollector InstantiationSetCollector;
446 for (const auto &Function : Functions) {
447 auto MainFileID = findMainViewFileID(Filename, Function);
448 if (!MainFileID)
449 continue;
450 InstantiationSetCollector.insert(Function, *MainFileID);
451 }
452
453 std::vector<const FunctionRecord *> Result;
454 for (const auto &InstantiationSet : InstantiationSetCollector) {
455 if (InstantiationSet.second.size() < 2)
456 continue;
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000457 Result.insert(Result.end(), InstantiationSet.second.begin(),
458 InstantiationSet.second.end());
Justin Bogner953e2402014-09-20 15:31:56 +0000459 }
460 return Result;
461}
462
463CoverageData
464CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
465 auto MainFileID = findMainViewFileID(Function);
466 if (!MainFileID)
467 return CoverageData();
468
469 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
470 std::vector<coverage::CountedRegion> Regions;
471 for (const auto &CR : Function.CountedRegions)
472 if (CR.FileID == *MainFileID) {
473 Regions.push_back(CR);
474 if (isExpansion(CR, *MainFileID))
475 FunctionCoverage.Expansions.emplace_back(CR, Function);
476 }
477
478 sortNestedRegions(Regions.begin(), Regions.end());
Justin Bogner3c0f1242015-01-24 20:58:52 +0000479 DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000480 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000481
482 return FunctionCoverage;
483}
484
485CoverageData
486CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
487 CoverageData ExpansionCoverage(
488 Expansion.Function.Filenames[Expansion.FileID]);
489 std::vector<coverage::CountedRegion> Regions;
490 for (const auto &CR : Expansion.Function.CountedRegions)
491 if (CR.FileID == Expansion.FileID) {
492 Regions.push_back(CR);
493 if (isExpansion(CR, Expansion.FileID))
494 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
495 }
496
497 sortNestedRegions(Regions.begin(), Regions.end());
Justin Bogner3c0f1242015-01-24 20:58:52 +0000498 DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
499 << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000500 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000501
502 return ExpansionCoverage;
503}
Justin Bogner367a9f22015-05-06 23:19:35 +0000504
505namespace {
506class CoverageMappingErrorCategoryType : public std::error_category {
507 const char *name() const LLVM_NOEXCEPT override { return "llvm.coveragemap"; }
508 std::string message(int IE) const override {
509 auto E = static_cast<coveragemap_error>(IE);
510 switch (E) {
511 case coveragemap_error::success:
512 return "Success";
513 case coveragemap_error::eof:
514 return "End of File";
515 case coveragemap_error::no_data_found:
516 return "No coverage data found";
517 case coveragemap_error::unsupported_version:
518 return "Unsupported coverage format version";
519 case coveragemap_error::truncated:
520 return "Truncated coverage data";
521 case coveragemap_error::malformed:
522 return "Malformed coverage data";
523 }
524 llvm_unreachable("A value of coveragemap_error has no message.");
525 }
526};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000527}
Justin Bogner367a9f22015-05-06 23:19:35 +0000528
529static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
530
Xinliang David Li8a5bdb52016-01-10 21:56:33 +0000531const std::error_category &llvm::coverage::coveragemap_category() {
Justin Bogner367a9f22015-05-06 23:19:35 +0000532 return *ErrorCategory;
533}