blob: 2e205f3fba5607e51f28afb4ae5048c6411320ba [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 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
27CounterExpressionBuilder::CounterExpressionBuilder(unsigned NumCounterValues) {
28 Terms.resize(NumCounterValues);
29}
30
31Counter CounterExpressionBuilder::get(const CounterExpression &E) {
32 for (unsigned I = 0, S = Expressions.size(); I < S; ++I) {
33 if (Expressions[I] == E)
34 return Counter::getExpression(I);
35 }
36 Expressions.push_back(E);
37 return Counter::getExpression(Expressions.size() - 1);
38}
39
40void CounterExpressionBuilder::extractTerms(Counter C, int Sign) {
41 switch (C.getKind()) {
42 case Counter::Zero:
43 break;
44 case Counter::CounterValueReference:
45 Terms[C.getCounterID()] += Sign;
46 break;
47 case Counter::Expression:
48 const auto &E = Expressions[C.getExpressionID()];
49 extractTerms(E.LHS, Sign);
50 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign);
51 break;
52 }
53}
54
55Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
56 // Gather constant terms.
57 for (auto &I : Terms)
58 I = 0;
59 extractTerms(ExpressionTree);
60
61 Counter C;
62 // Create additions.
63 // Note: the additions are created first
64 // to avoid creation of a tree like ((0 - X) + Y) instead of (Y - X).
65 for (unsigned I = 0, S = Terms.size(); I < S; ++I) {
66 if (Terms[I] <= 0)
67 continue;
68 for (int J = 0; J < Terms[I]; ++J) {
69 if (C.isZero())
70 C = Counter::getCounter(I);
71 else
72 C = get(CounterExpression(CounterExpression::Add, C,
73 Counter::getCounter(I)));
74 }
75 }
76
77 // Create subtractions.
78 for (unsigned I = 0, S = Terms.size(); I < S; ++I) {
79 if (Terms[I] >= 0)
80 continue;
81 for (int J = 0; J < (-Terms[I]); ++J)
82 C = get(CounterExpression(CounterExpression::Subtract, C,
83 Counter::getCounter(I)));
84 }
85 return C;
86}
87
88Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
89 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
90}
91
92Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
93 return simplify(
94 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
95}
96
97void CounterMappingContext::dump(const Counter &C,
98 llvm::raw_ostream &OS) const {
99 switch (C.getKind()) {
100 case Counter::Zero:
101 OS << '0';
102 return;
103 case Counter::CounterValueReference:
104 OS << '#' << C.getCounterID();
105 break;
106 case Counter::Expression: {
107 if (C.getExpressionID() >= Expressions.size())
108 return;
109 const auto &E = Expressions[C.getExpressionID()];
110 OS << '(';
Alex Lorenza422911c2014-07-29 19:58:16 +0000111 dump(E.LHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000112 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
Alex Lorenza422911c2014-07-29 19:58:16 +0000113 dump(E.RHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000114 OS << ')';
115 break;
116 }
117 }
118 if (CounterValues.empty())
119 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000120 ErrorOr<int64_t> Value = evaluate(C);
121 if (!Value)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000122 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000123 OS << '[' << *Value << ']';
Alex Lorenza20a5d52014-07-24 23:57:54 +0000124}
125
Justin Bogner85b0a032014-09-08 21:04:00 +0000126ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000127 switch (C.getKind()) {
128 case Counter::Zero:
129 return 0;
130 case Counter::CounterValueReference:
Justin Bogner85b0a032014-09-08 21:04:00 +0000131 if (C.getCounterID() >= CounterValues.size())
Justin Bogner3f188342014-09-08 21:31:43 +0000132 return std::make_error_code(std::errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000133 return CounterValues[C.getCounterID()];
134 case Counter::Expression: {
Justin Bogner85b0a032014-09-08 21:04:00 +0000135 if (C.getExpressionID() >= Expressions.size())
Justin Bogner3f188342014-09-08 21:31:43 +0000136 return std::make_error_code(std::errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000137 const auto &E = Expressions[C.getExpressionID()];
Justin Bogner85b0a032014-09-08 21:04:00 +0000138 ErrorOr<int64_t> LHS = evaluate(E.LHS);
139 if (!LHS)
140 return LHS;
141 ErrorOr<int64_t> RHS = evaluate(E.RHS);
142 if (!RHS)
143 return RHS;
144 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000145 }
146 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000147 llvm_unreachable("Unhandled CounterKind");
Alex Lorenza20a5d52014-07-24 23:57:54 +0000148}
Justin Bogner953e2402014-09-20 15:31:56 +0000149
150ErrorOr<std::unique_ptr<CoverageMapping>>
151CoverageMapping::load(ObjectFileCoverageMappingReader &CoverageReader,
152 IndexedInstrProfReader &ProfileReader) {
153 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
154
155 std::vector<uint64_t> Counts;
156 for (const auto &Record : CoverageReader) {
157 Counts.clear();
158 if (std::error_code EC = ProfileReader.getFunctionCounts(
159 Record.FunctionName, Record.FunctionHash, Counts)) {
160 if (EC != instrprof_error::hash_mismatch &&
161 EC != instrprof_error::unknown_function)
162 return EC;
163 Coverage->MismatchedFunctionCount++;
164 continue;
165 }
166
167 FunctionRecord Function(Record.FunctionName, Record.Filenames);
168 CounterMappingContext Ctx(Record.Expressions, Counts);
169 for (const auto &Region : Record.MappingRegions) {
170 ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
171 if (!ExecutionCount)
172 break;
173 Function.CountedRegions.push_back(CountedRegion(Region, *ExecutionCount));
174 }
175 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
176 Coverage->MismatchedFunctionCount++;
177 continue;
178 }
179
180 Coverage->Functions.push_back(Function);
181 }
182
183 return std::move(Coverage);
184}
185
186namespace {
187/// \brief Distributes functions into instantiation sets.
188///
189/// An instantiation set is a collection of functions that have the same source
190/// code, ie, template functions specializations.
191class FunctionInstantiationSetCollector {
192 typedef DenseMap<std::pair<unsigned, unsigned>,
193 std::vector<const FunctionRecord *>> MapT;
194 MapT InstantiatedFunctions;
195
196public:
197 void insert(const FunctionRecord &Function, unsigned FileID) {
198 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
199 while (I != E && I->FileID != FileID)
200 ++I;
201 assert(I != E && "function does not cover the given file");
202 auto &Functions = InstantiatedFunctions[I->startLoc()];
203 Functions.push_back(&Function);
204 }
205
206 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
207
208 MapT::iterator end() { return InstantiatedFunctions.end(); }
209};
210
211class SegmentBuilder {
212 std::vector<CoverageSegment> Segments;
213 SmallVector<const CountedRegion *, 8> ActiveRegions;
214
215 /// Start a segment with no count specified.
216 void startSegment(unsigned Line, unsigned Col) {
217 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
218 }
219
220 /// Start a segment with the given Region's count.
221 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
222 const CountedRegion &Region) {
223 if (Segments.empty())
224 Segments.emplace_back(Line, Col, IsRegionEntry);
225 CoverageSegment S = Segments.back();
226 // Avoid creating empty regions.
227 if (S.Line != Line || S.Col != Col) {
228 Segments.emplace_back(Line, Col, IsRegionEntry);
229 S = Segments.back();
230 }
231 // Set this region's count.
232 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion)
233 Segments.back().setCount(Region.ExecutionCount);
234 }
235
236 /// Start a segment for the given region.
237 void startSegment(const CountedRegion &Region) {
238 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
239 }
240
241 /// Pop the top region off of the active stack, starting a new segment with
242 /// the containing Region's count.
243 void popRegion() {
244 const CountedRegion *Active = ActiveRegions.back();
245 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
246 ActiveRegions.pop_back();
247 if (ActiveRegions.empty())
248 startSegment(Line, Col);
249 else
250 startSegment(Line, Col, false, *ActiveRegions.back());
251 }
252
253public:
254 /// Build a list of CoverageSegments from a sorted list of Regions.
255 std::vector<CoverageSegment> buildSegments(ArrayRef<CountedRegion> Regions) {
256 for (const auto &Region : Regions) {
257 // Pop any regions that end before this one starts.
258 while (!ActiveRegions.empty() &&
259 ActiveRegions.back()->endLoc() <= Region.startLoc())
260 popRegion();
261 // Add this region to the stack.
262 ActiveRegions.push_back(&Region);
263 startSegment(Region);
264 }
265 // Pop any regions that are left in the stack.
266 while (!ActiveRegions.empty())
267 popRegion();
268 return Segments;
269 }
270};
271}
272
273std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() {
274 std::vector<StringRef> Filenames;
275 for (const auto &Function : getCoveredFunctions())
276 for (const auto &Filename : Function.Filenames)
277 Filenames.push_back(Filename);
278 std::sort(Filenames.begin(), Filenames.end());
279 auto Last = std::unique(Filenames.begin(), Filenames.end());
280 Filenames.erase(Last, Filenames.end());
281 return Filenames;
282}
283
284static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
285 const FunctionRecord &Function) {
286 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
287 llvm::SmallVector<bool, 8> FilenameEquivalence(Function.Filenames.size(),
288 false);
289 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
290 if (SourceFile == Function.Filenames[I])
291 FilenameEquivalence[I] = true;
292 for (const auto &CR : Function.CountedRegions)
293 if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
294 FilenameEquivalence[CR.FileID])
295 IsExpandedFile[CR.ExpandedFileID] = true;
296 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
297 if (FilenameEquivalence[I] && !IsExpandedFile[I])
298 return I;
299 return None;
300}
301
302static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
303 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
304 for (const auto &CR : Function.CountedRegions)
305 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
306 IsExpandedFile[CR.ExpandedFileID] = true;
307 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
308 if (!IsExpandedFile[I])
309 return I;
310 return None;
311}
312
313static SmallSet<unsigned, 8> gatherFileIDs(StringRef SourceFile,
314 const FunctionRecord &Function) {
315 SmallSet<unsigned, 8> IDs;
316 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
317 if (SourceFile == Function.Filenames[I])
318 IDs.insert(I);
319 return IDs;
320}
321
322/// Sort a nested sequence of regions from a single file.
323template <class It> static void sortNestedRegions(It First, It Last) {
324 std::sort(First, Last,
325 [](const CountedRegion &LHS, const CountedRegion &RHS) {
326 if (LHS.startLoc() == RHS.startLoc())
327 // When LHS completely contains RHS, we sort LHS first.
328 return RHS.endLoc() < LHS.endLoc();
329 return LHS.startLoc() < RHS.startLoc();
330 });
331}
332
333static bool isExpansion(const CountedRegion &R, unsigned FileID) {
334 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
335}
336
337CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
338 CoverageData FileCoverage(Filename);
339 std::vector<coverage::CountedRegion> Regions;
340
341 for (const auto &Function : Functions) {
342 auto MainFileID = findMainViewFileID(Filename, Function);
343 if (!MainFileID)
344 continue;
345 auto FileIDs = gatherFileIDs(Filename, Function);
346 for (const auto &CR : Function.CountedRegions)
347 if (FileIDs.count(CR.FileID)) {
348 Regions.push_back(CR);
349 if (isExpansion(CR, *MainFileID))
350 FileCoverage.Expansions.emplace_back(CR, Function);
351 }
352 }
353
354 sortNestedRegions(Regions.begin(), Regions.end());
355 FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
356
357 return FileCoverage;
358}
359
360std::vector<const FunctionRecord *>
361CoverageMapping::getInstantiations(StringRef Filename) {
362 FunctionInstantiationSetCollector InstantiationSetCollector;
363 for (const auto &Function : Functions) {
364 auto MainFileID = findMainViewFileID(Filename, Function);
365 if (!MainFileID)
366 continue;
367 InstantiationSetCollector.insert(Function, *MainFileID);
368 }
369
370 std::vector<const FunctionRecord *> Result;
371 for (const auto &InstantiationSet : InstantiationSetCollector) {
372 if (InstantiationSet.second.size() < 2)
373 continue;
374 for (auto Function : InstantiationSet.second)
375 Result.push_back(Function);
376 }
377 return Result;
378}
379
380CoverageData
381CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
382 auto MainFileID = findMainViewFileID(Function);
383 if (!MainFileID)
384 return CoverageData();
385
386 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
387 std::vector<coverage::CountedRegion> Regions;
388 for (const auto &CR : Function.CountedRegions)
389 if (CR.FileID == *MainFileID) {
390 Regions.push_back(CR);
391 if (isExpansion(CR, *MainFileID))
392 FunctionCoverage.Expansions.emplace_back(CR, Function);
393 }
394
395 sortNestedRegions(Regions.begin(), Regions.end());
396 FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
397
398 return FunctionCoverage;
399}
400
401CoverageData
402CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
403 CoverageData ExpansionCoverage(
404 Expansion.Function.Filenames[Expansion.FileID]);
405 std::vector<coverage::CountedRegion> Regions;
406 for (const auto &CR : Expansion.Function.CountedRegions)
407 if (CR.FileID == Expansion.FileID) {
408 Regions.push_back(CR);
409 if (isExpansion(CR, Expansion.FileID))
410 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
411 }
412
413 sortNestedRegions(Regions.begin(), Regions.end());
414 ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
415
416 return ExpansionCoverage;
417}