blob: 0ccebc2b97ec5f57188b4581a3eac8f925fad523 [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
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ProfileData/CoverageMappingReader.h"
21#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb35a72a2014-09-25 00:34:18 +000022#include "llvm/Support/Debug.h"
Justin Bogner85b0a032014-09-08 21:04:00 +000023#include "llvm/Support/ErrorHandling.h"
Alex Lorenza20a5d52014-07-24 23:57:54 +000024
25using namespace llvm;
26using namespace coverage;
27
Justin Bognerb35a72a2014-09-25 00:34:18 +000028#define DEBUG_TYPE "coverage-mapping"
29
Alex Lorenza20a5d52014-07-24 23:57:54 +000030Counter CounterExpressionBuilder::get(const CounterExpression &E) {
Justin Bognerad69e642014-10-02 17:14:18 +000031 auto It = ExpressionIndices.find(E);
32 if (It != ExpressionIndices.end())
33 return Counter::getExpression(It->second);
34 unsigned I = Expressions.size();
Alex Lorenza20a5d52014-07-24 23:57:54 +000035 Expressions.push_back(E);
Justin Bognerad69e642014-10-02 17:14:18 +000036 ExpressionIndices[E] = I;
37 return Counter::getExpression(I);
Alex Lorenza20a5d52014-07-24 23:57:54 +000038}
39
Justin Bognerf9535c42014-10-02 16:43:31 +000040void CounterExpressionBuilder::extractTerms(
41 Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
Alex Lorenza20a5d52014-07-24 23:57:54 +000042 switch (C.getKind()) {
43 case Counter::Zero:
44 break;
45 case Counter::CounterValueReference:
Justin Bognerf9535c42014-10-02 16:43:31 +000046 Terms.push_back(std::make_pair(C.getCounterID(), Sign));
Alex Lorenza20a5d52014-07-24 23:57:54 +000047 break;
48 case Counter::Expression:
49 const auto &E = Expressions[C.getExpressionID()];
Justin Bognerf9535c42014-10-02 16:43:31 +000050 extractTerms(E.LHS, Sign, Terms);
51 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
52 Terms);
Alex Lorenza20a5d52014-07-24 23:57:54 +000053 break;
54 }
55}
56
57Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
58 // Gather constant terms.
Justin Bognerf9535c42014-10-02 16:43:31 +000059 llvm::SmallVector<std::pair<unsigned, int>, 32> Terms;
60 extractTerms(ExpressionTree, +1, Terms);
61
62 // If there are no terms, this is just a zero. The algorithm below assumes at
63 // least one term.
64 if (Terms.size() == 0)
65 return Counter::getZero();
66
67 // Group the terms by counter ID.
68 std::sort(Terms.begin(), Terms.end(),
69 [](const std::pair<unsigned, int> &LHS,
70 const std::pair<unsigned, int> &RHS) {
71 return LHS.first < RHS.first;
72 });
73
74 // Combine terms by counter ID to eliminate counters that sum to zero.
75 auto Prev = Terms.begin();
76 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
77 if (I->first == Prev->first) {
78 Prev->second += I->second;
79 continue;
80 }
81 ++Prev;
82 *Prev = *I;
83 }
84 Terms.erase(++Prev, Terms.end());
Alex Lorenza20a5d52014-07-24 23:57:54 +000085
86 Counter C;
Justin Bognerf9535c42014-10-02 16:43:31 +000087 // Create additions. We do this before subtractions to avoid constructs like
88 // ((0 - X) + Y), as opposed to (Y - X).
89 for (auto Term : Terms) {
90 if (Term.second <= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +000091 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +000092 for (int I = 0; I < Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +000093 if (C.isZero())
Justin Bognerf9535c42014-10-02 16:43:31 +000094 C = Counter::getCounter(Term.first);
Alex Lorenza20a5d52014-07-24 23:57:54 +000095 else
96 C = get(CounterExpression(CounterExpression::Add, C,
Justin Bognerf9535c42014-10-02 16:43:31 +000097 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +000098 }
99
100 // Create subtractions.
Justin Bognerf9535c42014-10-02 16:43:31 +0000101 for (auto Term : Terms) {
102 if (Term.second >= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000103 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +0000104 for (int I = 0; I < -Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000105 C = get(CounterExpression(CounterExpression::Subtract, C,
Justin Bognerf9535c42014-10-02 16:43:31 +0000106 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000107 }
108 return C;
109}
110
111Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
112 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
113}
114
115Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
116 return simplify(
117 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
118}
119
120void CounterMappingContext::dump(const Counter &C,
121 llvm::raw_ostream &OS) const {
122 switch (C.getKind()) {
123 case Counter::Zero:
124 OS << '0';
125 return;
126 case Counter::CounterValueReference:
127 OS << '#' << C.getCounterID();
128 break;
129 case Counter::Expression: {
130 if (C.getExpressionID() >= Expressions.size())
131 return;
132 const auto &E = Expressions[C.getExpressionID()];
133 OS << '(';
Alex Lorenza422911c2014-07-29 19:58:16 +0000134 dump(E.LHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000135 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
Alex Lorenza422911c2014-07-29 19:58:16 +0000136 dump(E.RHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000137 OS << ')';
138 break;
139 }
140 }
141 if (CounterValues.empty())
142 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000143 ErrorOr<int64_t> Value = evaluate(C);
144 if (!Value)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000145 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000146 OS << '[' << *Value << ']';
Alex Lorenza20a5d52014-07-24 23:57:54 +0000147}
148
Justin Bogner85b0a032014-09-08 21:04:00 +0000149ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000150 switch (C.getKind()) {
151 case Counter::Zero:
152 return 0;
153 case Counter::CounterValueReference:
Justin Bogner85b0a032014-09-08 21:04:00 +0000154 if (C.getCounterID() >= CounterValues.size())
Justin Bogner3f188342014-09-08 21:31:43 +0000155 return std::make_error_code(std::errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000156 return CounterValues[C.getCounterID()];
157 case Counter::Expression: {
Justin Bogner85b0a032014-09-08 21:04:00 +0000158 if (C.getExpressionID() >= Expressions.size())
Justin Bogner3f188342014-09-08 21:31:43 +0000159 return std::make_error_code(std::errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000160 const auto &E = Expressions[C.getExpressionID()];
Justin Bogner85b0a032014-09-08 21:04:00 +0000161 ErrorOr<int64_t> LHS = evaluate(E.LHS);
162 if (!LHS)
163 return LHS;
164 ErrorOr<int64_t> RHS = evaluate(E.RHS);
165 if (!RHS)
166 return RHS;
167 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000168 }
169 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000170 llvm_unreachable("Unhandled CounterKind");
Alex Lorenza20a5d52014-07-24 23:57:54 +0000171}
Justin Bogner953e2402014-09-20 15:31:56 +0000172
Justin Bognerd5fca922014-11-14 01:50:32 +0000173void FunctionRecordIterator::skipOtherFiles() {
174 while (Current != Records.end() && !Filename.empty() &&
175 Filename != Current->Filenames[0])
176 ++Current;
177 if (Current == Records.end())
178 *this = FunctionRecordIterator();
179}
180
Justin Bogner953e2402014-09-20 15:31:56 +0000181ErrorOr<std::unique_ptr<CoverageMapping>>
182CoverageMapping::load(ObjectFileCoverageMappingReader &CoverageReader,
183 IndexedInstrProfReader &ProfileReader) {
184 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
185
186 std::vector<uint64_t> Counts;
187 for (const auto &Record : CoverageReader) {
188 Counts.clear();
189 if (std::error_code EC = ProfileReader.getFunctionCounts(
190 Record.FunctionName, Record.FunctionHash, Counts)) {
191 if (EC != instrprof_error::hash_mismatch &&
192 EC != instrprof_error::unknown_function)
193 return EC;
194 Coverage->MismatchedFunctionCount++;
195 continue;
196 }
197
Alex Lorenzcb1702d2014-09-30 12:45:13 +0000198 assert(Counts.size() != 0 && "Function's counts are empty");
199 FunctionRecord Function(Record.FunctionName, Record.Filenames,
200 Counts.front());
Justin Bogner953e2402014-09-20 15:31:56 +0000201 CounterMappingContext Ctx(Record.Expressions, Counts);
202 for (const auto &Region : Record.MappingRegions) {
203 ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
204 if (!ExecutionCount)
205 break;
206 Function.CountedRegions.push_back(CountedRegion(Region, *ExecutionCount));
207 }
208 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
209 Coverage->MismatchedFunctionCount++;
210 continue;
211 }
212
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000213 Coverage->Functions.push_back(std::move(Function));
Justin Bogner953e2402014-09-20 15:31:56 +0000214 }
215
216 return std::move(Coverage);
217}
218
Justin Bogner19a93ba2014-09-20 17:19:52 +0000219ErrorOr<std::unique_ptr<CoverageMapping>>
220CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename) {
221 auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
222 if (auto EC = CounterMappingBuff.getError())
223 return EC;
224 ObjectFileCoverageMappingReader CoverageReader(CounterMappingBuff.get());
225 if (auto EC = CoverageReader.readHeader())
226 return EC;
227 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
228 if (auto EC = IndexedInstrProfReader::create(ProfileFilename, ProfileReader))
229 return EC;
230 return load(CoverageReader, *ProfileReader);
231}
232
Justin Bogner953e2402014-09-20 15:31:56 +0000233namespace {
234/// \brief Distributes functions into instantiation sets.
235///
236/// An instantiation set is a collection of functions that have the same source
237/// code, ie, template functions specializations.
238class FunctionInstantiationSetCollector {
239 typedef DenseMap<std::pair<unsigned, unsigned>,
240 std::vector<const FunctionRecord *>> MapT;
241 MapT InstantiatedFunctions;
242
243public:
244 void insert(const FunctionRecord &Function, unsigned FileID) {
245 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
246 while (I != E && I->FileID != FileID)
247 ++I;
248 assert(I != E && "function does not cover the given file");
249 auto &Functions = InstantiatedFunctions[I->startLoc()];
250 Functions.push_back(&Function);
251 }
252
253 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
254
255 MapT::iterator end() { return InstantiatedFunctions.end(); }
256};
257
258class SegmentBuilder {
259 std::vector<CoverageSegment> Segments;
260 SmallVector<const CountedRegion *, 8> ActiveRegions;
261
262 /// Start a segment with no count specified.
263 void startSegment(unsigned Line, unsigned Col) {
Justin Bognerb35a72a2014-09-25 00:34:18 +0000264 DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000265 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
266 }
267
268 /// Start a segment with the given Region's count.
269 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
270 const CountedRegion &Region) {
271 if (Segments.empty())
272 Segments.emplace_back(Line, Col, IsRegionEntry);
273 CoverageSegment S = Segments.back();
274 // Avoid creating empty regions.
275 if (S.Line != Line || S.Col != Col) {
276 Segments.emplace_back(Line, Col, IsRegionEntry);
277 S = Segments.back();
278 }
Justin Bognerb35a72a2014-09-25 00:34:18 +0000279 DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
Justin Bogner953e2402014-09-20 15:31:56 +0000280 // Set this region's count.
Justin Bognerb35a72a2014-09-25 00:34:18 +0000281 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
282 DEBUG(dbgs() << " with count " << Region.ExecutionCount);
Justin Bogner953e2402014-09-20 15:31:56 +0000283 Segments.back().setCount(Region.ExecutionCount);
Justin Bognerb35a72a2014-09-25 00:34:18 +0000284 }
285 DEBUG(dbgs() << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000286 }
287
288 /// Start a segment for the given region.
289 void startSegment(const CountedRegion &Region) {
290 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
291 }
292
293 /// Pop the top region off of the active stack, starting a new segment with
294 /// the containing Region's count.
295 void popRegion() {
296 const CountedRegion *Active = ActiveRegions.back();
297 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
298 ActiveRegions.pop_back();
299 if (ActiveRegions.empty())
300 startSegment(Line, Col);
301 else
302 startSegment(Line, Col, false, *ActiveRegions.back());
303 }
304
305public:
306 /// Build a list of CoverageSegments from a sorted list of Regions.
307 std::vector<CoverageSegment> buildSegments(ArrayRef<CountedRegion> Regions) {
308 for (const auto &Region : Regions) {
309 // Pop any regions that end before this one starts.
310 while (!ActiveRegions.empty() &&
311 ActiveRegions.back()->endLoc() <= Region.startLoc())
312 popRegion();
Justin Bognerb35a72a2014-09-25 00:34:18 +0000313 if (Segments.size() && Segments.back().Line == Region.LineStart &&
314 Segments.back().Col == Region.ColumnStart) {
315 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion)
316 Segments.back().addCount(Region.ExecutionCount);
317 } else {
318 // Add this region to the stack.
319 ActiveRegions.push_back(&Region);
320 startSegment(Region);
321 }
Justin Bogner953e2402014-09-20 15:31:56 +0000322 }
323 // Pop any regions that are left in the stack.
324 while (!ActiveRegions.empty())
325 popRegion();
326 return Segments;
327 }
328};
329}
330
Justin Bognerd5fca922014-11-14 01:50:32 +0000331std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
Justin Bogner953e2402014-09-20 15:31:56 +0000332 std::vector<StringRef> Filenames;
333 for (const auto &Function : getCoveredFunctions())
334 for (const auto &Filename : Function.Filenames)
335 Filenames.push_back(Filename);
336 std::sort(Filenames.begin(), Filenames.end());
337 auto Last = std::unique(Filenames.begin(), Filenames.end());
338 Filenames.erase(Last, Filenames.end());
339 return Filenames;
340}
341
342static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
343 const FunctionRecord &Function) {
344 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
345 llvm::SmallVector<bool, 8> FilenameEquivalence(Function.Filenames.size(),
346 false);
347 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
348 if (SourceFile == Function.Filenames[I])
349 FilenameEquivalence[I] = true;
350 for (const auto &CR : Function.CountedRegions)
351 if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
352 FilenameEquivalence[CR.FileID])
353 IsExpandedFile[CR.ExpandedFileID] = true;
354 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
355 if (FilenameEquivalence[I] && !IsExpandedFile[I])
356 return I;
357 return None;
358}
359
360static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
361 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
362 for (const auto &CR : Function.CountedRegions)
363 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
364 IsExpandedFile[CR.ExpandedFileID] = true;
365 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
366 if (!IsExpandedFile[I])
367 return I;
368 return None;
369}
370
371static SmallSet<unsigned, 8> gatherFileIDs(StringRef SourceFile,
372 const FunctionRecord &Function) {
373 SmallSet<unsigned, 8> IDs;
374 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
375 if (SourceFile == Function.Filenames[I])
376 IDs.insert(I);
377 return IDs;
378}
379
380/// Sort a nested sequence of regions from a single file.
381template <class It> static void sortNestedRegions(It First, It Last) {
382 std::sort(First, Last,
383 [](const CountedRegion &LHS, const CountedRegion &RHS) {
384 if (LHS.startLoc() == RHS.startLoc())
385 // When LHS completely contains RHS, we sort LHS first.
386 return RHS.endLoc() < LHS.endLoc();
387 return LHS.startLoc() < RHS.startLoc();
388 });
389}
390
391static bool isExpansion(const CountedRegion &R, unsigned FileID) {
392 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
393}
394
395CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
396 CoverageData FileCoverage(Filename);
397 std::vector<coverage::CountedRegion> Regions;
398
399 for (const auto &Function : Functions) {
400 auto MainFileID = findMainViewFileID(Filename, Function);
401 if (!MainFileID)
402 continue;
403 auto FileIDs = gatherFileIDs(Filename, Function);
404 for (const auto &CR : Function.CountedRegions)
405 if (FileIDs.count(CR.FileID)) {
406 Regions.push_back(CR);
407 if (isExpansion(CR, *MainFileID))
408 FileCoverage.Expansions.emplace_back(CR, Function);
409 }
410 }
411
412 sortNestedRegions(Regions.begin(), Regions.end());
413 FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
414
415 return FileCoverage;
416}
417
418std::vector<const FunctionRecord *>
419CoverageMapping::getInstantiations(StringRef Filename) {
420 FunctionInstantiationSetCollector InstantiationSetCollector;
421 for (const auto &Function : Functions) {
422 auto MainFileID = findMainViewFileID(Filename, Function);
423 if (!MainFileID)
424 continue;
425 InstantiationSetCollector.insert(Function, *MainFileID);
426 }
427
428 std::vector<const FunctionRecord *> Result;
429 for (const auto &InstantiationSet : InstantiationSetCollector) {
430 if (InstantiationSet.second.size() < 2)
431 continue;
432 for (auto Function : InstantiationSet.second)
433 Result.push_back(Function);
434 }
435 return Result;
436}
437
438CoverageData
439CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
440 auto MainFileID = findMainViewFileID(Function);
441 if (!MainFileID)
442 return CoverageData();
443
444 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
445 std::vector<coverage::CountedRegion> Regions;
446 for (const auto &CR : Function.CountedRegions)
447 if (CR.FileID == *MainFileID) {
448 Regions.push_back(CR);
449 if (isExpansion(CR, *MainFileID))
450 FunctionCoverage.Expansions.emplace_back(CR, Function);
451 }
452
453 sortNestedRegions(Regions.begin(), Regions.end());
454 FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
455
456 return FunctionCoverage;
457}
458
459CoverageData
460CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
461 CoverageData ExpansionCoverage(
462 Expansion.Function.Filenames[Expansion.FileID]);
463 std::vector<coverage::CountedRegion> Regions;
464 for (const auto &CR : Expansion.Function.CountedRegions)
465 if (CR.FileID == Expansion.FileID) {
466 Regions.push_back(CR);
467 if (isExpansion(CR, Expansion.FileID))
468 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
469 }
470
471 sortNestedRegions(Regions.begin(), Regions.end());
472 ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
473
474 return ExpansionCoverage;
475}