CoverageMappingWriter.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. //===- CoverageMappingWriter.cpp - Code coverage mapping writer -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for writing coverage mapping data for
  10. // instrumentation based coverage.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ProfileData/InstrProf.h"
  14. #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Support/Compression.h"
  18. #include "llvm/Support/LEB128.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include <algorithm>
  21. #include <cassert>
  22. #include <limits>
  23. #include <vector>
  24. using namespace llvm;
  25. using namespace coverage;
  26. CoverageFilenamesSectionWriter::CoverageFilenamesSectionWriter(
  27. ArrayRef<std::string> Filenames)
  28. : Filenames(Filenames) {
  29. #ifndef NDEBUG
  30. StringSet<> NameSet;
  31. for (StringRef Name : Filenames)
  32. assert(NameSet.insert(Name).second && "Duplicate filename");
  33. #endif
  34. }
  35. void CoverageFilenamesSectionWriter::write(raw_ostream &OS, bool Compress) {
  36. std::string FilenamesStr;
  37. {
  38. raw_string_ostream FilenamesOS{FilenamesStr};
  39. for (const auto &Filename : Filenames) {
  40. encodeULEB128(Filename.size(), FilenamesOS);
  41. FilenamesOS << Filename;
  42. }
  43. }
  44. SmallString<128> CompressedStr;
  45. bool doCompression =
  46. Compress && zlib::isAvailable() && DoInstrProfNameCompression;
  47. if (doCompression) {
  48. auto E =
  49. zlib::compress(FilenamesStr, CompressedStr, zlib::BestSizeCompression);
  50. if (E)
  51. report_bad_alloc_error("Failed to zlib compress coverage data");
  52. }
  53. // ::= <num-filenames>
  54. // <uncompressed-len>
  55. // <compressed-len-or-zero>
  56. // (<compressed-filenames> | <uncompressed-filenames>)
  57. encodeULEB128(Filenames.size(), OS);
  58. encodeULEB128(FilenamesStr.size(), OS);
  59. encodeULEB128(doCompression ? CompressedStr.size() : 0U, OS);
  60. OS << (doCompression ? CompressedStr.str() : StringRef(FilenamesStr));
  61. }
  62. namespace {
  63. /// Gather only the expressions that are used by the mapping
  64. /// regions in this function.
  65. class CounterExpressionsMinimizer {
  66. ArrayRef<CounterExpression> Expressions;
  67. SmallVector<CounterExpression, 16> UsedExpressions;
  68. std::vector<unsigned> AdjustedExpressionIDs;
  69. public:
  70. CounterExpressionsMinimizer(ArrayRef<CounterExpression> Expressions,
  71. ArrayRef<CounterMappingRegion> MappingRegions)
  72. : Expressions(Expressions) {
  73. AdjustedExpressionIDs.resize(Expressions.size(), 0);
  74. for (const auto &I : MappingRegions) {
  75. mark(I.Count);
  76. mark(I.FalseCount);
  77. }
  78. for (const auto &I : MappingRegions) {
  79. gatherUsed(I.Count);
  80. gatherUsed(I.FalseCount);
  81. }
  82. }
  83. void mark(Counter C) {
  84. if (!C.isExpression())
  85. return;
  86. unsigned ID = C.getExpressionID();
  87. AdjustedExpressionIDs[ID] = 1;
  88. mark(Expressions[ID].LHS);
  89. mark(Expressions[ID].RHS);
  90. }
  91. void gatherUsed(Counter C) {
  92. if (!C.isExpression() || !AdjustedExpressionIDs[C.getExpressionID()])
  93. return;
  94. AdjustedExpressionIDs[C.getExpressionID()] = UsedExpressions.size();
  95. const auto &E = Expressions[C.getExpressionID()];
  96. UsedExpressions.push_back(E);
  97. gatherUsed(E.LHS);
  98. gatherUsed(E.RHS);
  99. }
  100. ArrayRef<CounterExpression> getExpressions() const { return UsedExpressions; }
  101. /// Adjust the given counter to correctly transition from the old
  102. /// expression ids to the new expression ids.
  103. Counter adjust(Counter C) const {
  104. if (C.isExpression())
  105. C = Counter::getExpression(AdjustedExpressionIDs[C.getExpressionID()]);
  106. return C;
  107. }
  108. };
  109. } // end anonymous namespace
  110. /// Encode the counter.
  111. ///
  112. /// The encoding uses the following format:
  113. /// Low 2 bits - Tag:
  114. /// Counter::Zero(0) - A Counter with kind Counter::Zero
  115. /// Counter::CounterValueReference(1) - A counter with kind
  116. /// Counter::CounterValueReference
  117. /// Counter::Expression(2) + CounterExpression::Subtract(0) -
  118. /// A counter with kind Counter::Expression and an expression
  119. /// with kind CounterExpression::Subtract
  120. /// Counter::Expression(2) + CounterExpression::Add(1) -
  121. /// A counter with kind Counter::Expression and an expression
  122. /// with kind CounterExpression::Add
  123. /// Remaining bits - Counter/Expression ID.
  124. static unsigned encodeCounter(ArrayRef<CounterExpression> Expressions,
  125. Counter C) {
  126. unsigned Tag = unsigned(C.getKind());
  127. if (C.isExpression())
  128. Tag += Expressions[C.getExpressionID()].Kind;
  129. unsigned ID = C.getCounterID();
  130. assert(ID <=
  131. (std::numeric_limits<unsigned>::max() >> Counter::EncodingTagBits));
  132. return Tag | (ID << Counter::EncodingTagBits);
  133. }
  134. static void writeCounter(ArrayRef<CounterExpression> Expressions, Counter C,
  135. raw_ostream &OS) {
  136. encodeULEB128(encodeCounter(Expressions, C), OS);
  137. }
  138. void CoverageMappingWriter::write(raw_ostream &OS) {
  139. // Check that we don't have any bogus regions.
  140. assert(all_of(MappingRegions,
  141. [](const CounterMappingRegion &CMR) {
  142. return CMR.startLoc() <= CMR.endLoc();
  143. }) &&
  144. "Source region does not begin before it ends");
  145. // Sort the regions in an ascending order by the file id and the starting
  146. // location. Sort by region kinds to ensure stable order for tests.
  147. llvm::stable_sort(MappingRegions, [](const CounterMappingRegion &LHS,
  148. const CounterMappingRegion &RHS) {
  149. if (LHS.FileID != RHS.FileID)
  150. return LHS.FileID < RHS.FileID;
  151. if (LHS.startLoc() != RHS.startLoc())
  152. return LHS.startLoc() < RHS.startLoc();
  153. return LHS.Kind < RHS.Kind;
  154. });
  155. // Write out the fileid -> filename mapping.
  156. encodeULEB128(VirtualFileMapping.size(), OS);
  157. for (const auto &FileID : VirtualFileMapping)
  158. encodeULEB128(FileID, OS);
  159. // Write out the expressions.
  160. CounterExpressionsMinimizer Minimizer(Expressions, MappingRegions);
  161. auto MinExpressions = Minimizer.getExpressions();
  162. encodeULEB128(MinExpressions.size(), OS);
  163. for (const auto &E : MinExpressions) {
  164. writeCounter(MinExpressions, Minimizer.adjust(E.LHS), OS);
  165. writeCounter(MinExpressions, Minimizer.adjust(E.RHS), OS);
  166. }
  167. // Write out the mapping regions.
  168. // Split the regions into subarrays where each region in a
  169. // subarray has a fileID which is the index of that subarray.
  170. unsigned PrevLineStart = 0;
  171. unsigned CurrentFileID = ~0U;
  172. for (auto I = MappingRegions.begin(), E = MappingRegions.end(); I != E; ++I) {
  173. if (I->FileID != CurrentFileID) {
  174. // Ensure that all file ids have at least one mapping region.
  175. assert(I->FileID == (CurrentFileID + 1));
  176. // Find the number of regions with this file id.
  177. unsigned RegionCount = 1;
  178. for (auto J = I + 1; J != E && I->FileID == J->FileID; ++J)
  179. ++RegionCount;
  180. // Start a new region sub-array.
  181. encodeULEB128(RegionCount, OS);
  182. CurrentFileID = I->FileID;
  183. PrevLineStart = 0;
  184. }
  185. Counter Count = Minimizer.adjust(I->Count);
  186. Counter FalseCount = Minimizer.adjust(I->FalseCount);
  187. switch (I->Kind) {
  188. case CounterMappingRegion::CodeRegion:
  189. case CounterMappingRegion::GapRegion:
  190. writeCounter(MinExpressions, Count, OS);
  191. break;
  192. case CounterMappingRegion::ExpansionRegion: {
  193. assert(Count.isZero());
  194. assert(I->ExpandedFileID <=
  195. (std::numeric_limits<unsigned>::max() >>
  196. Counter::EncodingCounterTagAndExpansionRegionTagBits));
  197. // Mark an expansion region with a set bit that follows the counter tag,
  198. // and pack the expanded file id into the remaining bits.
  199. unsigned EncodedTagExpandedFileID =
  200. (1 << Counter::EncodingTagBits) |
  201. (I->ExpandedFileID
  202. << Counter::EncodingCounterTagAndExpansionRegionTagBits);
  203. encodeULEB128(EncodedTagExpandedFileID, OS);
  204. break;
  205. }
  206. case CounterMappingRegion::SkippedRegion:
  207. assert(Count.isZero());
  208. encodeULEB128(unsigned(I->Kind)
  209. << Counter::EncodingCounterTagAndExpansionRegionTagBits,
  210. OS);
  211. break;
  212. case CounterMappingRegion::BranchRegion:
  213. encodeULEB128(unsigned(I->Kind)
  214. << Counter::EncodingCounterTagAndExpansionRegionTagBits,
  215. OS);
  216. writeCounter(MinExpressions, Count, OS);
  217. writeCounter(MinExpressions, FalseCount, OS);
  218. break;
  219. }
  220. assert(I->LineStart >= PrevLineStart);
  221. encodeULEB128(I->LineStart - PrevLineStart, OS);
  222. encodeULEB128(I->ColumnStart, OS);
  223. assert(I->LineEnd >= I->LineStart);
  224. encodeULEB128(I->LineEnd - I->LineStart, OS);
  225. encodeULEB128(I->ColumnEnd, OS);
  226. PrevLineStart = I->LineStart;
  227. }
  228. // Ensure that all file ids have at least one mapping region.
  229. assert(CurrentFileID == (VirtualFileMapping.size() - 1));
  230. }