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 CounterExpressionBuilder::CounterExpressionBuilder(unsigned NumCounterValues) {
31 Terms.resize(NumCounterValues);
34 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
35 for (unsigned I = 0, S = Expressions.size(); I < S; ++I) {
36 if (Expressions[I] == E)
37 return Counter::getExpression(I);
39 Expressions.push_back(E);
40 return Counter::getExpression(Expressions.size() - 1);
43 void CounterExpressionBuilder::extractTerms(Counter C, int Sign) {
44 switch (C.getKind()) {
47 case Counter::CounterValueReference:
48 Terms[C.getCounterID()] += Sign;
50 case Counter::Expression:
51 const auto &E = Expressions[C.getExpressionID()];
52 extractTerms(E.LHS, Sign);
53 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign);
58 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
59 // Gather constant terms.
62 extractTerms(ExpressionTree);
66 // Note: the additions are created first
67 // to avoid creation of a tree like ((0 - X) + Y) instead of (Y - X).
68 for (unsigned I = 0, S = Terms.size(); I < S; ++I) {
71 for (int J = 0; J < Terms[I]; ++J) {
73 C = Counter::getCounter(I);
75 C = get(CounterExpression(CounterExpression::Add, C,
76 Counter::getCounter(I)));
80 // Create subtractions.
81 for (unsigned I = 0, S = Terms.size(); I < S; ++I) {
84 for (int J = 0; J < (-Terms[I]); ++J)
85 C = get(CounterExpression(CounterExpression::Subtract, C,
86 Counter::getCounter(I)));
91 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
92 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
95 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
97 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
100 void CounterMappingContext::dump(const Counter &C,
101 llvm::raw_ostream &OS) const {
102 switch (C.getKind()) {
106 case Counter::CounterValueReference:
107 OS << '#' << C.getCounterID();
109 case Counter::Expression: {
110 if (C.getExpressionID() >= Expressions.size())
112 const auto &E = Expressions[C.getExpressionID()];
115 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
121 if (CounterValues.empty())
123 ErrorOr<int64_t> Value = evaluate(C);
126 OS << '[' << *Value << ']';
129 ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
130 switch (C.getKind()) {
133 case Counter::CounterValueReference:
134 if (C.getCounterID() >= CounterValues.size())
135 return std::make_error_code(std::errc::argument_out_of_domain);
136 return CounterValues[C.getCounterID()];
137 case Counter::Expression: {
138 if (C.getExpressionID() >= Expressions.size())
139 return std::make_error_code(std::errc::argument_out_of_domain);
140 const auto &E = Expressions[C.getExpressionID()];
141 ErrorOr<int64_t> LHS = evaluate(E.LHS);
144 ErrorOr<int64_t> RHS = evaluate(E.RHS);
147 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
150 llvm_unreachable("Unhandled CounterKind");
153 ErrorOr<std::unique_ptr<CoverageMapping>>
154 CoverageMapping::load(ObjectFileCoverageMappingReader &CoverageReader,
155 IndexedInstrProfReader &ProfileReader) {
156 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
158 std::vector<uint64_t> Counts;
159 for (const auto &Record : CoverageReader) {
161 if (std::error_code EC = ProfileReader.getFunctionCounts(
162 Record.FunctionName, Record.FunctionHash, Counts)) {
163 if (EC != instrprof_error::hash_mismatch &&
164 EC != instrprof_error::unknown_function)
166 Coverage->MismatchedFunctionCount++;
170 FunctionRecord Function(Record.FunctionName, Record.Filenames);
171 CounterMappingContext Ctx(Record.Expressions, Counts);
172 for (const auto &Region : Record.MappingRegions) {
173 ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
176 Function.CountedRegions.push_back(CountedRegion(Region, *ExecutionCount));
178 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
179 Coverage->MismatchedFunctionCount++;
183 Coverage->Functions.push_back(Function);
186 return std::move(Coverage);
189 ErrorOr<std::unique_ptr<CoverageMapping>>
190 CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename) {
191 auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
192 if (auto EC = CounterMappingBuff.getError())
194 ObjectFileCoverageMappingReader CoverageReader(CounterMappingBuff.get());
195 if (auto EC = CoverageReader.readHeader())
197 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
198 if (auto EC = IndexedInstrProfReader::create(ProfileFilename, ProfileReader))
200 return load(CoverageReader, *ProfileReader);
204 /// \brief Distributes functions into instantiation sets.
206 /// An instantiation set is a collection of functions that have the same source
207 /// code, ie, template functions specializations.
208 class FunctionInstantiationSetCollector {
209 typedef DenseMap<std::pair<unsigned, unsigned>,
210 std::vector<const FunctionRecord *>> MapT;
211 MapT InstantiatedFunctions;
214 void insert(const FunctionRecord &Function, unsigned FileID) {
215 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
216 while (I != E && I->FileID != FileID)
218 assert(I != E && "function does not cover the given file");
219 auto &Functions = InstantiatedFunctions[I->startLoc()];
220 Functions.push_back(&Function);
223 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
225 MapT::iterator end() { return InstantiatedFunctions.end(); }
228 class SegmentBuilder {
229 std::vector<CoverageSegment> Segments;
230 SmallVector<const CountedRegion *, 8> ActiveRegions;
232 /// Start a segment with no count specified.
233 void startSegment(unsigned Line, unsigned Col) {
234 DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
235 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
238 /// Start a segment with the given Region's count.
239 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
240 const CountedRegion &Region) {
241 if (Segments.empty())
242 Segments.emplace_back(Line, Col, IsRegionEntry);
243 CoverageSegment S = Segments.back();
244 // Avoid creating empty regions.
245 if (S.Line != Line || S.Col != Col) {
246 Segments.emplace_back(Line, Col, IsRegionEntry);
249 DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
250 // Set this region's count.
251 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
252 DEBUG(dbgs() << " with count " << Region.ExecutionCount);
253 Segments.back().setCount(Region.ExecutionCount);
255 DEBUG(dbgs() << "\n");
258 /// Start a segment for the given region.
259 void startSegment(const CountedRegion &Region) {
260 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
263 /// Pop the top region off of the active stack, starting a new segment with
264 /// the containing Region's count.
266 const CountedRegion *Active = ActiveRegions.back();
267 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
268 ActiveRegions.pop_back();
269 if (ActiveRegions.empty())
270 startSegment(Line, Col);
272 startSegment(Line, Col, false, *ActiveRegions.back());
276 /// Build a list of CoverageSegments from a sorted list of Regions.
277 std::vector<CoverageSegment> buildSegments(ArrayRef<CountedRegion> Regions) {
278 for (const auto &Region : Regions) {
279 // Pop any regions that end before this one starts.
280 while (!ActiveRegions.empty() &&
281 ActiveRegions.back()->endLoc() <= Region.startLoc())
283 if (Segments.size() && Segments.back().Line == Region.LineStart &&
284 Segments.back().Col == Region.ColumnStart) {
285 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion)
286 Segments.back().addCount(Region.ExecutionCount);
288 // Add this region to the stack.
289 ActiveRegions.push_back(&Region);
290 startSegment(Region);
293 // Pop any regions that are left in the stack.
294 while (!ActiveRegions.empty())
301 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() {
302 std::vector<StringRef> Filenames;
303 for (const auto &Function : getCoveredFunctions())
304 for (const auto &Filename : Function.Filenames)
305 Filenames.push_back(Filename);
306 std::sort(Filenames.begin(), Filenames.end());
307 auto Last = std::unique(Filenames.begin(), Filenames.end());
308 Filenames.erase(Last, Filenames.end());
312 static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
313 const FunctionRecord &Function) {
314 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
315 llvm::SmallVector<bool, 8> FilenameEquivalence(Function.Filenames.size(),
317 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
318 if (SourceFile == Function.Filenames[I])
319 FilenameEquivalence[I] = true;
320 for (const auto &CR : Function.CountedRegions)
321 if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
322 FilenameEquivalence[CR.FileID])
323 IsExpandedFile[CR.ExpandedFileID] = true;
324 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
325 if (FilenameEquivalence[I] && !IsExpandedFile[I])
330 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
331 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
332 for (const auto &CR : Function.CountedRegions)
333 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
334 IsExpandedFile[CR.ExpandedFileID] = true;
335 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
336 if (!IsExpandedFile[I])
341 static SmallSet<unsigned, 8> gatherFileIDs(StringRef SourceFile,
342 const FunctionRecord &Function) {
343 SmallSet<unsigned, 8> IDs;
344 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
345 if (SourceFile == Function.Filenames[I])
350 /// Sort a nested sequence of regions from a single file.
351 template <class It> static void sortNestedRegions(It First, It Last) {
352 std::sort(First, Last,
353 [](const CountedRegion &LHS, const CountedRegion &RHS) {
354 if (LHS.startLoc() == RHS.startLoc())
355 // When LHS completely contains RHS, we sort LHS first.
356 return RHS.endLoc() < LHS.endLoc();
357 return LHS.startLoc() < RHS.startLoc();
361 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
362 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
365 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
366 CoverageData FileCoverage(Filename);
367 std::vector<coverage::CountedRegion> Regions;
369 for (const auto &Function : Functions) {
370 auto MainFileID = findMainViewFileID(Filename, Function);
373 auto FileIDs = gatherFileIDs(Filename, Function);
374 for (const auto &CR : Function.CountedRegions)
375 if (FileIDs.count(CR.FileID)) {
376 Regions.push_back(CR);
377 if (isExpansion(CR, *MainFileID))
378 FileCoverage.Expansions.emplace_back(CR, Function);
382 sortNestedRegions(Regions.begin(), Regions.end());
383 FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
388 std::vector<const FunctionRecord *>
389 CoverageMapping::getInstantiations(StringRef Filename) {
390 FunctionInstantiationSetCollector InstantiationSetCollector;
391 for (const auto &Function : Functions) {
392 auto MainFileID = findMainViewFileID(Filename, Function);
395 InstantiationSetCollector.insert(Function, *MainFileID);
398 std::vector<const FunctionRecord *> Result;
399 for (const auto &InstantiationSet : InstantiationSetCollector) {
400 if (InstantiationSet.second.size() < 2)
402 for (auto Function : InstantiationSet.second)
403 Result.push_back(Function);
409 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
410 auto MainFileID = findMainViewFileID(Function);
412 return CoverageData();
414 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
415 std::vector<coverage::CountedRegion> Regions;
416 for (const auto &CR : Function.CountedRegions)
417 if (CR.FileID == *MainFileID) {
418 Regions.push_back(CR);
419 if (isExpansion(CR, *MainFileID))
420 FunctionCoverage.Expansions.emplace_back(CR, Function);
423 sortNestedRegions(Regions.begin(), Regions.end());
424 FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
426 return FunctionCoverage;
430 CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
431 CoverageData ExpansionCoverage(
432 Expansion.Function.Filenames[Expansion.FileID]);
433 std::vector<coverage::CountedRegion> Regions;
434 for (const auto &CR : Expansion.Function.CountedRegions)
435 if (CR.FileID == Expansion.FileID) {
436 Regions.push_back(CR);
437 if (isExpansion(CR, Expansion.FileID))
438 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
441 sortNestedRegions(Regions.begin(), Regions.end());
442 ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
444 return ExpansionCoverage;