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