1 //=-- CoverageMapping.h - 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 // Code coverage mapping data is generated by clang and read by
11 // llvm-cov to show code coverage statistics for a file.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PROFILEDATA_COVERAGEMAPPING_H_
16 #define LLVM_PROFILEDATA_COVERAGEMAPPING_H_
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorOr.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <system_error>
28 class IndexedInstrProfReader;
31 class ObjectFileCoverageMappingReader;
33 class CoverageMapping;
34 struct CounterExpressions;
36 enum CoverageMappingVersion { CoverageMappingVersion1 };
38 /// \brief A Counter is an abstract value that describes how to compute the
39 /// execution count for a region of code using the collected profile count data.
41 enum CounterKind { Zero, CounterValueReference, Expression };
42 static const unsigned EncodingTagBits = 2;
43 static const unsigned EncodingTagMask = 0x3;
44 static const unsigned EncodingCounterTagAndExpansionRegionTagBits =
51 Counter(CounterKind Kind, unsigned ID) : Kind(Kind), ID(ID) {}
54 Counter() : Kind(Zero), ID(0) {}
56 CounterKind getKind() const { return Kind; }
58 bool isZero() const { return Kind == Zero; }
60 bool isExpression() const { return Kind == Expression; }
62 unsigned getCounterID() const { return ID; }
64 unsigned getExpressionID() const { return ID; }
66 friend bool operator==(const Counter &LHS, const Counter &RHS) {
67 return LHS.Kind == RHS.Kind && LHS.ID == RHS.ID;
70 friend bool operator!=(const Counter &LHS, const Counter &RHS) {
74 friend bool operator<(const Counter &LHS, const Counter &RHS) {
75 return std::tie(LHS.Kind, LHS.ID) < std::tie(RHS.Kind, RHS.ID);
78 /// \brief Return the counter that represents the number zero.
79 static Counter getZero() { return Counter(); }
81 /// \brief Return the counter that corresponds to a specific profile counter.
82 static Counter getCounter(unsigned CounterId) {
83 return Counter(CounterValueReference, CounterId);
86 /// \brief Return the counter that corresponds to a specific
87 /// addition counter expression.
88 static Counter getExpression(unsigned ExpressionId) {
89 return Counter(Expression, ExpressionId);
93 /// \brief A Counter expression is a value that represents an arithmetic
94 /// operation with two counters.
95 struct CounterExpression {
96 enum ExprKind { Subtract, Add };
100 CounterExpression(ExprKind Kind, Counter LHS, Counter RHS)
101 : Kind(Kind), LHS(LHS), RHS(RHS) {}
104 /// \brief A Counter expression builder is used to construct the
105 /// counter expressions. It avoids unecessary duplication
106 /// and simplifies algebraic expressions.
107 class CounterExpressionBuilder {
108 /// \brief A list of all the counter expressions
109 std::vector<CounterExpression> Expressions;
110 /// \brief A lookup table for the index of a given expression.
111 llvm::DenseMap<CounterExpression, unsigned> ExpressionIndices;
113 /// \brief Return the counter which corresponds to the given expression.
115 /// If the given expression is already stored in the builder, a counter
116 /// that references that expression is returned. Otherwise, the given
117 /// expression is added to the builder's collection of expressions.
118 Counter get(const CounterExpression &E);
120 /// \brief Gather the terms of the expression tree for processing.
122 /// This collects each addition and subtraction referenced by the counter into
123 /// a sequence that can be sorted and combined to build a simplified counter
125 void extractTerms(Counter C, int Sign,
126 SmallVectorImpl<std::pair<unsigned, int>> &Terms);
128 /// \brief Simplifies the given expression tree
129 /// by getting rid of algebraically redundant operations.
130 Counter simplify(Counter ExpressionTree);
133 ArrayRef<CounterExpression> getExpressions() const { return Expressions; }
135 /// \brief Return a counter that represents the expression
136 /// that adds LHS and RHS.
137 Counter add(Counter LHS, Counter RHS);
139 /// \brief Return a counter that represents the expression
140 /// that subtracts RHS from LHS.
141 Counter subtract(Counter LHS, Counter RHS);
144 /// \brief A Counter mapping region associates a source range with
145 /// a specific counter.
146 struct CounterMappingRegion {
148 /// \brief A CodeRegion associates some code with a counter
151 /// \brief An ExpansionRegion represents a file expansion region that
152 /// associates a source range with the expansion of a virtual source file,
153 /// such as for a macro instantiation or #include file.
156 /// \brief A SkippedRegion represents a source range with code that
157 /// was skipped by a preprocessor or similar means.
161 static const unsigned EncodingHasCodeBeforeBits = 1;
164 unsigned FileID, ExpandedFileID;
165 unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
167 /// \brief A flag that is set to true when there is already code before
168 /// this region on the same line.
169 /// This is useful to accurately compute the execution counts for a line.
172 CounterMappingRegion(Counter Count, unsigned FileID, unsigned LineStart,
173 unsigned ColumnStart, unsigned LineEnd,
174 unsigned ColumnEnd, bool HasCodeBefore = false,
175 RegionKind Kind = CodeRegion)
176 : Count(Count), FileID(FileID), ExpandedFileID(0), LineStart(LineStart),
177 ColumnStart(ColumnStart), LineEnd(LineEnd), ColumnEnd(ColumnEnd),
178 Kind(Kind), HasCodeBefore(HasCodeBefore) {}
180 inline std::pair<unsigned, unsigned> startLoc() const {
181 return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
184 inline std::pair<unsigned, unsigned> endLoc() const {
185 return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
188 bool operator<(const CounterMappingRegion &Other) const {
189 if (FileID != Other.FileID)
190 return FileID < Other.FileID;
191 return startLoc() < Other.startLoc();
194 bool contains(const CounterMappingRegion &Other) const {
195 if (FileID != Other.FileID)
197 if (startLoc() > Other.startLoc())
199 if (endLoc() < Other.endLoc())
205 /// \brief Associates a source range with an execution count.
206 struct CountedRegion : public CounterMappingRegion {
207 uint64_t ExecutionCount;
209 CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
210 : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
213 /// \brief A Counter mapping context is used to connect the counters,
214 /// expressions and the obtained counter values.
215 class CounterMappingContext {
216 ArrayRef<CounterExpression> Expressions;
217 ArrayRef<uint64_t> CounterValues;
220 CounterMappingContext(ArrayRef<CounterExpression> Expressions,
221 ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>())
222 : Expressions(Expressions), CounterValues(CounterValues) {}
224 void dump(const Counter &C, llvm::raw_ostream &OS) const;
225 void dump(const Counter &C) const { dump(C, dbgs()); }
227 /// \brief Return the number of times that a region of code associated with
228 /// this counter was executed.
229 ErrorOr<int64_t> evaluate(const Counter &C) const;
232 /// \brief Code coverage information for a single function.
233 struct FunctionRecord {
234 /// \brief Raw function name.
236 /// \brief Associated files.
237 std::vector<std::string> Filenames;
238 /// \brief Regions in the function along with their counts.
239 std::vector<CountedRegion> CountedRegions;
240 /// \brief The number of times this function was executed.
241 uint64_t ExecutionCount;
243 FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames,
244 uint64_t ExecutionCount)
245 : Name(Name), Filenames(Filenames.begin(), Filenames.end()),
246 ExecutionCount(ExecutionCount) {}
249 /// \brief Iterator over Functions, optionally filtered to a single file.
250 class FunctionRecordIterator
251 : public iterator_facade_base<FunctionRecordIterator,
252 std::forward_iterator_tag, FunctionRecord> {
253 ArrayRef<FunctionRecord> Records;
254 ArrayRef<FunctionRecord>::iterator Current;
257 /// \brief Skip records whose primary file is not \c Filename.
258 void skipOtherFiles();
261 FunctionRecordIterator(ArrayRef<FunctionRecord> Records_,
262 StringRef Filename = "")
263 : Records(Records_), Current(Records.begin()), Filename(Filename) {
267 FunctionRecordIterator() : Current(Records.begin()) {}
269 bool operator==(const FunctionRecordIterator &RHS) const {
270 return Current == RHS.Current && Filename == RHS.Filename;
273 const FunctionRecord &operator*() const { return *Current; }
275 FunctionRecordIterator &operator++() {
276 assert(Current != Records.end() && "incremented past end");
283 /// \brief Coverage information for a macro expansion or #included file.
285 /// When covered code has pieces that can be expanded for more detail, such as a
286 /// preprocessor macro use and its definition, these are represented as
287 /// expansions whose coverage can be looked up independently.
288 struct ExpansionRecord {
289 /// \brief The abstract file this expansion covers.
291 /// \brief The region that expands to this record.
292 const CountedRegion &Region;
293 /// \brief Coverage for the expansion.
294 const FunctionRecord &Function;
296 ExpansionRecord(const CountedRegion &Region,
297 const FunctionRecord &Function)
298 : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
301 /// \brief The execution count information starting at a point in a file.
303 /// A sequence of CoverageSegments gives execution counts for a file in format
304 /// that's simple to iterate through for processing.
305 struct CoverageSegment {
306 /// \brief The line where this segment begins.
308 /// \brief The column where this segment begins.
310 /// \brief The execution count, or zero if no count was recorded.
312 /// \brief When false, the segment was uninstrumented or skipped.
314 /// \brief Whether this enters a new region or returns to a previous count.
317 CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry)
318 : Line(Line), Col(Col), Count(0), HasCount(false),
319 IsRegionEntry(IsRegionEntry) {}
320 void setCount(uint64_t NewCount) {
324 void addCount(uint64_t NewCount) { setCount(Count + NewCount); }
327 /// \brief Coverage information to be processed or displayed.
329 /// This represents the coverage of an entire file, expansion, or function. It
330 /// provides a sequence of CoverageSegments to iterate through, as well as the
331 /// list of expansions that can be further processed.
333 std::string Filename;
334 std::vector<CoverageSegment> Segments;
335 std::vector<ExpansionRecord> Expansions;
336 friend class CoverageMapping;
341 CoverageData(StringRef Filename) : Filename(Filename) {}
343 CoverageData(CoverageData &&RHS)
344 : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
345 Expansions(std::move(RHS.Expansions)) {}
347 /// \brief Get the name of the file this data covers.
348 StringRef getFilename() { return Filename; }
350 std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
351 std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
352 bool empty() { return Segments.empty(); }
354 /// \brief Expansions that can be further processed.
355 std::vector<ExpansionRecord> getExpansions() { return Expansions; }
358 /// \brief The mapping of profile information to coverage data.
360 /// This is the main interface to get coverage information, using a profile to
361 /// fill out execution counts.
362 class CoverageMapping {
363 std::vector<FunctionRecord> Functions;
364 unsigned MismatchedFunctionCount;
366 CoverageMapping() : MismatchedFunctionCount(0) {}
369 /// \brief Load the coverage mapping using the given readers.
370 static ErrorOr<std::unique_ptr<CoverageMapping>>
371 load(ObjectFileCoverageMappingReader &CoverageReader,
372 IndexedInstrProfReader &ProfileReader);
374 /// \brief Load the coverage mapping from the given files.
375 static ErrorOr<std::unique_ptr<CoverageMapping>>
376 load(StringRef ObjectFilename, StringRef ProfileFilename);
378 /// \brief The number of functions that couldn't have their profiles mapped.
380 /// This is a count of functions whose profile is out of date or otherwise
381 /// can't be associated with any coverage information.
382 unsigned getMismatchedCount() { return MismatchedFunctionCount; }
384 /// \brief Returns the list of files that are covered.
385 std::vector<StringRef> getUniqueSourceFiles() const;
387 /// \brief Get the coverage for a particular file.
389 /// The given filename must be the name as recorded in the coverage
390 /// information. That is, only names returned from getUniqueSourceFiles will
392 CoverageData getCoverageForFile(StringRef Filename);
394 /// \brief Gets all of the functions covered by this profile.
395 iterator_range<FunctionRecordIterator> getCoveredFunctions() const {
396 return make_range(FunctionRecordIterator(Functions),
397 FunctionRecordIterator());
400 /// \brief Gets all of the functions in a particular file.
401 iterator_range<FunctionRecordIterator>
402 getCoveredFunctions(StringRef Filename) const {
403 return make_range(FunctionRecordIterator(Functions, Filename),
404 FunctionRecordIterator());
407 /// \brief Get the list of function instantiations in the file.
409 /// Fucntions that are instantiated more than once, such as C++ template
410 /// specializations, have distinct coverage records for each instantiation.
411 std::vector<const FunctionRecord *> getInstantiations(StringRef Filename);
413 /// \brief Get the coverage for a particular function.
414 CoverageData getCoverageForFunction(const FunctionRecord &Function);
416 /// \brief Get the coverage for an expansion within a coverage set.
417 CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
420 } // end namespace coverage
422 /// \brief Provide DenseMapInfo for CounterExpression
423 template<> struct DenseMapInfo<coverage::CounterExpression> {
424 static inline coverage::CounterExpression getEmptyKey() {
425 using namespace coverage;
426 return CounterExpression(CounterExpression::ExprKind::Subtract,
427 Counter::getCounter(~0U),
428 Counter::getCounter(~0U));
431 static inline coverage::CounterExpression getTombstoneKey() {
432 using namespace coverage;
433 return CounterExpression(CounterExpression::ExprKind::Add,
434 Counter::getCounter(~0U),
435 Counter::getCounter(~0U));
438 static unsigned getHashValue(const coverage::CounterExpression &V) {
439 return static_cast<unsigned>(
440 hash_combine(V.Kind, V.LHS.getKind(), V.LHS.getCounterID(),
441 V.RHS.getKind(), V.RHS.getCounterID()));
444 static bool isEqual(const coverage::CounterExpression &LHS,
445 const coverage::CounterExpression &RHS) {
446 return LHS.Kind == RHS.Kind && LHS.LHS == RHS.LHS && LHS.RHS == RHS.RHS;
451 } // end namespace llvm
453 #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_