1 //=-- CoverageMapping.cpp - Code coverage mapping support ---------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for clang's and llvm's instrumentation based
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ProfileData/CoverageMapping.h"
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"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
26 using namespace coverage;
28 #define DEBUG_TYPE "coverage-mapping"
30 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
31 for (unsigned I = 0, S = Expressions.size(); I < S; ++I) {
32 if (Expressions[I] == E)
33 return Counter::getExpression(I);
35 Expressions.push_back(E);
36 return Counter::getExpression(Expressions.size() - 1);
39 void CounterExpressionBuilder::extractTerms(
40 Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
41 switch (C.getKind()) {
44 case Counter::CounterValueReference:
45 Terms.push_back(std::make_pair(C.getCounterID(), Sign));
47 case Counter::Expression:
48 const auto &E = Expressions[C.getExpressionID()];
49 extractTerms(E.LHS, Sign, Terms);
50 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
56 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
57 // Gather constant terms.
58 llvm::SmallVector<std::pair<unsigned, int>, 32> Terms;
59 extractTerms(ExpressionTree, +1, Terms);
61 // Group the terms by counter ID.
62 std::sort(Terms.begin(), Terms.end(),
63 [](const std::pair<unsigned, int> &LHS,
64 const std::pair<unsigned, int> &RHS) {
65 return LHS.first < RHS.first;
68 // Combine terms by counter ID to eliminate counters that sum to zero.
69 auto Prev = Terms.begin();
70 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
71 if (I->first == Prev->first) {
72 Prev->second += I->second;
78 Terms.erase(++Prev, Terms.end());
81 // Create additions. We do this before subtractions to avoid constructs like
82 // ((0 - X) + Y), as opposed to (Y - X).
83 for (auto Term : Terms) {
86 for (int I = 0; I < Term.second; ++I)
88 C = Counter::getCounter(Term.first);
90 C = get(CounterExpression(CounterExpression::Add, C,
91 Counter::getCounter(Term.first)));
94 // Create subtractions.
95 for (auto Term : Terms) {
98 for (int I = 0; I < -Term.second; ++I)
99 C = get(CounterExpression(CounterExpression::Subtract, C,
100 Counter::getCounter(Term.first)));
105 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
106 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
109 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
111 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
114 void CounterMappingContext::dump(const Counter &C,
115 llvm::raw_ostream &OS) const {
116 switch (C.getKind()) {
120 case Counter::CounterValueReference:
121 OS << '#' << C.getCounterID();
123 case Counter::Expression: {
124 if (C.getExpressionID() >= Expressions.size())
126 const auto &E = Expressions[C.getExpressionID()];
129 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
135 if (CounterValues.empty())
137 ErrorOr<int64_t> Value = evaluate(C);
140 OS << '[' << *Value << ']';
143 ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
144 switch (C.getKind()) {
147 case Counter::CounterValueReference:
148 if (C.getCounterID() >= CounterValues.size())
149 return std::make_error_code(std::errc::argument_out_of_domain);
150 return CounterValues[C.getCounterID()];
151 case Counter::Expression: {
152 if (C.getExpressionID() >= Expressions.size())
153 return std::make_error_code(std::errc::argument_out_of_domain);
154 const auto &E = Expressions[C.getExpressionID()];
155 ErrorOr<int64_t> LHS = evaluate(E.LHS);
158 ErrorOr<int64_t> RHS = evaluate(E.RHS);
161 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
164 llvm_unreachable("Unhandled CounterKind");
167 ErrorOr<std::unique_ptr<CoverageMapping>>
168 CoverageMapping::load(ObjectFileCoverageMappingReader &CoverageReader,
169 IndexedInstrProfReader &ProfileReader) {
170 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
172 std::vector<uint64_t> Counts;
173 for (const auto &Record : CoverageReader) {
175 if (std::error_code EC = ProfileReader.getFunctionCounts(
176 Record.FunctionName, Record.FunctionHash, Counts)) {
177 if (EC != instrprof_error::hash_mismatch &&
178 EC != instrprof_error::unknown_function)
180 Coverage->MismatchedFunctionCount++;
184 assert(Counts.size() != 0 && "Function's counts are empty");
185 FunctionRecord Function(Record.FunctionName, Record.Filenames,
187 CounterMappingContext Ctx(Record.Expressions, Counts);
188 for (const auto &Region : Record.MappingRegions) {
189 ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
192 Function.CountedRegions.push_back(CountedRegion(Region, *ExecutionCount));
194 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
195 Coverage->MismatchedFunctionCount++;
199 Coverage->Functions.push_back(Function);
202 return std::move(Coverage);
205 ErrorOr<std::unique_ptr<CoverageMapping>>
206 CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename) {
207 auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
208 if (auto EC = CounterMappingBuff.getError())
210 ObjectFileCoverageMappingReader CoverageReader(CounterMappingBuff.get());
211 if (auto EC = CoverageReader.readHeader())
213 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
214 if (auto EC = IndexedInstrProfReader::create(ProfileFilename, ProfileReader))
216 return load(CoverageReader, *ProfileReader);
220 /// \brief Distributes functions into instantiation sets.
222 /// An instantiation set is a collection of functions that have the same source
223 /// code, ie, template functions specializations.
224 class FunctionInstantiationSetCollector {
225 typedef DenseMap<std::pair<unsigned, unsigned>,
226 std::vector<const FunctionRecord *>> MapT;
227 MapT InstantiatedFunctions;
230 void insert(const FunctionRecord &Function, unsigned FileID) {
231 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
232 while (I != E && I->FileID != FileID)
234 assert(I != E && "function does not cover the given file");
235 auto &Functions = InstantiatedFunctions[I->startLoc()];
236 Functions.push_back(&Function);
239 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
241 MapT::iterator end() { return InstantiatedFunctions.end(); }
244 class SegmentBuilder {
245 std::vector<CoverageSegment> Segments;
246 SmallVector<const CountedRegion *, 8> ActiveRegions;
248 /// Start a segment with no count specified.
249 void startSegment(unsigned Line, unsigned Col) {
250 DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
251 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
254 /// Start a segment with the given Region's count.
255 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
256 const CountedRegion &Region) {
257 if (Segments.empty())
258 Segments.emplace_back(Line, Col, IsRegionEntry);
259 CoverageSegment S = Segments.back();
260 // Avoid creating empty regions.
261 if (S.Line != Line || S.Col != Col) {
262 Segments.emplace_back(Line, Col, IsRegionEntry);
265 DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
266 // Set this region's count.
267 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
268 DEBUG(dbgs() << " with count " << Region.ExecutionCount);
269 Segments.back().setCount(Region.ExecutionCount);
271 DEBUG(dbgs() << "\n");
274 /// Start a segment for the given region.
275 void startSegment(const CountedRegion &Region) {
276 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
279 /// Pop the top region off of the active stack, starting a new segment with
280 /// the containing Region's count.
282 const CountedRegion *Active = ActiveRegions.back();
283 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
284 ActiveRegions.pop_back();
285 if (ActiveRegions.empty())
286 startSegment(Line, Col);
288 startSegment(Line, Col, false, *ActiveRegions.back());
292 /// Build a list of CoverageSegments from a sorted list of Regions.
293 std::vector<CoverageSegment> buildSegments(ArrayRef<CountedRegion> Regions) {
294 for (const auto &Region : Regions) {
295 // Pop any regions that end before this one starts.
296 while (!ActiveRegions.empty() &&
297 ActiveRegions.back()->endLoc() <= Region.startLoc())
299 if (Segments.size() && Segments.back().Line == Region.LineStart &&
300 Segments.back().Col == Region.ColumnStart) {
301 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion)
302 Segments.back().addCount(Region.ExecutionCount);
304 // Add this region to the stack.
305 ActiveRegions.push_back(&Region);
306 startSegment(Region);
309 // Pop any regions that are left in the stack.
310 while (!ActiveRegions.empty())
317 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() {
318 std::vector<StringRef> Filenames;
319 for (const auto &Function : getCoveredFunctions())
320 for (const auto &Filename : Function.Filenames)
321 Filenames.push_back(Filename);
322 std::sort(Filenames.begin(), Filenames.end());
323 auto Last = std::unique(Filenames.begin(), Filenames.end());
324 Filenames.erase(Last, Filenames.end());
328 static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
329 const FunctionRecord &Function) {
330 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
331 llvm::SmallVector<bool, 8> FilenameEquivalence(Function.Filenames.size(),
333 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
334 if (SourceFile == Function.Filenames[I])
335 FilenameEquivalence[I] = true;
336 for (const auto &CR : Function.CountedRegions)
337 if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
338 FilenameEquivalence[CR.FileID])
339 IsExpandedFile[CR.ExpandedFileID] = true;
340 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
341 if (FilenameEquivalence[I] && !IsExpandedFile[I])
346 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
347 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
348 for (const auto &CR : Function.CountedRegions)
349 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
350 IsExpandedFile[CR.ExpandedFileID] = true;
351 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
352 if (!IsExpandedFile[I])
357 static SmallSet<unsigned, 8> gatherFileIDs(StringRef SourceFile,
358 const FunctionRecord &Function) {
359 SmallSet<unsigned, 8> IDs;
360 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
361 if (SourceFile == Function.Filenames[I])
366 /// Sort a nested sequence of regions from a single file.
367 template <class It> static void sortNestedRegions(It First, It Last) {
368 std::sort(First, Last,
369 [](const CountedRegion &LHS, const CountedRegion &RHS) {
370 if (LHS.startLoc() == RHS.startLoc())
371 // When LHS completely contains RHS, we sort LHS first.
372 return RHS.endLoc() < LHS.endLoc();
373 return LHS.startLoc() < RHS.startLoc();
377 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
378 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
381 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
382 CoverageData FileCoverage(Filename);
383 std::vector<coverage::CountedRegion> Regions;
385 for (const auto &Function : Functions) {
386 auto MainFileID = findMainViewFileID(Filename, Function);
389 auto FileIDs = gatherFileIDs(Filename, Function);
390 for (const auto &CR : Function.CountedRegions)
391 if (FileIDs.count(CR.FileID)) {
392 Regions.push_back(CR);
393 if (isExpansion(CR, *MainFileID))
394 FileCoverage.Expansions.emplace_back(CR, Function);
398 sortNestedRegions(Regions.begin(), Regions.end());
399 FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
404 std::vector<const FunctionRecord *>
405 CoverageMapping::getInstantiations(StringRef Filename) {
406 FunctionInstantiationSetCollector InstantiationSetCollector;
407 for (const auto &Function : Functions) {
408 auto MainFileID = findMainViewFileID(Filename, Function);
411 InstantiationSetCollector.insert(Function, *MainFileID);
414 std::vector<const FunctionRecord *> Result;
415 for (const auto &InstantiationSet : InstantiationSetCollector) {
416 if (InstantiationSet.second.size() < 2)
418 for (auto Function : InstantiationSet.second)
419 Result.push_back(Function);
425 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
426 auto MainFileID = findMainViewFileID(Function);
428 return CoverageData();
430 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
431 std::vector<coverage::CountedRegion> Regions;
432 for (const auto &CR : Function.CountedRegions)
433 if (CR.FileID == *MainFileID) {
434 Regions.push_back(CR);
435 if (isExpansion(CR, *MainFileID))
436 FunctionCoverage.Expansions.emplace_back(CR, Function);
439 sortNestedRegions(Regions.begin(), Regions.end());
440 FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
442 return FunctionCoverage;
446 CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
447 CoverageData ExpansionCoverage(
448 Expansion.Function.Filenames[Expansion.FileID]);
449 std::vector<coverage::CountedRegion> Regions;
450 for (const auto &CR : Expansion.Function.CountedRegions)
451 if (CR.FileID == Expansion.FileID) {
452 Regions.push_back(CR);
453 if (isExpansion(CR, Expansion.FileID))
454 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
457 sortNestedRegions(Regions.begin(), Regions.end());
458 ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
460 return ExpansionCoverage;