SourceCoverageView.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. //===- SourceCoverageView.cpp - Code coverage view for source code --------===//
  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. /// \file This class implements rendering for code coverage of source code.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "SourceCoverageView.h"
  14. #include "SourceCoverageViewHTML.h"
  15. #include "SourceCoverageViewText.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/Support/FileSystem.h"
  19. #include "llvm/Support/LineIterator.h"
  20. #include "llvm/Support/Path.h"
  21. using namespace llvm;
  22. void CoveragePrinter::StreamDestructor::operator()(raw_ostream *OS) const {
  23. if (OS == &outs())
  24. return;
  25. delete OS;
  26. }
  27. std::string CoveragePrinter::getOutputPath(StringRef Path, StringRef Extension,
  28. bool InToplevel,
  29. bool Relative) const {
  30. assert(Extension.size() && "The file extension may not be empty");
  31. SmallString<256> FullPath;
  32. if (!Relative)
  33. FullPath.append(Opts.ShowOutputDirectory);
  34. if (!InToplevel)
  35. sys::path::append(FullPath, getCoverageDir());
  36. SmallString<256> ParentPath = sys::path::parent_path(Path);
  37. sys::path::remove_dots(ParentPath, /*remove_dot_dots=*/true);
  38. sys::path::append(FullPath, sys::path::relative_path(ParentPath));
  39. auto PathFilename = (sys::path::filename(Path) + "." + Extension).str();
  40. sys::path::append(FullPath, PathFilename);
  41. sys::path::native(FullPath);
  42. return FullPath.str();
  43. }
  44. Expected<CoveragePrinter::OwnedStream>
  45. CoveragePrinter::createOutputStream(StringRef Path, StringRef Extension,
  46. bool InToplevel) const {
  47. if (!Opts.hasOutputDirectory())
  48. return OwnedStream(&outs());
  49. std::string FullPath = getOutputPath(Path, Extension, InToplevel, false);
  50. auto ParentDir = sys::path::parent_path(FullPath);
  51. if (auto E = sys::fs::create_directories(ParentDir))
  52. return errorCodeToError(E);
  53. std::error_code E;
  54. raw_ostream *RawStream = new raw_fd_ostream(FullPath, E, sys::fs::F_RW);
  55. auto OS = CoveragePrinter::OwnedStream(RawStream);
  56. if (E)
  57. return errorCodeToError(E);
  58. return std::move(OS);
  59. }
  60. std::unique_ptr<CoveragePrinter>
  61. CoveragePrinter::create(const CoverageViewOptions &Opts) {
  62. switch (Opts.Format) {
  63. case CoverageViewOptions::OutputFormat::Text:
  64. return llvm::make_unique<CoveragePrinterText>(Opts);
  65. case CoverageViewOptions::OutputFormat::HTML:
  66. return llvm::make_unique<CoveragePrinterHTML>(Opts);
  67. }
  68. llvm_unreachable("Unknown coverage output format!");
  69. }
  70. LineCoverageStats::LineCoverageStats(
  71. ArrayRef<const coverage::CoverageSegment *> LineSegments,
  72. const coverage::CoverageSegment *WrappedSegment) {
  73. // Find the minimum number of regions which start in this line.
  74. unsigned MinRegionCount = 0;
  75. auto isStartOfRegion = [](const coverage::CoverageSegment *S) {
  76. return S->HasCount && S->IsRegionEntry;
  77. };
  78. for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
  79. if (isStartOfRegion(LineSegments[I]))
  80. ++MinRegionCount;
  81. ExecutionCount = 0;
  82. HasMultipleRegions = MinRegionCount > 1;
  83. Mapped = (WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0);
  84. if (!Mapped)
  85. return;
  86. // Pick the max count among regions which start and end on this line, to
  87. // avoid erroneously using the wrapped count, and to avoid picking region
  88. // counts which come from deferred regions.
  89. if (LineSegments.size() > 1) {
  90. for (unsigned I = 0; I < LineSegments.size() - 1; ++I)
  91. ExecutionCount = std::max(ExecutionCount, LineSegments[I]->Count);
  92. return;
  93. }
  94. // Just pick the maximum count.
  95. if (WrappedSegment && WrappedSegment->HasCount)
  96. ExecutionCount = WrappedSegment->Count;
  97. if (!LineSegments.empty())
  98. ExecutionCount = std::max(ExecutionCount, LineSegments[0]->Count);
  99. }
  100. unsigned SourceCoverageView::getFirstUncoveredLineNo() {
  101. auto CheckIfUncovered = [](const coverage::CoverageSegment &S) {
  102. return S.HasCount && S.Count == 0;
  103. };
  104. // L is less than R if (1) it's an uncovered segment (has a 0 count), and (2)
  105. // either R is not an uncovered segment, or L has a lower line number than R.
  106. const auto MinSegIt =
  107. std::min_element(CoverageInfo.begin(), CoverageInfo.end(),
  108. [CheckIfUncovered](const coverage::CoverageSegment &L,
  109. const coverage::CoverageSegment &R) {
  110. return (CheckIfUncovered(L) &&
  111. (!CheckIfUncovered(R) || (L.Line < R.Line)));
  112. });
  113. if (CheckIfUncovered(*MinSegIt))
  114. return (*MinSegIt).Line;
  115. // There is no uncovered line, return zero.
  116. return 0;
  117. }
  118. std::string SourceCoverageView::formatCount(uint64_t N) {
  119. std::string Number = utostr(N);
  120. int Len = Number.size();
  121. if (Len <= 3)
  122. return Number;
  123. int IntLen = Len % 3 == 0 ? 3 : Len % 3;
  124. std::string Result(Number.data(), IntLen);
  125. if (IntLen != 3) {
  126. Result.push_back('.');
  127. Result += Number.substr(IntLen, 3 - IntLen);
  128. }
  129. Result.push_back(" kMGTPEZY"[(Len - 1) / 3]);
  130. return Result;
  131. }
  132. bool SourceCoverageView::shouldRenderRegionMarkers(
  133. CoverageSegmentArray Segments) const {
  134. if (!getOptions().ShowRegionMarkers)
  135. return false;
  136. // Render the region markers if there's more than one count to show.
  137. unsigned RegionCount = 0;
  138. for (const auto *S : Segments)
  139. if (S->IsRegionEntry)
  140. if (++RegionCount > 1)
  141. return true;
  142. return false;
  143. }
  144. bool SourceCoverageView::hasSubViews() const {
  145. return !ExpansionSubViews.empty() || !InstantiationSubViews.empty();
  146. }
  147. std::unique_ptr<SourceCoverageView>
  148. SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
  149. const CoverageViewOptions &Options,
  150. coverage::CoverageData &&CoverageInfo) {
  151. switch (Options.Format) {
  152. case CoverageViewOptions::OutputFormat::Text:
  153. return llvm::make_unique<SourceCoverageViewText>(
  154. SourceName, File, Options, std::move(CoverageInfo));
  155. case CoverageViewOptions::OutputFormat::HTML:
  156. return llvm::make_unique<SourceCoverageViewHTML>(
  157. SourceName, File, Options, std::move(CoverageInfo));
  158. }
  159. llvm_unreachable("Unknown coverage output format!");
  160. }
  161. std::string SourceCoverageView::getSourceName() const {
  162. SmallString<128> SourceText(SourceName);
  163. sys::path::remove_dots(SourceText, /*remove_dot_dots=*/true);
  164. sys::path::native(SourceText);
  165. return SourceText.str();
  166. }
  167. void SourceCoverageView::addExpansion(
  168. const coverage::CounterMappingRegion &Region,
  169. std::unique_ptr<SourceCoverageView> View) {
  170. ExpansionSubViews.emplace_back(Region, std::move(View));
  171. }
  172. void SourceCoverageView::addInstantiation(
  173. StringRef FunctionName, unsigned Line,
  174. std::unique_ptr<SourceCoverageView> View) {
  175. InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View));
  176. }
  177. void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
  178. bool ShowSourceName, unsigned ViewDepth) {
  179. if (WholeFile && getOptions().hasOutputDirectory())
  180. renderTitle(OS, "Coverage Report");
  181. renderViewHeader(OS);
  182. if (ShowSourceName)
  183. renderSourceName(OS, WholeFile);
  184. renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
  185. ViewDepth);
  186. // We need the expansions and instantiations sorted so we can go through them
  187. // while we iterate lines.
  188. std::sort(ExpansionSubViews.begin(), ExpansionSubViews.end());
  189. std::sort(InstantiationSubViews.begin(), InstantiationSubViews.end());
  190. auto NextESV = ExpansionSubViews.begin();
  191. auto EndESV = ExpansionSubViews.end();
  192. auto NextISV = InstantiationSubViews.begin();
  193. auto EndISV = InstantiationSubViews.end();
  194. // Get the coverage information for the file.
  195. auto NextSegment = CoverageInfo.begin();
  196. auto EndSegment = CoverageInfo.end();
  197. unsigned FirstLine = NextSegment != EndSegment ? NextSegment->Line : 0;
  198. const coverage::CoverageSegment *WrappedSegment = nullptr;
  199. SmallVector<const coverage::CoverageSegment *, 8> LineSegments;
  200. for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof(); ++LI) {
  201. // If we aren't rendering the whole file, we need to filter out the prologue
  202. // and epilogue.
  203. if (!WholeFile) {
  204. if (NextSegment == EndSegment)
  205. break;
  206. else if (LI.line_number() < FirstLine)
  207. continue;
  208. }
  209. // Collect the coverage information relevant to this line.
  210. if (LineSegments.size())
  211. WrappedSegment = LineSegments.back();
  212. LineSegments.clear();
  213. while (NextSegment != EndSegment && NextSegment->Line == LI.line_number())
  214. LineSegments.push_back(&*NextSegment++);
  215. renderLinePrefix(OS, ViewDepth);
  216. if (getOptions().ShowLineNumbers)
  217. renderLineNumberColumn(OS, LI.line_number());
  218. LineCoverageStats LineCount{LineSegments, WrappedSegment};
  219. if (getOptions().ShowLineStats)
  220. renderLineCoverageColumn(OS, LineCount);
  221. // If there are expansion subviews, we want to highlight the first one.
  222. unsigned ExpansionColumn = 0;
  223. if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
  224. getOptions().Colors)
  225. ExpansionColumn = NextESV->getStartCol();
  226. // Display the source code for the current line.
  227. renderLine(OS, {*LI, LI.line_number()}, WrappedSegment, LineSegments,
  228. ExpansionColumn, ViewDepth);
  229. // Show the region markers.
  230. if (shouldRenderRegionMarkers(LineSegments))
  231. renderRegionMarkers(OS, LineSegments, ViewDepth);
  232. // Show the expansions and instantiations for this line.
  233. bool RenderedSubView = false;
  234. for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
  235. ++NextESV) {
  236. renderViewDivider(OS, ViewDepth + 1);
  237. // Re-render the current line and highlight the expansion range for
  238. // this subview.
  239. if (RenderedSubView) {
  240. ExpansionColumn = NextESV->getStartCol();
  241. renderExpansionSite(OS, {*LI, LI.line_number()}, WrappedSegment,
  242. LineSegments, ExpansionColumn, ViewDepth);
  243. renderViewDivider(OS, ViewDepth + 1);
  244. }
  245. renderExpansionView(OS, *NextESV, ViewDepth + 1);
  246. RenderedSubView = true;
  247. }
  248. for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
  249. renderViewDivider(OS, ViewDepth + 1);
  250. renderInstantiationView(OS, *NextISV, ViewDepth + 1);
  251. RenderedSubView = true;
  252. }
  253. if (RenderedSubView)
  254. renderViewDivider(OS, ViewDepth + 1);
  255. renderLineSuffix(OS, ViewDepth);
  256. }
  257. renderViewFooter(OS);
  258. }