blob: b2dde3406a63c320bd308ee097132911244b5938 [file] [log] [blame]
Eugene Zelenko72208a82017-06-21 23:19:47 +00001//===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
Alex Lorenza20a5d52014-07-24 23:57:54 +00002//
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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/ProfileData/Coverage/CoverageMapping.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000016#include "llvm/ADT/ArrayRef.h"
Justin Bogner953e2402014-09-20 15:31:56 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000018#include "llvm/ADT/None.h"
Justin Bogner953e2402014-09-20 15:31:56 +000019#include "llvm/ADT/Optional.h"
Benjamin Kramer71e1eb52015-02-12 16:18:07 +000020#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000023#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
Justin Bogner953e2402014-09-20 15:31:56 +000024#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb35a72a2014-09-25 00:34:18 +000025#include "llvm/Support/Debug.h"
Rafael Espindola74f29322015-06-13 17:23:04 +000026#include "llvm/Support/Errc.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000027#include "llvm/Support/Error.h"
Justin Bogner85b0a032014-09-08 21:04:00 +000028#include "llvm/Support/ErrorHandling.h"
Justin Bogner367a9f22015-05-06 23:19:35 +000029#include "llvm/Support/ManagedStatic.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000030#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000031#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000032#include <algorithm>
33#include <cassert>
34#include <cstdint>
35#include <iterator>
Vedant Kumar7bef6da2017-10-24 22:35:29 +000036#include <map>
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000037#include <memory>
38#include <string>
39#include <system_error>
40#include <utility>
41#include <vector>
Alex Lorenza20a5d52014-07-24 23:57:54 +000042
43using namespace llvm;
44using namespace coverage;
45
Justin Bognerb35a72a2014-09-25 00:34:18 +000046#define DEBUG_TYPE "coverage-mapping"
47
Alex Lorenza20a5d52014-07-24 23:57:54 +000048Counter CounterExpressionBuilder::get(const CounterExpression &E) {
Justin Bognerad69e642014-10-02 17:14:18 +000049 auto It = ExpressionIndices.find(E);
50 if (It != ExpressionIndices.end())
51 return Counter::getExpression(It->second);
52 unsigned I = Expressions.size();
Alex Lorenza20a5d52014-07-24 23:57:54 +000053 Expressions.push_back(E);
Justin Bognerad69e642014-10-02 17:14:18 +000054 ExpressionIndices[E] = I;
55 return Counter::getExpression(I);
Alex Lorenza20a5d52014-07-24 23:57:54 +000056}
57
Vedant Kumar71b3d722017-06-26 22:33:06 +000058void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
59 SmallVectorImpl<Term> &Terms) {
Alex Lorenza20a5d52014-07-24 23:57:54 +000060 switch (C.getKind()) {
61 case Counter::Zero:
62 break;
63 case Counter::CounterValueReference:
Vedant Kumar71b3d722017-06-26 22:33:06 +000064 Terms.emplace_back(C.getCounterID(), Factor);
Alex Lorenza20a5d52014-07-24 23:57:54 +000065 break;
66 case Counter::Expression:
67 const auto &E = Expressions[C.getExpressionID()];
Vedant Kumar71b3d722017-06-26 22:33:06 +000068 extractTerms(E.LHS, Factor, Terms);
69 extractTerms(
70 E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
Alex Lorenza20a5d52014-07-24 23:57:54 +000071 break;
72 }
73}
74
75Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
76 // Gather constant terms.
Vedant Kumar71b3d722017-06-26 22:33:06 +000077 SmallVector<Term, 32> Terms;
Justin Bognerf9535c42014-10-02 16:43:31 +000078 extractTerms(ExpressionTree, +1, Terms);
79
80 // If there are no terms, this is just a zero. The algorithm below assumes at
81 // least one term.
82 if (Terms.size() == 0)
83 return Counter::getZero();
84
85 // Group the terms by counter ID.
Fangrui Song0cac7262018-09-27 02:13:45 +000086 llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
Vedant Kumar71b3d722017-06-26 22:33:06 +000087 return LHS.CounterID < RHS.CounterID;
Justin Bognerf9535c42014-10-02 16:43:31 +000088 });
89
90 // Combine terms by counter ID to eliminate counters that sum to zero.
91 auto Prev = Terms.begin();
92 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
Vedant Kumar71b3d722017-06-26 22:33:06 +000093 if (I->CounterID == Prev->CounterID) {
94 Prev->Factor += I->Factor;
Justin Bognerf9535c42014-10-02 16:43:31 +000095 continue;
96 }
97 ++Prev;
98 *Prev = *I;
99 }
100 Terms.erase(++Prev, Terms.end());
Alex Lorenza20a5d52014-07-24 23:57:54 +0000101
102 Counter C;
Justin Bognerf9535c42014-10-02 16:43:31 +0000103 // Create additions. We do this before subtractions to avoid constructs like
104 // ((0 - X) + Y), as opposed to (Y - X).
Vedant Kumar71b3d722017-06-26 22:33:06 +0000105 for (auto T : Terms) {
106 if (T.Factor <= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000107 continue;
Vedant Kumar71b3d722017-06-26 22:33:06 +0000108 for (int I = 0; I < T.Factor; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000109 if (C.isZero())
Vedant Kumar71b3d722017-06-26 22:33:06 +0000110 C = Counter::getCounter(T.CounterID);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000111 else
112 C = get(CounterExpression(CounterExpression::Add, C,
Vedant Kumar71b3d722017-06-26 22:33:06 +0000113 Counter::getCounter(T.CounterID)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000114 }
115
116 // Create subtractions.
Vedant Kumar71b3d722017-06-26 22:33:06 +0000117 for (auto T : Terms) {
118 if (T.Factor >= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000119 continue;
Vedant Kumar71b3d722017-06-26 22:33:06 +0000120 for (int I = 0; I < -T.Factor; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000121 C = get(CounterExpression(CounterExpression::Subtract, C,
Vedant Kumar71b3d722017-06-26 22:33:06 +0000122 Counter::getCounter(T.CounterID)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000123 }
124 return C;
125}
126
127Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
128 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
129}
130
131Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
132 return simplify(
133 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
134}
135
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000136void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000137 switch (C.getKind()) {
138 case Counter::Zero:
139 OS << '0';
140 return;
141 case Counter::CounterValueReference:
142 OS << '#' << C.getCounterID();
143 break;
144 case Counter::Expression: {
145 if (C.getExpressionID() >= Expressions.size())
146 return;
147 const auto &E = Expressions[C.getExpressionID()];
148 OS << '(';
Alex Lorenza422911c2014-07-29 19:58:16 +0000149 dump(E.LHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000150 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
Alex Lorenza422911c2014-07-29 19:58:16 +0000151 dump(E.RHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000152 OS << ')';
153 break;
154 }
155 }
156 if (CounterValues.empty())
157 return;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000158 Expected<int64_t> Value = evaluate(C);
159 if (auto E = Value.takeError()) {
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000160 consumeError(std::move(E));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000161 return;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000162 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000163 OS << '[' << *Value << ']';
Alex Lorenza20a5d52014-07-24 23:57:54 +0000164}
165
Vedant Kumar9152fd12016-05-19 03:54:45 +0000166Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000167 switch (C.getKind()) {
168 case Counter::Zero:
169 return 0;
170 case Counter::CounterValueReference:
Justin Bogner85b0a032014-09-08 21:04:00 +0000171 if (C.getCounterID() >= CounterValues.size())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000172 return errorCodeToError(errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000173 return CounterValues[C.getCounterID()];
174 case Counter::Expression: {
Justin Bogner85b0a032014-09-08 21:04:00 +0000175 if (C.getExpressionID() >= Expressions.size())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000176 return errorCodeToError(errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000177 const auto &E = Expressions[C.getExpressionID()];
Vedant Kumar9152fd12016-05-19 03:54:45 +0000178 Expected<int64_t> LHS = evaluate(E.LHS);
Justin Bogner85b0a032014-09-08 21:04:00 +0000179 if (!LHS)
180 return LHS;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000181 Expected<int64_t> RHS = evaluate(E.RHS);
Justin Bogner85b0a032014-09-08 21:04:00 +0000182 if (!RHS)
183 return RHS;
184 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000185 }
186 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000187 llvm_unreachable("Unhandled CounterKind");
Alex Lorenza20a5d52014-07-24 23:57:54 +0000188}
Justin Bogner953e2402014-09-20 15:31:56 +0000189
Justin Bognerd5fca922014-11-14 01:50:32 +0000190void FunctionRecordIterator::skipOtherFiles() {
191 while (Current != Records.end() && !Filename.empty() &&
192 Filename != Current->Filenames[0])
193 ++Current;
194 if (Current == Records.end())
195 *this = FunctionRecordIterator();
196}
197
Vedant Kumar68216d72016-10-12 22:27:45 +0000198Error CoverageMapping::loadFunctionRecord(
199 const CoverageMappingRecord &Record,
200 IndexedInstrProfReader &ProfileReader) {
Vedant Kumar743574b2016-10-14 17:16:53 +0000201 StringRef OrigFuncName = Record.FunctionName;
Vedant Kumarb1d331a2017-06-20 02:05:35 +0000202 if (OrigFuncName.empty())
203 return make_error<CoverageMapError>(coveragemap_error::malformed);
204
Vedant Kumar743574b2016-10-14 17:16:53 +0000205 if (Record.Filenames.empty())
206 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
207 else
208 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
209
Vedant Kumar68216d72016-10-12 22:27:45 +0000210 CounterMappingContext Ctx(Record.Expressions);
211
212 std::vector<uint64_t> Counts;
213 if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
214 Record.FunctionHash, Counts)) {
215 instrprof_error IPE = InstrProfError::take(std::move(E));
216 if (IPE == instrprof_error::hash_mismatch) {
Vedant Kumar18dd9e82017-09-21 01:11:30 +0000217 FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash);
Vedant Kumar68216d72016-10-12 22:27:45 +0000218 return Error::success();
219 } else if (IPE != instrprof_error::unknown_function)
220 return make_error<InstrProfError>(IPE);
221 Counts.assign(Record.MappingRegions.size(), 0);
222 }
223 Ctx.setCounts(Counts);
224
225 assert(!Record.MappingRegions.empty() && "Function has no regions");
226
Vedant Kumar381e9d22018-08-07 22:25:36 +0000227 // This coverage record is a zero region for a function that's unused in
228 // some TU, but used in a different TU. Ignore it. The coverage maps from the
229 // the other TU will either be loaded (providing full region counts) or they
230 // won't (in which case we don't unintuitively report functions as uncovered
231 // when they have non-zero counts in the profile).
232 if (Record.MappingRegions.size() == 1 &&
233 Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
234 return Error::success();
235
Vedant Kumar68216d72016-10-12 22:27:45 +0000236 FunctionRecord Function(OrigFuncName, Record.Filenames);
237 for (const auto &Region : Record.MappingRegions) {
238 Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
239 if (auto E = ExecutionCount.takeError()) {
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000240 consumeError(std::move(E));
Vedant Kumar68216d72016-10-12 22:27:45 +0000241 return Error::success();
242 }
243 Function.pushRegion(Region, *ExecutionCount);
244 }
Vedant Kumar68216d72016-10-12 22:27:45 +0000245
Vedant Kumar381e9d22018-08-07 22:25:36 +0000246 // Don't create records for (filenames, function) pairs we've already seen.
247 auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
248 Record.Filenames.end());
249 if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
250 return Error::success();
251
Vedant Kumar68216d72016-10-12 22:27:45 +0000252 Functions.push_back(std::move(Function));
253 return Error::success();
254}
255
Vedant Kumar743574b2016-10-14 17:16:53 +0000256Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
257 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
258 IndexedInstrProfReader &ProfileReader) {
259 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
260
Vedant Kumarbae83972017-09-08 18:44:47 +0000261 for (const auto &CoverageReader : CoverageReaders) {
262 for (auto RecordOrErr : *CoverageReader) {
263 if (Error E = RecordOrErr.takeError())
264 return std::move(E);
265 const auto &Record = *RecordOrErr;
Vedant Kumar743574b2016-10-14 17:16:53 +0000266 if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
267 return std::move(E);
Vedant Kumarbae83972017-09-08 18:44:47 +0000268 }
269 }
Vedant Kumar743574b2016-10-14 17:16:53 +0000270
271 return std::move(Coverage);
272}
273
Vedant Kumar9152fd12016-05-19 03:54:45 +0000274Expected<std::unique_ptr<CoverageMapping>>
Vedant Kumar743574b2016-10-14 17:16:53 +0000275CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
Vedant Kumar4b102c32017-08-01 21:23:26 +0000276 StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
Justin Bognerab89ed72015-02-16 21:28:58 +0000277 auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000278 if (Error E = ProfileReaderOrErr.takeError())
279 return std::move(E);
Justin Bognerab89ed72015-02-16 21:28:58 +0000280 auto ProfileReader = std::move(ProfileReaderOrErr.get());
Vedant Kumar743574b2016-10-14 17:16:53 +0000281
282 SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
283 SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
Vedant Kumar4b102c32017-08-01 21:23:26 +0000284 for (const auto &File : llvm::enumerate(ObjectFilenames)) {
285 auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
Vedant Kumar743574b2016-10-14 17:16:53 +0000286 if (std::error_code EC = CovMappingBufOrErr.getError())
287 return errorCodeToError(EC);
Vedant Kumar4b102c32017-08-01 21:23:26 +0000288 StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
Vedant Kumar743574b2016-10-14 17:16:53 +0000289 auto CoverageReaderOrErr =
290 BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
291 if (Error E = CoverageReaderOrErr.takeError())
292 return std::move(E);
293 Readers.push_back(std::move(CoverageReaderOrErr.get()));
294 Buffers.push_back(std::move(CovMappingBufOrErr.get()));
295 }
296 return load(Readers, *ProfileReader);
Justin Bogner19a93ba2014-09-20 17:19:52 +0000297}
298
Justin Bogner953e2402014-09-20 15:31:56 +0000299namespace {
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000300
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000301/// Distributes functions into instantiation sets.
Justin Bogner953e2402014-09-20 15:31:56 +0000302///
303/// An instantiation set is a collection of functions that have the same source
304/// code, ie, template functions specializations.
305class FunctionInstantiationSetCollector {
Vedant Kumar7bef6da2017-10-24 22:35:29 +0000306 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
Justin Bogner953e2402014-09-20 15:31:56 +0000307 MapT InstantiatedFunctions;
308
309public:
310 void insert(const FunctionRecord &Function, unsigned FileID) {
311 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
312 while (I != E && I->FileID != FileID)
313 ++I;
314 assert(I != E && "function does not cover the given file");
315 auto &Functions = InstantiatedFunctions[I->startLoc()];
316 Functions.push_back(&Function);
317 }
318
319 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
Justin Bogner953e2402014-09-20 15:31:56 +0000320 MapT::iterator end() { return InstantiatedFunctions.end(); }
321};
322
323class SegmentBuilder {
Igor Kudrinc0774e62016-04-14 09:10:00 +0000324 std::vector<CoverageSegment> &Segments;
Justin Bogner953e2402014-09-20 15:31:56 +0000325 SmallVector<const CountedRegion *, 8> ActiveRegions;
326
Igor Kudrinc0774e62016-04-14 09:10:00 +0000327 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
328
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000329 /// Emit a segment with the count from \p Region starting at \p StartLoc.
330 //
Vedant Kumarad8f6372017-09-18 23:37:28 +0000331 /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000332 /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
333 void startSegment(const CountedRegion &Region, LineColPair StartLoc,
334 bool IsRegionEntry, bool EmitSkippedRegion = false) {
335 bool HasCount = !EmitSkippedRegion &&
336 (Region.Kind != CounterMappingRegion::SkippedRegion);
Justin Bogner953e2402014-09-20 15:31:56 +0000337
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000338 // If the new segment wouldn't affect coverage rendering, skip it.
339 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
340 const auto &Last = Segments.back();
341 if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
342 !Last.IsRegionEntry)
343 return;
344 }
Justin Bogner953e2402014-09-20 15:31:56 +0000345
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000346 if (HasCount)
347 Segments.emplace_back(StartLoc.first, StartLoc.second,
Vedant Kumarad8f6372017-09-18 23:37:28 +0000348 Region.ExecutionCount, IsRegionEntry,
349 Region.Kind == CounterMappingRegion::GapRegion);
Justin Bogner953e2402014-09-20 15:31:56 +0000350 else
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000351 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
352
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000353 LLVM_DEBUG({
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000354 const auto &Last = Segments.back();
355 dbgs() << "Segment at " << Last.Line << ":" << Last.Col
356 << " (count = " << Last.Count << ")"
357 << (Last.IsRegionEntry ? ", RegionEntry" : "")
Vedant Kumarad8f6372017-09-18 23:37:28 +0000358 << (!Last.HasCount ? ", Skipped" : "")
359 << (Last.IsGapRegion ? ", Gap" : "") << "\n";
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000360 });
361 }
362
363 /// Emit segments for active regions which end before \p Loc.
364 ///
365 /// \p Loc: The start location of the next region. If None, all active
366 /// regions are completed.
367 /// \p FirstCompletedRegion: Index of the first completed region.
368 void completeRegionsUntil(Optional<LineColPair> Loc,
369 unsigned FirstCompletedRegion) {
370 // Sort the completed regions by end location. This makes it simple to
371 // emit closing segments in sorted order.
372 auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
373 std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
374 [](const CountedRegion *L, const CountedRegion *R) {
375 return L->endLoc() < R->endLoc();
376 });
377
378 // Emit segments for all completed regions.
379 for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
380 ++I) {
381 const auto *CompletedRegion = ActiveRegions[I];
382 assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
383 "Completed region ends after start of new region");
384
385 const auto *PrevCompletedRegion = ActiveRegions[I - 1];
386 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
387
388 // Don't emit any more segments if they start where the new region begins.
389 if (Loc && CompletedSegmentLoc == *Loc)
390 break;
391
392 // Don't emit a segment if the next completed region ends at the same
393 // location as this one.
394 if (CompletedSegmentLoc == CompletedRegion->endLoc())
395 continue;
396
Vedant Kumar337b0db2017-12-07 00:01:15 +0000397 // Use the count from the last completed region which ends at this loc.
398 for (unsigned J = I + 1; J < E; ++J)
399 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
400 CompletedRegion = ActiveRegions[J];
Vedant Kumar80fbb852017-11-30 00:28:23 +0000401
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000402 startSegment(*CompletedRegion, CompletedSegmentLoc, false);
403 }
404
405 auto Last = ActiveRegions.back();
406 if (FirstCompletedRegion && Last->endLoc() != *Loc) {
407 // If there's a gap after the end of the last completed region and the
408 // start of the new region, use the last active region to fill the gap.
409 startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
410 false);
411 } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
412 // Emit a skipped segment if there are no more active regions. This
413 // ensures that gaps between functions are marked correctly.
414 startSegment(*Last, Last->endLoc(), false, true);
415 }
416
417 // Pop the completed regions.
418 ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
Justin Bogner953e2402014-09-20 15:31:56 +0000419 }
420
Igor Kudrinc0774e62016-04-14 09:10:00 +0000421 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000422 for (const auto &CR : enumerate(Regions)) {
423 auto CurStartLoc = CR.value().startLoc();
424
425 // Active regions which end before the current region need to be popped.
426 auto CompletedRegions =
427 std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
428 [&](const CountedRegion *Region) {
429 return !(Region->endLoc() <= CurStartLoc);
430 });
431 if (CompletedRegions != ActiveRegions.end()) {
432 unsigned FirstCompletedRegion =
433 std::distance(ActiveRegions.begin(), CompletedRegions);
434 completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
435 }
436
Vedant Kumarad8f6372017-09-18 23:37:28 +0000437 bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
438
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000439 // Try to emit a segment for the current region.
440 if (CurStartLoc == CR.value().endLoc()) {
441 // Avoid making zero-length regions active. If it's the last region,
442 // emit a skipped segment. Otherwise use its predecessor's count.
443 const bool Skipped = (CR.index() + 1) == Regions.size();
444 startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
Vedant Kumarad8f6372017-09-18 23:37:28 +0000445 CurStartLoc, !GapRegion, Skipped);
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000446 continue;
447 }
448 if (CR.index() + 1 == Regions.size() ||
449 CurStartLoc != Regions[CR.index() + 1].startLoc()) {
450 // Emit a segment if the next region doesn't start at the same location
451 // as this one.
Vedant Kumarad8f6372017-09-18 23:37:28 +0000452 startSegment(CR.value(), CurStartLoc, !GapRegion);
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000453 }
454
455 // This region is active (i.e not completed).
456 ActiveRegions.push_back(&CR.value());
Justin Bogner953e2402014-09-20 15:31:56 +0000457 }
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000458
459 // Complete any remaining active regions.
460 if (!ActiveRegions.empty())
461 completeRegionsUntil(None, 0);
Igor Kudrinc0774e62016-04-14 09:10:00 +0000462 }
463
Igor Kudrined99a962016-04-25 09:43:37 +0000464 /// Sort a nested sequence of regions from a single file.
465 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
Fangrui Song0cac7262018-09-27 02:13:45 +0000466 llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
Igor Kudrin27d8dd32016-05-05 09:39:45 +0000467 if (LHS.startLoc() != RHS.startLoc())
468 return LHS.startLoc() < RHS.startLoc();
469 if (LHS.endLoc() != RHS.endLoc())
470 // When LHS completely contains RHS, we sort LHS first.
471 return RHS.endLoc() < LHS.endLoc();
472 // If LHS and RHS cover the same area, we need to sort them according
473 // to their kinds so that the most suitable region will become "active"
474 // in combineRegions(). Because we accumulate counter values only from
475 // regions of the same kind as the first region of the area, prefer
476 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000477 static_assert(CounterMappingRegion::CodeRegion <
478 CounterMappingRegion::ExpansionRegion &&
479 CounterMappingRegion::ExpansionRegion <
480 CounterMappingRegion::SkippedRegion,
Igor Kudrin27d8dd32016-05-05 09:39:45 +0000481 "Unexpected order of region kind values");
482 return LHS.Kind < RHS.Kind;
483 });
Igor Kudrined99a962016-04-25 09:43:37 +0000484 }
485
486 /// Combine counts of regions which cover the same area.
487 static ArrayRef<CountedRegion>
488 combineRegions(MutableArrayRef<CountedRegion> Regions) {
489 if (Regions.empty())
490 return Regions;
491 auto Active = Regions.begin();
492 auto End = Regions.end();
493 for (auto I = Regions.begin() + 1; I != End; ++I) {
494 if (Active->startLoc() != I->startLoc() ||
495 Active->endLoc() != I->endLoc()) {
496 // Shift to the next region.
497 ++Active;
498 if (Active != I)
499 *Active = *I;
500 continue;
501 }
502 // Merge duplicate region.
Igor Kudrin27d8dd32016-05-05 09:39:45 +0000503 // If CodeRegions and ExpansionRegions cover the same area, it's probably
504 // a macro which is fully expanded to another macro. In that case, we need
505 // to accumulate counts only from CodeRegions, or else the area will be
506 // counted twice.
507 // On the other hand, a macro may have a nested macro in its body. If the
508 // outer macro is used several times, the ExpansionRegion for the nested
509 // macro will also be added several times. These ExpansionRegions cover
510 // the same source locations and have to be combined to reach the correct
511 // value for that area.
512 // We add counts of the regions of the same kind as the active region
513 // to handle the both situations.
514 if (I->Kind == Active->Kind)
Igor Kudrined99a962016-04-25 09:43:37 +0000515 Active->ExecutionCount += I->ExecutionCount;
516 }
517 return Regions.drop_back(std::distance(++Active, End));
518 }
519
Igor Kudrinc0774e62016-04-14 09:10:00 +0000520public:
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000521 /// Build a sorted list of CoverageSegments from a list of Regions.
Igor Kudrinc0774e62016-04-14 09:10:00 +0000522 static std::vector<CoverageSegment>
Igor Kudrined99a962016-04-25 09:43:37 +0000523 buildSegments(MutableArrayRef<CountedRegion> Regions) {
Igor Kudrinc0774e62016-04-14 09:10:00 +0000524 std::vector<CoverageSegment> Segments;
525 SegmentBuilder Builder(Segments);
Igor Kudrined99a962016-04-25 09:43:37 +0000526
527 sortNestedRegions(Regions);
528 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
529
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000530 LLVM_DEBUG({
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000531 dbgs() << "Combined regions:\n";
532 for (const auto &CR : CombinedRegions)
533 dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
534 << CR.LineEnd << ":" << CR.ColumnEnd
535 << " (count=" << CR.ExecutionCount << ")\n";
536 });
537
Igor Kudrined99a962016-04-25 09:43:37 +0000538 Builder.buildSegmentsImpl(CombinedRegions);
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000539
540#ifndef NDEBUG
541 for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
542 const auto &L = Segments[I - 1];
543 const auto &R = Segments[I];
544 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000545 LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
546 << " followed by " << R.Line << ":" << R.Col << "\n");
Vedant Kumar79a1b5e2017-09-08 18:44:50 +0000547 assert(false && "Coverage segments not unique or sorted");
548 }
549 }
550#endif
551
Justin Bogner953e2402014-09-20 15:31:56 +0000552 return Segments;
553 }
554};
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000555
556} // end anonymous namespace
Justin Bogner953e2402014-09-20 15:31:56 +0000557
Justin Bognerd5fca922014-11-14 01:50:32 +0000558std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
Justin Bogner953e2402014-09-20 15:31:56 +0000559 std::vector<StringRef> Filenames;
560 for (const auto &Function : getCoveredFunctions())
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000561 Filenames.insert(Filenames.end(), Function.Filenames.begin(),
562 Function.Filenames.end());
Fangrui Song0cac7262018-09-27 02:13:45 +0000563 llvm::sort(Filenames);
Justin Bogner953e2402014-09-20 15:31:56 +0000564 auto Last = std::unique(Filenames.begin(), Filenames.end());
565 Filenames.erase(Last, Filenames.end());
566 return Filenames;
567}
568
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000569static SmallBitVector gatherFileIDs(StringRef SourceFile,
570 const FunctionRecord &Function) {
571 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
Justin Bogner953e2402014-09-20 15:31:56 +0000572 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
573 if (SourceFile == Function.Filenames[I])
574 FilenameEquivalence[I] = true;
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000575 return FilenameEquivalence;
576}
577
Igor Kudrin1c14dc42016-04-18 15:36:30 +0000578/// Return the ID of the file where the definition of the function is located.
Justin Bogner953e2402014-09-20 15:31:56 +0000579static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
Benjamin Kramer40957cc2015-02-12 16:30:00 +0000580 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
Justin Bogner953e2402014-09-20 15:31:56 +0000581 for (const auto &CR : Function.CountedRegions)
582 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
Benjamin Kramer40957cc2015-02-12 16:30:00 +0000583 IsNotExpandedFile[CR.ExpandedFileID] = false;
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000584 int I = IsNotExpandedFile.find_first();
Justin Bognerc4f5a5e2015-02-20 07:28:28 +0000585 if (I == -1)
586 return None;
587 return I;
Justin Bogner953e2402014-09-20 15:31:56 +0000588}
589
Igor Kudrin1c14dc42016-04-18 15:36:30 +0000590/// Check if SourceFile is the file that contains the definition of
591/// the Function. Return the ID of the file in that case or None otherwise.
592static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
593 const FunctionRecord &Function) {
594 Optional<unsigned> I = findMainViewFileID(Function);
595 if (I && SourceFile == Function.Filenames[*I])
596 return I;
597 return None;
598}
599
Justin Bogner953e2402014-09-20 15:31:56 +0000600static bool isExpansion(const CountedRegion &R, unsigned FileID) {
601 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
602}
603
Vedant Kumar7fcc5472016-07-13 23:12:23 +0000604CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
Justin Bogner953e2402014-09-20 15:31:56 +0000605 CoverageData FileCoverage(Filename);
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000606 std::vector<CountedRegion> Regions;
Justin Bogner953e2402014-09-20 15:31:56 +0000607
608 for (const auto &Function : Functions) {
609 auto MainFileID = findMainViewFileID(Filename, Function);
Justin Bogner953e2402014-09-20 15:31:56 +0000610 auto FileIDs = gatherFileIDs(Filename, Function);
611 for (const auto &CR : Function.CountedRegions)
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000612 if (FileIDs.test(CR.FileID)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000613 Regions.push_back(CR);
Igor Kudrin1c14dc42016-04-18 15:36:30 +0000614 if (MainFileID && isExpansion(CR, *MainFileID))
Justin Bogner953e2402014-09-20 15:31:56 +0000615 FileCoverage.Expansions.emplace_back(CR, Function);
616 }
617 }
618
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000619 LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000620 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000621
622 return FileCoverage;
623}
624
Vedant Kumardde19c52017-08-02 23:35:25 +0000625std::vector<InstantiationGroup>
626CoverageMapping::getInstantiationGroups(StringRef Filename) const {
Justin Bogner953e2402014-09-20 15:31:56 +0000627 FunctionInstantiationSetCollector InstantiationSetCollector;
628 for (const auto &Function : Functions) {
629 auto MainFileID = findMainViewFileID(Filename, Function);
630 if (!MainFileID)
631 continue;
632 InstantiationSetCollector.insert(Function, *MainFileID);
633 }
634
Vedant Kumardde19c52017-08-02 23:35:25 +0000635 std::vector<InstantiationGroup> Result;
Benjamin Kramer24cb28b2017-12-28 18:10:41 +0000636 for (auto &InstantiationSet : InstantiationSetCollector) {
Vedant Kumardde19c52017-08-02 23:35:25 +0000637 InstantiationGroup IG{InstantiationSet.first.first,
638 InstantiationSet.first.second,
639 std::move(InstantiationSet.second)};
640 Result.emplace_back(std::move(IG));
Justin Bogner953e2402014-09-20 15:31:56 +0000641 }
642 return Result;
643}
644
645CoverageData
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000646CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
Justin Bogner953e2402014-09-20 15:31:56 +0000647 auto MainFileID = findMainViewFileID(Function);
648 if (!MainFileID)
649 return CoverageData();
650
651 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000652 std::vector<CountedRegion> Regions;
Justin Bogner953e2402014-09-20 15:31:56 +0000653 for (const auto &CR : Function.CountedRegions)
654 if (CR.FileID == *MainFileID) {
655 Regions.push_back(CR);
656 if (isExpansion(CR, *MainFileID))
657 FunctionCoverage.Expansions.emplace_back(CR, Function);
658 }
659
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000660 LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
661 << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000662 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000663
664 return FunctionCoverage;
665}
666
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000667CoverageData CoverageMapping::getCoverageForExpansion(
668 const ExpansionRecord &Expansion) const {
Justin Bogner953e2402014-09-20 15:31:56 +0000669 CoverageData ExpansionCoverage(
670 Expansion.Function.Filenames[Expansion.FileID]);
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000671 std::vector<CountedRegion> Regions;
Justin Bogner953e2402014-09-20 15:31:56 +0000672 for (const auto &CR : Expansion.Function.CountedRegions)
673 if (CR.FileID == Expansion.FileID) {
674 Regions.push_back(CR);
675 if (isExpansion(CR, Expansion.FileID))
676 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
677 }
678
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000679 LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
680 << Expansion.FileID << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000681 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000682
683 return ExpansionCoverage;
684}
Justin Bogner367a9f22015-05-06 23:19:35 +0000685
Vedant Kumar821160d2017-10-18 23:58:28 +0000686LineCoverageStats::LineCoverageStats(
Vedant Kumarf5f153d2017-10-19 06:16:23 +0000687 ArrayRef<const CoverageSegment *> LineSegments,
688 const CoverageSegment *WrappedSegment, unsigned Line)
Vedant Kumar821160d2017-10-18 23:58:28 +0000689 : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
690 LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
691 // Find the minimum number of regions which start in this line.
692 unsigned MinRegionCount = 0;
Vedant Kumarf5f153d2017-10-19 06:16:23 +0000693 auto isStartOfRegion = [](const CoverageSegment *S) {
Vedant Kumar821160d2017-10-18 23:58:28 +0000694 return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
695 };
696 for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
697 if (isStartOfRegion(LineSegments[I]))
698 ++MinRegionCount;
699
700 bool StartOfSkippedRegion = !LineSegments.empty() &&
701 !LineSegments.front()->HasCount &&
702 LineSegments.front()->IsRegionEntry;
703
704 HasMultipleRegions = MinRegionCount > 1;
705 Mapped =
706 !StartOfSkippedRegion &&
707 ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
708
709 if (!Mapped)
710 return;
711
Vedant Kumar43247f02017-11-09 02:33:43 +0000712 // Pick the max count from the non-gap, region entry segments and the
713 // wrapped count.
714 if (WrappedSegment)
Vedant Kumar821160d2017-10-18 23:58:28 +0000715 ExecutionCount = WrappedSegment->Count;
Vedant Kumar43247f02017-11-09 02:33:43 +0000716 if (!MinRegionCount)
Vedant Kumar821160d2017-10-18 23:58:28 +0000717 return;
Vedant Kumar821160d2017-10-18 23:58:28 +0000718 for (const auto *LS : LineSegments)
719 if (isStartOfRegion(LS))
720 ExecutionCount = std::max(ExecutionCount, LS->Count);
721}
722
723LineCoverageIterator &LineCoverageIterator::operator++() {
724 if (Next == CD.end()) {
725 Stats = LineCoverageStats();
726 Ended = true;
727 return *this;
728 }
729 if (Segments.size())
730 WrappedSegment = Segments.back();
731 Segments.clear();
732 while (Next != CD.end() && Next->Line == Line)
733 Segments.push_back(&*Next++);
734 Stats = LineCoverageStats(Segments, WrappedSegment, Line);
735 ++Line;
736 return *this;
737}
738
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000739static std::string getCoverageMapErrString(coveragemap_error Err) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000740 switch (Err) {
741 case coveragemap_error::success:
742 return "Success";
743 case coveragemap_error::eof:
744 return "End of File";
745 case coveragemap_error::no_data_found:
746 return "No coverage data found";
747 case coveragemap_error::unsupported_version:
748 return "Unsupported coverage format version";
749 case coveragemap_error::truncated:
750 return "Truncated coverage data";
751 case coveragemap_error::malformed:
752 return "Malformed coverage data";
753 }
754 llvm_unreachable("A value of coveragemap_error has no message.");
755}
756
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000757namespace {
758
Peter Collingbourne4718f8b2016-05-24 20:13:46 +0000759// FIXME: This class is only here to support the transition to llvm::Error. It
760// will be removed once this transition is complete. Clients should prefer to
761// deal with the Error value directly, rather than converting to error_code.
Justin Bogner367a9f22015-05-06 23:19:35 +0000762class CoverageMappingErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +0000763 const char *name() const noexcept override { return "llvm.coveragemap"; }
Justin Bogner367a9f22015-05-06 23:19:35 +0000764 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000765 return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
Justin Bogner367a9f22015-05-06 23:19:35 +0000766 }
767};
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000768
Vedant Kumar9152fd12016-05-19 03:54:45 +0000769} // end anonymous namespace
770
771std::string CoverageMapError::message() const {
772 return getCoverageMapErrString(Err);
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000773}
Justin Bogner367a9f22015-05-06 23:19:35 +0000774
775static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
776
Xinliang David Li8a5bdb52016-01-10 21:56:33 +0000777const std::error_category &llvm::coverage::coveragemap_category() {
Justin Bogner367a9f22015-05-06 23:19:35 +0000778 return *ErrorCategory;
779}
Vedant Kumar9152fd12016-05-19 03:54:45 +0000780
781char CoverageMapError::ID = 0;