CoverageMapping.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. //=-- CoverageMapping.h - 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. // Code coverage mapping data is generated by clang and read by
  11. // llvm-cov to show code coverage statistics for a file.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_PROFILEDATA_COVERAGEMAPPING_H_
  15. #define LLVM_PROFILEDATA_COVERAGEMAPPING_H_
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/Hashing.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/ADT/iterator.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/ErrorOr.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include <system_error>
  25. #include <tuple>
  26. namespace llvm {
  27. class IndexedInstrProfReader;
  28. namespace coverage {
  29. class CoverageMappingReader;
  30. class CoverageMapping;
  31. struct CounterExpressions;
  32. enum CoverageMappingVersion { CoverageMappingVersion1 };
  33. /// \brief A Counter is an abstract value that describes how to compute the
  34. /// execution count for a region of code using the collected profile count data.
  35. struct Counter {
  36. enum CounterKind { Zero, CounterValueReference, Expression };
  37. static const unsigned EncodingTagBits = 2;
  38. static const unsigned EncodingTagMask = 0x3;
  39. static const unsigned EncodingCounterTagAndExpansionRegionTagBits =
  40. EncodingTagBits + 1;
  41. private:
  42. CounterKind Kind;
  43. unsigned ID;
  44. Counter(CounterKind Kind, unsigned ID) : Kind(Kind), ID(ID) {}
  45. public:
  46. Counter() : Kind(Zero), ID(0) {}
  47. CounterKind getKind() const { return Kind; }
  48. bool isZero() const { return Kind == Zero; }
  49. bool isExpression() const { return Kind == Expression; }
  50. unsigned getCounterID() const { return ID; }
  51. unsigned getExpressionID() const { return ID; }
  52. friend bool operator==(const Counter &LHS, const Counter &RHS) {
  53. return LHS.Kind == RHS.Kind && LHS.ID == RHS.ID;
  54. }
  55. friend bool operator!=(const Counter &LHS, const Counter &RHS) {
  56. return !(LHS == RHS);
  57. }
  58. friend bool operator<(const Counter &LHS, const Counter &RHS) {
  59. return std::tie(LHS.Kind, LHS.ID) < std::tie(RHS.Kind, RHS.ID);
  60. }
  61. /// \brief Return the counter that represents the number zero.
  62. static Counter getZero() { return Counter(); }
  63. /// \brief Return the counter that corresponds to a specific profile counter.
  64. static Counter getCounter(unsigned CounterId) {
  65. return Counter(CounterValueReference, CounterId);
  66. }
  67. /// \brief Return the counter that corresponds to a specific
  68. /// addition counter expression.
  69. static Counter getExpression(unsigned ExpressionId) {
  70. return Counter(Expression, ExpressionId);
  71. }
  72. };
  73. /// \brief A Counter expression is a value that represents an arithmetic
  74. /// operation with two counters.
  75. struct CounterExpression {
  76. enum ExprKind { Subtract, Add };
  77. ExprKind Kind;
  78. Counter LHS, RHS;
  79. CounterExpression(ExprKind Kind, Counter LHS, Counter RHS)
  80. : Kind(Kind), LHS(LHS), RHS(RHS) {}
  81. };
  82. /// \brief A Counter expression builder is used to construct the
  83. /// counter expressions. It avoids unecessary duplication
  84. /// and simplifies algebraic expressions.
  85. class CounterExpressionBuilder {
  86. /// \brief A list of all the counter expressions
  87. std::vector<CounterExpression> Expressions;
  88. /// \brief A lookup table for the index of a given expression.
  89. llvm::DenseMap<CounterExpression, unsigned> ExpressionIndices;
  90. /// \brief Return the counter which corresponds to the given expression.
  91. ///
  92. /// If the given expression is already stored in the builder, a counter
  93. /// that references that expression is returned. Otherwise, the given
  94. /// expression is added to the builder's collection of expressions.
  95. Counter get(const CounterExpression &E);
  96. /// \brief Gather the terms of the expression tree for processing.
  97. ///
  98. /// This collects each addition and subtraction referenced by the counter into
  99. /// a sequence that can be sorted and combined to build a simplified counter
  100. /// expression.
  101. void extractTerms(Counter C, int Sign,
  102. SmallVectorImpl<std::pair<unsigned, int>> &Terms);
  103. /// \brief Simplifies the given expression tree
  104. /// by getting rid of algebraically redundant operations.
  105. Counter simplify(Counter ExpressionTree);
  106. public:
  107. ArrayRef<CounterExpression> getExpressions() const { return Expressions; }
  108. /// \brief Return a counter that represents the expression
  109. /// that adds LHS and RHS.
  110. Counter add(Counter LHS, Counter RHS);
  111. /// \brief Return a counter that represents the expression
  112. /// that subtracts RHS from LHS.
  113. Counter subtract(Counter LHS, Counter RHS);
  114. };
  115. /// \brief A Counter mapping region associates a source range with
  116. /// a specific counter.
  117. struct CounterMappingRegion {
  118. enum RegionKind {
  119. /// \brief A CodeRegion associates some code with a counter
  120. CodeRegion,
  121. /// \brief An ExpansionRegion represents a file expansion region that
  122. /// associates a source range with the expansion of a virtual source file,
  123. /// such as for a macro instantiation or #include file.
  124. ExpansionRegion,
  125. /// \brief A SkippedRegion represents a source range with code that
  126. /// was skipped by a preprocessor or similar means.
  127. SkippedRegion
  128. };
  129. Counter Count;
  130. unsigned FileID, ExpandedFileID;
  131. unsigned LineStart, ColumnStart, LineEnd, ColumnEnd;
  132. RegionKind Kind;
  133. CounterMappingRegion(Counter Count, unsigned FileID, unsigned ExpandedFileID,
  134. unsigned LineStart, unsigned ColumnStart,
  135. unsigned LineEnd, unsigned ColumnEnd, RegionKind Kind)
  136. : Count(Count), FileID(FileID), ExpandedFileID(ExpandedFileID),
  137. LineStart(LineStart), ColumnStart(ColumnStart), LineEnd(LineEnd),
  138. ColumnEnd(ColumnEnd), Kind(Kind) {}
  139. static CounterMappingRegion
  140. makeRegion(Counter Count, unsigned FileID, unsigned LineStart,
  141. unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd) {
  142. return CounterMappingRegion(Count, FileID, 0, LineStart, ColumnStart,
  143. LineEnd, ColumnEnd, CodeRegion);
  144. }
  145. static CounterMappingRegion
  146. makeExpansion(unsigned FileID, unsigned ExpandedFileID, unsigned LineStart,
  147. unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd) {
  148. return CounterMappingRegion(Counter(), FileID, ExpandedFileID, LineStart,
  149. ColumnStart, LineEnd, ColumnEnd,
  150. ExpansionRegion);
  151. }
  152. static CounterMappingRegion
  153. makeSkipped(unsigned FileID, unsigned LineStart, unsigned ColumnStart,
  154. unsigned LineEnd, unsigned ColumnEnd) {
  155. return CounterMappingRegion(Counter(), FileID, 0, LineStart, ColumnStart,
  156. LineEnd, ColumnEnd, SkippedRegion);
  157. }
  158. inline std::pair<unsigned, unsigned> startLoc() const {
  159. return std::pair<unsigned, unsigned>(LineStart, ColumnStart);
  160. }
  161. inline std::pair<unsigned, unsigned> endLoc() const {
  162. return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd);
  163. }
  164. bool operator<(const CounterMappingRegion &Other) const {
  165. if (FileID != Other.FileID)
  166. return FileID < Other.FileID;
  167. return startLoc() < Other.startLoc();
  168. }
  169. bool contains(const CounterMappingRegion &Other) const {
  170. if (FileID != Other.FileID)
  171. return false;
  172. if (startLoc() > Other.startLoc())
  173. return false;
  174. if (endLoc() < Other.endLoc())
  175. return false;
  176. return true;
  177. }
  178. };
  179. /// \brief Associates a source range with an execution count.
  180. struct CountedRegion : public CounterMappingRegion {
  181. uint64_t ExecutionCount;
  182. CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount)
  183. : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {}
  184. };
  185. /// \brief A Counter mapping context is used to connect the counters,
  186. /// expressions and the obtained counter values.
  187. class CounterMappingContext {
  188. ArrayRef<CounterExpression> Expressions;
  189. ArrayRef<uint64_t> CounterValues;
  190. public:
  191. CounterMappingContext(ArrayRef<CounterExpression> Expressions,
  192. ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>())
  193. : Expressions(Expressions), CounterValues(CounterValues) {}
  194. void setCounts(ArrayRef<uint64_t> Counts) { CounterValues = Counts; }
  195. void dump(const Counter &C, llvm::raw_ostream &OS) const;
  196. void dump(const Counter &C) const { dump(C, dbgs()); }
  197. /// \brief Return the number of times that a region of code associated with
  198. /// this counter was executed.
  199. ErrorOr<int64_t> evaluate(const Counter &C) const;
  200. };
  201. /// \brief Code coverage information for a single function.
  202. struct FunctionRecord {
  203. /// \brief Raw function name.
  204. std::string Name;
  205. /// \brief Associated files.
  206. std::vector<std::string> Filenames;
  207. /// \brief Regions in the function along with their counts.
  208. std::vector<CountedRegion> CountedRegions;
  209. /// \brief The number of times this function was executed.
  210. uint64_t ExecutionCount;
  211. FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames)
  212. : Name(Name), Filenames(Filenames.begin(), Filenames.end()) {}
  213. void pushRegion(CounterMappingRegion Region, uint64_t Count) {
  214. if (CountedRegions.empty())
  215. ExecutionCount = Count;
  216. CountedRegions.emplace_back(Region, Count);
  217. }
  218. };
  219. /// \brief Iterator over Functions, optionally filtered to a single file.
  220. class FunctionRecordIterator
  221. : public iterator_facade_base<FunctionRecordIterator,
  222. std::forward_iterator_tag, FunctionRecord> {
  223. ArrayRef<FunctionRecord> Records;
  224. ArrayRef<FunctionRecord>::iterator Current;
  225. StringRef Filename;
  226. /// \brief Skip records whose primary file is not \c Filename.
  227. void skipOtherFiles();
  228. public:
  229. FunctionRecordIterator(ArrayRef<FunctionRecord> Records_,
  230. StringRef Filename = "")
  231. : Records(Records_), Current(Records.begin()), Filename(Filename) {
  232. skipOtherFiles();
  233. }
  234. FunctionRecordIterator() : Current(Records.begin()) {}
  235. bool operator==(const FunctionRecordIterator &RHS) const {
  236. return Current == RHS.Current && Filename == RHS.Filename;
  237. }
  238. const FunctionRecord &operator*() const { return *Current; }
  239. FunctionRecordIterator &operator++() {
  240. assert(Current != Records.end() && "incremented past end");
  241. ++Current;
  242. skipOtherFiles();
  243. return *this;
  244. }
  245. };
  246. /// \brief Coverage information for a macro expansion or #included file.
  247. ///
  248. /// When covered code has pieces that can be expanded for more detail, such as a
  249. /// preprocessor macro use and its definition, these are represented as
  250. /// expansions whose coverage can be looked up independently.
  251. struct ExpansionRecord {
  252. /// \brief The abstract file this expansion covers.
  253. unsigned FileID;
  254. /// \brief The region that expands to this record.
  255. const CountedRegion &Region;
  256. /// \brief Coverage for the expansion.
  257. const FunctionRecord &Function;
  258. ExpansionRecord(const CountedRegion &Region,
  259. const FunctionRecord &Function)
  260. : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {}
  261. };
  262. /// \brief The execution count information starting at a point in a file.
  263. ///
  264. /// A sequence of CoverageSegments gives execution counts for a file in format
  265. /// that's simple to iterate through for processing.
  266. struct CoverageSegment {
  267. /// \brief The line where this segment begins.
  268. unsigned Line;
  269. /// \brief The column where this segment begins.
  270. unsigned Col;
  271. /// \brief The execution count, or zero if no count was recorded.
  272. uint64_t Count;
  273. /// \brief When false, the segment was uninstrumented or skipped.
  274. bool HasCount;
  275. /// \brief Whether this enters a new region or returns to a previous count.
  276. bool IsRegionEntry;
  277. CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry)
  278. : Line(Line), Col(Col), Count(0), HasCount(false),
  279. IsRegionEntry(IsRegionEntry) {}
  280. CoverageSegment(unsigned Line, unsigned Col, uint64_t Count,
  281. bool IsRegionEntry)
  282. : Line(Line), Col(Col), Count(Count), HasCount(true),
  283. IsRegionEntry(IsRegionEntry) {}
  284. friend bool operator==(const CoverageSegment &L, const CoverageSegment &R) {
  285. return std::tie(L.Line, L.Col, L.Count, L.HasCount, L.IsRegionEntry) ==
  286. std::tie(R.Line, R.Col, R.Count, R.HasCount, R.IsRegionEntry);
  287. }
  288. void setCount(uint64_t NewCount) {
  289. Count = NewCount;
  290. HasCount = true;
  291. }
  292. void addCount(uint64_t NewCount) { setCount(Count + NewCount); }
  293. };
  294. /// \brief Coverage information to be processed or displayed.
  295. ///
  296. /// This represents the coverage of an entire file, expansion, or function. It
  297. /// provides a sequence of CoverageSegments to iterate through, as well as the
  298. /// list of expansions that can be further processed.
  299. class CoverageData {
  300. std::string Filename;
  301. std::vector<CoverageSegment> Segments;
  302. std::vector<ExpansionRecord> Expansions;
  303. friend class CoverageMapping;
  304. public:
  305. CoverageData() {}
  306. CoverageData(StringRef Filename) : Filename(Filename) {}
  307. CoverageData(CoverageData &&RHS)
  308. : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)),
  309. Expansions(std::move(RHS.Expansions)) {}
  310. /// \brief Get the name of the file this data covers.
  311. StringRef getFilename() { return Filename; }
  312. std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); }
  313. std::vector<CoverageSegment>::iterator end() { return Segments.end(); }
  314. bool empty() { return Segments.empty(); }
  315. /// \brief Expansions that can be further processed.
  316. std::vector<ExpansionRecord> getExpansions() { return Expansions; }
  317. };
  318. /// \brief The mapping of profile information to coverage data.
  319. ///
  320. /// This is the main interface to get coverage information, using a profile to
  321. /// fill out execution counts.
  322. class CoverageMapping {
  323. std::vector<FunctionRecord> Functions;
  324. unsigned MismatchedFunctionCount;
  325. CoverageMapping() : MismatchedFunctionCount(0) {}
  326. public:
  327. /// \brief Load the coverage mapping using the given readers.
  328. static ErrorOr<std::unique_ptr<CoverageMapping>>
  329. load(CoverageMappingReader &CoverageReader,
  330. IndexedInstrProfReader &ProfileReader);
  331. /// \brief Load the coverage mapping from the given files.
  332. static ErrorOr<std::unique_ptr<CoverageMapping>>
  333. load(StringRef ObjectFilename, StringRef ProfileFilename,
  334. StringRef Arch = StringRef());
  335. /// \brief The number of functions that couldn't have their profiles mapped.
  336. ///
  337. /// This is a count of functions whose profile is out of date or otherwise
  338. /// can't be associated with any coverage information.
  339. unsigned getMismatchedCount() { return MismatchedFunctionCount; }
  340. /// \brief Returns the list of files that are covered.
  341. std::vector<StringRef> getUniqueSourceFiles() const;
  342. /// \brief Get the coverage for a particular file.
  343. ///
  344. /// The given filename must be the name as recorded in the coverage
  345. /// information. That is, only names returned from getUniqueSourceFiles will
  346. /// yield a result.
  347. CoverageData getCoverageForFile(StringRef Filename);
  348. /// \brief Gets all of the functions covered by this profile.
  349. iterator_range<FunctionRecordIterator> getCoveredFunctions() const {
  350. return make_range(FunctionRecordIterator(Functions),
  351. FunctionRecordIterator());
  352. }
  353. /// \brief Gets all of the functions in a particular file.
  354. iterator_range<FunctionRecordIterator>
  355. getCoveredFunctions(StringRef Filename) const {
  356. return make_range(FunctionRecordIterator(Functions, Filename),
  357. FunctionRecordIterator());
  358. }
  359. /// \brief Get the list of function instantiations in the file.
  360. ///
  361. /// Fucntions that are instantiated more than once, such as C++ template
  362. /// specializations, have distinct coverage records for each instantiation.
  363. std::vector<const FunctionRecord *> getInstantiations(StringRef Filename);
  364. /// \brief Get the coverage for a particular function.
  365. CoverageData getCoverageForFunction(const FunctionRecord &Function);
  366. /// \brief Get the coverage for an expansion within a coverage set.
  367. CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion);
  368. };
  369. } // end namespace coverage
  370. /// \brief Provide DenseMapInfo for CounterExpression
  371. template<> struct DenseMapInfo<coverage::CounterExpression> {
  372. static inline coverage::CounterExpression getEmptyKey() {
  373. using namespace coverage;
  374. return CounterExpression(CounterExpression::ExprKind::Subtract,
  375. Counter::getCounter(~0U),
  376. Counter::getCounter(~0U));
  377. }
  378. static inline coverage::CounterExpression getTombstoneKey() {
  379. using namespace coverage;
  380. return CounterExpression(CounterExpression::ExprKind::Add,
  381. Counter::getCounter(~0U),
  382. Counter::getCounter(~0U));
  383. }
  384. static unsigned getHashValue(const coverage::CounterExpression &V) {
  385. return static_cast<unsigned>(
  386. hash_combine(V.Kind, V.LHS.getKind(), V.LHS.getCounterID(),
  387. V.RHS.getKind(), V.RHS.getCounterID()));
  388. }
  389. static bool isEqual(const coverage::CounterExpression &LHS,
  390. const coverage::CounterExpression &RHS) {
  391. return LHS.Kind == RHS.Kind && LHS.LHS == RHS.LHS && LHS.RHS == RHS.RHS;
  392. }
  393. };
  394. const std::error_category &coveragemap_category();
  395. enum class coveragemap_error {
  396. success = 0,
  397. eof,
  398. no_data_found,
  399. unsupported_version,
  400. truncated,
  401. malformed
  402. };
  403. inline std::error_code make_error_code(coveragemap_error E) {
  404. return std::error_code(static_cast<int>(E), coveragemap_category());
  405. }
  406. } // end namespace llvm
  407. namespace std {
  408. template <>
  409. struct is_error_code_enum<llvm::coveragemap_error> : std::true_type {};
  410. }
  411. #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_