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 bool operator==(const Counter &Other) const {
67 return Kind == Other.Kind && ID == Other.ID;
70 friend bool operator<(const Counter &LHS, const Counter &RHS) {
71 return std::tie(LHS.Kind, LHS.ID) < std::tie(RHS.Kind, RHS.ID);
74 /// \brief Return the counter that represents the number zero.
75 static Counter getZero() { return Counter(); }
77 /// \brief Return the counter that corresponds to a specific profile counter.
78 static Counter getCounter(unsigned CounterId) {
79 return Counter(CounterValueReference, CounterId);
82 /// \brief Return the counter that corresponds to a specific
83 /// addition counter expression.
84 static Counter getExpression(unsigned ExpressionId) {
85 return Counter(Expression, ExpressionId);
89 /// \brief A Counter expression is a value that represents an arithmetic
90 /// operation with two counters.
91 struct CounterExpression {
92 enum ExprKind { Subtract, Add };
96 CounterExpression(ExprKind Kind, Counter LHS, Counter RHS)
97 : Kind(Kind), LHS(LHS), RHS(RHS) {}
100 /// \brief A Counter expression builder is used to construct the
101 /// counter expressions. It avoids unecessary duplication
102 /// and simplifies algebraic expressions.
103 class CounterExpressionBuilder {
104 /// \brief A list of all the counter expressions
105 std::vector<CounterExpression> Expressions;
106 /// \brief A lookup table for the index of a given expression.
107 llvm::DenseMap<CounterExpression, unsigned> ExpressionIndices;
109 /// \brief Return the counter which corresponds to the given expression.
111 /// If the given expression is already stored in the builder, a counter
112 /// that references that expression is returned. Otherwise, the given
113 /// expression is added to the builder's collection of expressions.
114 Counter get(const CounterExpression &E);
116 /// \brief Gather the terms of the expression tree for processing.
118 /// This collects each addition and subtraction referenced by the counter into
119 /// a sequence that can be sorted and combined to build a simplified counter
121 void extractTerms(Counter C, int Sign,
122 SmallVectorImpl<std::pair<unsigned, int>> &Terms);
124 /// \brief Simplifies the given expression tree
125 /// by getting rid of algebraically redundant operations.
126 Counter simplify(Counter ExpressionTree);
129 ArrayRef<CounterExpression> getExpressions() const { return Expressions; }
131 /// \brief Return a counter that represents the expression
132 /// that adds LHS and RHS.
133 Counter add(Counter LHS, Counter RHS);
135 /// \brief Return a counter that represents the expression
136 /// that subtracts RHS from LHS.
137 Counter subtract(Counter LHS, Counter RHS);
140 /// \brief A Counter mapping region associates a source range with
141 /// a specific counter.
142 struct CounterMappingRegion {
144 /// \brief A CodeRegion associates some code with a counter
147 /// \brief An ExpansionRegion represents a file expansion region that
148 /// associates a source range with the expansion of a virtual source file,
149 /// such as for a macro instantiation or #include file.
152 /// \brief A SkippedRegion represents a source range with code that
153 /// was skipped by a preprocessor or similar means.
157 static const unsigned EncodingHasCodeBeforeBits = 1;
160 unsigned FileID, ExpandedFileID;
161 unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
163 /// \brief A flag that is set to true when there is already code before
164 /// this region on the same line.
165 /// This is useful to accurately compute the execution counts for a line.
168 CounterMappingRegion(Counter Count, unsigned FileID, unsigned LineStart,
169 unsigned ColumnStart, unsigned LineEnd,
170 unsigned ColumnEnd, bool HasCodeBefore = false,
171 RegionKind Kind = CodeRegion)
172 : Count(Count), FileID(FileID), ExpandedFileID(0), LineStart(LineStart),
173 ColumnStart(ColumnStart), LineEnd(LineEnd), ColumnEnd(ColumnEnd),
174 Kind(Kind), HasCodeBefore(HasCodeBefore) {}
176 inline std::pair<unsigned, unsigned> startLoc() const {
177 return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
180 inline std::pair<unsigned, unsigned> endLoc() const {
181 return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
184 bool operator<(const CounterMappingRegion &Other) const {
185 if (FileID != Other.FileID)
186 return FileID < Other.FileID;
187 return startLoc() < Other.startLoc();
190 bool contains(const CounterMappingRegion &Other) const {
191 if (FileID != Other.FileID)
193 if (startLoc() > Other.startLoc())
195 if (endLoc() < Other.endLoc())
201 /// \brief Associates a source range with an execution count.
202 struct CountedRegion : public CounterMappingRegion {
203 uint64_t ExecutionCount;
205 CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
206 : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
209 /// \brief A Counter mapping context is used to connect the counters,
210 /// expressions and the obtained counter values.
211 class CounterMappingContext {
212 ArrayRef<CounterExpression> Expressions;
213 ArrayRef<uint64_t> CounterValues;
216 CounterMappingContext(ArrayRef<CounterExpression> Expressions,
217 ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>())
218 : Expressions(Expressions), CounterValues(CounterValues) {}
220 void dump(const Counter &C, llvm::raw_ostream &OS) const;
221 void dump(const Counter &C) const { dump(C, dbgs()); }
223 /// \brief Return the number of times that a region of code associated with
224 /// this counter was executed.
225 ErrorOr<int64_t> evaluate(const Counter &C) const;
228 /// \brief Code coverage information for a single function.
229 struct FunctionRecord {
230 /// \brief Raw function name.
232 /// \brief Associated files.
233 std::vector<std::string> Filenames;
234 /// \brief Regions in the function along with their counts.
235 std::vector<CountedRegion> CountedRegions;
236 /// \brief The number of times this function was executed.
237 uint64_t ExecutionCount;
239 FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames,
240 uint64_t ExecutionCount)
241 : Name(Name), Filenames(Filenames.begin(), Filenames.end()),
242 ExecutionCount(ExecutionCount) {}
245 /// \brief Iterator over Functions, optionally filtered to a single file.
246 class FunctionRecordIterator
247 : public iterator_facade_base<FunctionRecordIterator,
248 std::forward_iterator_tag, FunctionRecord> {
249 ArrayRef<FunctionRecord> Records;
250 ArrayRef<FunctionRecord>::iterator Current;
253 /// \brief Skip records whose primary file is not \c Filename.
254 void skipOtherFiles();
257 FunctionRecordIterator(ArrayRef<FunctionRecord> Records_,
258 StringRef Filename = "")
259 : Records(Records_), Current(Records.begin()), Filename(Filename) {
263 FunctionRecordIterator() : Current(Records.begin()) {}
265 bool operator==(const FunctionRecordIterator &RHS) const {
266 return Current == RHS.Current && Filename == RHS.Filename;
269 const FunctionRecord &operator*() const { return *Current; }
271 FunctionRecordIterator &operator++() {
272 assert(Current != Records.end() && "incremented past end");
279 /// \brief Coverage information for a macro expansion or #included file.
281 /// When covered code has pieces that can be expanded for more detail, such as a
282 /// preprocessor macro use and its definition, these are represented as
283 /// expansions whose coverage can be looked up independently.
284 struct ExpansionRecord {
285 /// \brief The abstract file this expansion covers.
287 /// \brief The region that expands to this record.
288 const CountedRegion &Region;
289 /// \brief Coverage for the expansion.
290 const FunctionRecord &Function;
292 ExpansionRecord(const CountedRegion &Region,
293 const FunctionRecord &Function)
294 : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
297 /// \brief The execution count information starting at a point in a file.
299 /// A sequence of CoverageSegments gives execution counts for a file in format
300 /// that's simple to iterate through for processing.
301 struct CoverageSegment {
302 /// \brief The line where this segment begins.
304 /// \brief The column where this segment begins.
306 /// \brief The execution count, or zero if no count was recorded.
308 /// \brief When false, the segment was uninstrumented or skipped.
310 /// \brief Whether this enters a new region or returns to a previous count.
313 CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry)
314 : Line(Line), Col(Col), Count(0), HasCount(false),
315 IsRegionEntry(IsRegionEntry) {}
316 void setCount(uint64_t NewCount) {
320 void addCount(uint64_t NewCount) { setCount(Count + NewCount); }
323 /// \brief Coverage information to be processed or displayed.
325 /// This represents the coverage of an entire file, expansion, or function. It
326 /// provides a sequence of CoverageSegments to iterate through, as well as the
327 /// list of expansions that can be further processed.
329 std::string Filename;
330 std::vector<CoverageSegment> Segments;
331 std::vector<ExpansionRecord> Expansions;
332 friend class CoverageMapping;
337 CoverageData(StringRef Filename) : Filename(Filename) {}
339 CoverageData(CoverageData &&RHS)
340 : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
341 Expansions(std::move(RHS.Expansions)) {}
343 /// \brief Get the name of the file this data covers.
344 StringRef getFilename() { return Filename; }
346 std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
347 std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
348 bool empty() { return Segments.empty(); }
350 /// \brief Expansions that can be further processed.
351 std::vector<ExpansionRecord> getExpansions() { return Expansions; }
354 /// \brief The mapping of profile information to coverage data.
356 /// This is the main interface to get coverage information, using a profile to
357 /// fill out execution counts.
358 class CoverageMapping {
359 std::vector<FunctionRecord> Functions;
360 unsigned MismatchedFunctionCount;
362 CoverageMapping() : MismatchedFunctionCount(0) {}
365 /// \brief Load the coverage mapping using the given readers.
366 static ErrorOr<std::unique_ptr<CoverageMapping>>
367 load(ObjectFileCoverageMappingReader &CoverageReader,
368 IndexedInstrProfReader &ProfileReader);
370 /// \brief Load the coverage mapping from the given files.
371 static ErrorOr<std::unique_ptr<CoverageMapping>>
372 load(StringRef ObjectFilename, StringRef ProfileFilename);
374 /// \brief The number of functions that couldn't have their profiles mapped.
376 /// This is a count of functions whose profile is out of date or otherwise
377 /// can't be associated with any coverage information.
378 unsigned getMismatchedCount() { return MismatchedFunctionCount; }
380 /// \brief Returns the list of files that are covered.
381 std::vector<StringRef> getUniqueSourceFiles() const;
383 /// \brief Get the coverage for a particular file.
385 /// The given filename must be the name as recorded in the coverage
386 /// information. That is, only names returned from getUniqueSourceFiles will
388 CoverageData getCoverageForFile(StringRef Filename);
390 /// \brief Gets all of the functions covered by this profile.
391 iterator_range<FunctionRecordIterator> getCoveredFunctions() const {
392 return make_range(FunctionRecordIterator(Functions),
393 FunctionRecordIterator());
396 /// \brief Gets all of the functions in a particular file.
397 iterator_range<FunctionRecordIterator>
398 getCoveredFunctions(StringRef Filename) const {
399 return make_range(FunctionRecordIterator(Functions, Filename),
400 FunctionRecordIterator());
403 /// \brief Get the list of function instantiations in the file.
405 /// Fucntions that are instantiated more than once, such as C++ template
406 /// specializations, have distinct coverage records for each instantiation.
407 std::vector<const FunctionRecord *> getInstantiations(StringRef Filename);
409 /// \brief Get the coverage for a particular function.
410 CoverageData getCoverageForFunction(const FunctionRecord &Function);
412 /// \brief Get the coverage for an expansion within a coverage set.
413 CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
416 } // end namespace coverage
418 /// \brief Provide DenseMapInfo for CounterExpression
419 template<> struct DenseMapInfo<coverage::CounterExpression> {
420 static inline coverage::CounterExpression getEmptyKey() {
421 using namespace coverage;
422 return CounterExpression(CounterExpression::ExprKind::Subtract,
423 Counter::getCounter(~0U),
424 Counter::getCounter(~0U));
427 static inline coverage::CounterExpression getTombstoneKey() {
428 using namespace coverage;
429 return CounterExpression(CounterExpression::ExprKind::Add,
430 Counter::getCounter(~0U),
431 Counter::getCounter(~0U));
434 static unsigned getHashValue(const coverage::CounterExpression &V) {
435 return static_cast<unsigned>(
436 hash_combine(V.Kind, V.LHS.getKind(), V.LHS.getCounterID(),
437 V.RHS.getKind(), V.RHS.getCounterID()));
440 static bool isEqual(const coverage::CounterExpression &LHS,
441 const coverage::CounterExpression &RHS) {
442 return LHS.Kind == RHS.Kind && LHS.LHS == RHS.LHS && LHS.RHS == RHS.RHS;
447 } // end namespace llvm
449 #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_