CodeCoverage.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===//
  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. // The 'CodeCoverageTool' class implements a command line tool to analyze and
  11. // report coverage information using the profiling instrumentation and code
  12. // coverage mapping.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CoverageFilters.h"
  16. #include "CoverageReport.h"
  17. #include "CoverageViewOptions.h"
  18. #include "RenderingSupport.h"
  19. #include "SourceCoverageView.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Triple.h"
  23. #include "llvm/ProfileData/Coverage/CoverageMapping.h"
  24. #include "llvm/ProfileData/InstrProfReader.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/Format.h"
  28. #include "llvm/Support/Path.h"
  29. #include "llvm/Support/Process.h"
  30. #include <functional>
  31. #include <system_error>
  32. using namespace llvm;
  33. using namespace coverage;
  34. namespace {
  35. /// \brief The implementation of the coverage tool.
  36. class CodeCoverageTool {
  37. public:
  38. enum Command {
  39. /// \brief The show command.
  40. Show,
  41. /// \brief The report command.
  42. Report
  43. };
  44. /// \brief Print the error message to the error output stream.
  45. void error(const Twine &Message, StringRef Whence = "");
  46. /// \brief Append a reference to a private copy of \p Path into SourceFiles.
  47. void addCollectedPath(const std::string &Path);
  48. /// \brief Return a memory buffer for the given source file.
  49. ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
  50. /// \brief Create source views for the expansions of the view.
  51. void attachExpansionSubViews(SourceCoverageView &View,
  52. ArrayRef<ExpansionRecord> Expansions,
  53. CoverageMapping &Coverage);
  54. /// \brief Create the source view of a particular function.
  55. std::unique_ptr<SourceCoverageView>
  56. createFunctionView(const FunctionRecord &Function, CoverageMapping &Coverage);
  57. /// \brief Create the main source view of a particular source file.
  58. std::unique_ptr<SourceCoverageView>
  59. createSourceFileView(StringRef SourceFile, CoverageMapping &Coverage);
  60. /// \brief Load the coverage mapping data. Return true if an error occured.
  61. std::unique_ptr<CoverageMapping> load();
  62. int run(Command Cmd, int argc, const char **argv);
  63. typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
  64. int show(int argc, const char **argv,
  65. CommandLineParserType commandLineParser);
  66. int report(int argc, const char **argv,
  67. CommandLineParserType commandLineParser);
  68. std::string ObjectFilename;
  69. CoverageViewOptions ViewOpts;
  70. std::string PGOFilename;
  71. CoverageFiltersMatchAll Filters;
  72. std::vector<StringRef> SourceFiles;
  73. std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
  74. LoadedSourceFiles;
  75. bool CompareFilenamesOnly;
  76. StringMap<std::string> RemappedFilenames;
  77. std::string CoverageArch;
  78. private:
  79. std::vector<std::string> CollectedPaths;
  80. };
  81. }
  82. void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
  83. errs() << "error: ";
  84. if (!Whence.empty())
  85. errs() << Whence << ": ";
  86. errs() << Message << "\n";
  87. }
  88. void CodeCoverageTool::addCollectedPath(const std::string &Path) {
  89. CollectedPaths.push_back(Path);
  90. SourceFiles.emplace_back(CollectedPaths.back());
  91. }
  92. ErrorOr<const MemoryBuffer &>
  93. CodeCoverageTool::getSourceFile(StringRef SourceFile) {
  94. // If we've remapped filenames, look up the real location for this file.
  95. if (!RemappedFilenames.empty()) {
  96. auto Loc = RemappedFilenames.find(SourceFile);
  97. if (Loc != RemappedFilenames.end())
  98. SourceFile = Loc->second;
  99. }
  100. for (const auto &Files : LoadedSourceFiles)
  101. if (sys::fs::equivalent(SourceFile, Files.first))
  102. return *Files.second;
  103. auto Buffer = MemoryBuffer::getFile(SourceFile);
  104. if (auto EC = Buffer.getError()) {
  105. error(EC.message(), SourceFile);
  106. return EC;
  107. }
  108. LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
  109. return *LoadedSourceFiles.back().second;
  110. }
  111. void
  112. CodeCoverageTool::attachExpansionSubViews(SourceCoverageView &View,
  113. ArrayRef<ExpansionRecord> Expansions,
  114. CoverageMapping &Coverage) {
  115. if (!ViewOpts.ShowExpandedRegions)
  116. return;
  117. for (const auto &Expansion : Expansions) {
  118. auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
  119. if (ExpansionCoverage.empty())
  120. continue;
  121. auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
  122. if (!SourceBuffer)
  123. continue;
  124. auto SubViewExpansions = ExpansionCoverage.getExpansions();
  125. auto SubView =
  126. SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
  127. ViewOpts, std::move(ExpansionCoverage));
  128. attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
  129. View.addExpansion(Expansion.Region, std::move(SubView));
  130. }
  131. }
  132. std::unique_ptr<SourceCoverageView>
  133. CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
  134. CoverageMapping &Coverage) {
  135. auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
  136. if (FunctionCoverage.empty())
  137. return nullptr;
  138. auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
  139. if (!SourceBuffer)
  140. return nullptr;
  141. auto Expansions = FunctionCoverage.getExpansions();
  142. auto View = SourceCoverageView::create(Function.Name, SourceBuffer.get(),
  143. ViewOpts, std::move(FunctionCoverage));
  144. attachExpansionSubViews(*View, Expansions, Coverage);
  145. return View;
  146. }
  147. std::unique_ptr<SourceCoverageView>
  148. CodeCoverageTool::createSourceFileView(StringRef SourceFile,
  149. CoverageMapping &Coverage) {
  150. auto SourceBuffer = getSourceFile(SourceFile);
  151. if (!SourceBuffer)
  152. return nullptr;
  153. auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
  154. if (FileCoverage.empty())
  155. return nullptr;
  156. auto Expansions = FileCoverage.getExpansions();
  157. auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
  158. ViewOpts, std::move(FileCoverage));
  159. attachExpansionSubViews(*View, Expansions, Coverage);
  160. for (auto Function : Coverage.getInstantiations(SourceFile)) {
  161. auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
  162. auto SubViewExpansions = SubViewCoverage.getExpansions();
  163. auto SubView =
  164. SourceCoverageView::create(Function->Name, SourceBuffer.get(), ViewOpts,
  165. std::move(SubViewCoverage));
  166. attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
  167. if (SubView) {
  168. unsigned FileID = Function->CountedRegions.front().FileID;
  169. unsigned Line = 0;
  170. for (const auto &CR : Function->CountedRegions)
  171. if (CR.FileID == FileID)
  172. Line = std::max(CR.LineEnd, Line);
  173. View->addInstantiation(Function->Name, Line, std::move(SubView));
  174. }
  175. }
  176. return View;
  177. }
  178. static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
  179. sys::fs::file_status Status;
  180. if (sys::fs::status(LHS, Status))
  181. return false;
  182. auto LHSTime = Status.getLastModificationTime();
  183. if (sys::fs::status(RHS, Status))
  184. return false;
  185. auto RHSTime = Status.getLastModificationTime();
  186. return LHSTime > RHSTime;
  187. }
  188. std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
  189. if (modifiedTimeGT(ObjectFilename, PGOFilename))
  190. errs() << "warning: profile data may be out of date - object is newer\n";
  191. auto CoverageOrErr = CoverageMapping::load(ObjectFilename, PGOFilename,
  192. CoverageArch);
  193. if (Error E = CoverageOrErr.takeError()) {
  194. colored_ostream(errs(), raw_ostream::RED)
  195. << "error: Failed to load coverage: " << toString(std::move(E)) << "\n";
  196. return nullptr;
  197. }
  198. auto Coverage = std::move(CoverageOrErr.get());
  199. unsigned Mismatched = Coverage->getMismatchedCount();
  200. if (Mismatched) {
  201. colored_ostream(errs(), raw_ostream::RED)
  202. << "warning: " << Mismatched << " functions have mismatched data. ";
  203. errs() << "\n";
  204. }
  205. if (CompareFilenamesOnly) {
  206. auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
  207. for (auto &SF : SourceFiles) {
  208. StringRef SFBase = sys::path::filename(SF);
  209. for (const auto &CF : CoveredFiles)
  210. if (SFBase == sys::path::filename(CF)) {
  211. RemappedFilenames[CF] = SF;
  212. SF = CF;
  213. break;
  214. }
  215. }
  216. }
  217. return Coverage;
  218. }
  219. int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
  220. cl::opt<std::string, true> ObjectFilename(
  221. cl::Positional, cl::Required, cl::location(this->ObjectFilename),
  222. cl::desc("Covered executable or object file."));
  223. cl::list<std::string> InputSourceFiles(
  224. cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
  225. cl::opt<std::string, true> PGOFilename(
  226. "instr-profile", cl::Required, cl::location(this->PGOFilename),
  227. cl::desc(
  228. "File with the profile data obtained after an instrumented run"));
  229. cl::opt<std::string> Arch(
  230. "arch", cl::desc("architecture of the coverage mapping binary"));
  231. cl::opt<bool> DebugDump("dump", cl::Optional,
  232. cl::desc("Show internal debug dump"));
  233. cl::opt<CoverageViewOptions::OutputFormat> Format(
  234. "format", cl::desc("Output format for line-based coverage reports"),
  235. cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
  236. "Text output"),
  237. clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
  238. "HTML output"),
  239. clEnumValEnd),
  240. cl::init(CoverageViewOptions::OutputFormat::Text));
  241. cl::opt<bool> FilenameEquivalence(
  242. "filename-equivalence", cl::Optional,
  243. cl::desc("Treat source files as equivalent to paths in the coverage data "
  244. "when the file names match, even if the full paths do not"));
  245. cl::OptionCategory FilteringCategory("Function filtering options");
  246. cl::list<std::string> NameFilters(
  247. "name", cl::Optional,
  248. cl::desc("Show code coverage only for functions with the given name"),
  249. cl::ZeroOrMore, cl::cat(FilteringCategory));
  250. cl::list<std::string> NameRegexFilters(
  251. "name-regex", cl::Optional,
  252. cl::desc("Show code coverage only for functions that match the given "
  253. "regular expression"),
  254. cl::ZeroOrMore, cl::cat(FilteringCategory));
  255. cl::opt<double> RegionCoverageLtFilter(
  256. "region-coverage-lt", cl::Optional,
  257. cl::desc("Show code coverage only for functions with region coverage "
  258. "less than the given threshold"),
  259. cl::cat(FilteringCategory));
  260. cl::opt<double> RegionCoverageGtFilter(
  261. "region-coverage-gt", cl::Optional,
  262. cl::desc("Show code coverage only for functions with region coverage "
  263. "greater than the given threshold"),
  264. cl::cat(FilteringCategory));
  265. cl::opt<double> LineCoverageLtFilter(
  266. "line-coverage-lt", cl::Optional,
  267. cl::desc("Show code coverage only for functions with line coverage less "
  268. "than the given threshold"),
  269. cl::cat(FilteringCategory));
  270. cl::opt<double> LineCoverageGtFilter(
  271. "line-coverage-gt", cl::Optional,
  272. cl::desc("Show code coverage only for functions with line coverage "
  273. "greater than the given threshold"),
  274. cl::cat(FilteringCategory));
  275. cl::opt<cl::boolOrDefault> UseColor(
  276. "use-color", cl::desc("Emit colored output (default=autodetect)"),
  277. cl::init(cl::BOU_UNSET));
  278. auto commandLineParser = [&, this](int argc, const char **argv) -> int {
  279. cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
  280. ViewOpts.Debug = DebugDump;
  281. CompareFilenamesOnly = FilenameEquivalence;
  282. ViewOpts.Format = Format;
  283. switch (ViewOpts.Format) {
  284. case CoverageViewOptions::OutputFormat::Text:
  285. ViewOpts.Colors = UseColor == cl::BOU_UNSET
  286. ? sys::Process::StandardOutHasColors()
  287. : UseColor == cl::BOU_TRUE;
  288. break;
  289. case CoverageViewOptions::OutputFormat::HTML:
  290. if (UseColor == cl::BOU_FALSE)
  291. error("Color output cannot be disabled when generating html.");
  292. ViewOpts.Colors = true;
  293. break;
  294. }
  295. // Create the function filters
  296. if (!NameFilters.empty() || !NameRegexFilters.empty()) {
  297. auto NameFilterer = new CoverageFilters;
  298. for (const auto &Name : NameFilters)
  299. NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
  300. for (const auto &Regex : NameRegexFilters)
  301. NameFilterer->push_back(
  302. llvm::make_unique<NameRegexCoverageFilter>(Regex));
  303. Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
  304. }
  305. if (RegionCoverageLtFilter.getNumOccurrences() ||
  306. RegionCoverageGtFilter.getNumOccurrences() ||
  307. LineCoverageLtFilter.getNumOccurrences() ||
  308. LineCoverageGtFilter.getNumOccurrences()) {
  309. auto StatFilterer = new CoverageFilters;
  310. if (RegionCoverageLtFilter.getNumOccurrences())
  311. StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
  312. RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
  313. if (RegionCoverageGtFilter.getNumOccurrences())
  314. StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
  315. RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
  316. if (LineCoverageLtFilter.getNumOccurrences())
  317. StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
  318. LineCoverageFilter::LessThan, LineCoverageLtFilter));
  319. if (LineCoverageGtFilter.getNumOccurrences())
  320. StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
  321. RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
  322. Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
  323. }
  324. if (!Arch.empty() &&
  325. Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
  326. errs() << "error: Unknown architecture: " << Arch << "\n";
  327. return 1;
  328. }
  329. CoverageArch = Arch;
  330. for (const auto &File : InputSourceFiles) {
  331. SmallString<128> Path(File);
  332. if (!CompareFilenamesOnly)
  333. if (std::error_code EC = sys::fs::make_absolute(Path)) {
  334. errs() << "error: " << File << ": " << EC.message();
  335. return 1;
  336. }
  337. addCollectedPath(Path.str());
  338. }
  339. return 0;
  340. };
  341. switch (Cmd) {
  342. case Show:
  343. return show(argc, argv, commandLineParser);
  344. case Report:
  345. return report(argc, argv, commandLineParser);
  346. }
  347. return 0;
  348. }
  349. int CodeCoverageTool::show(int argc, const char **argv,
  350. CommandLineParserType commandLineParser) {
  351. cl::OptionCategory ViewCategory("Viewing options");
  352. cl::opt<bool> ShowLineExecutionCounts(
  353. "show-line-counts", cl::Optional,
  354. cl::desc("Show the execution counts for each line"), cl::init(true),
  355. cl::cat(ViewCategory));
  356. cl::opt<bool> ShowRegions(
  357. "show-regions", cl::Optional,
  358. cl::desc("Show the execution counts for each region"),
  359. cl::cat(ViewCategory));
  360. cl::opt<bool> ShowBestLineRegionsCounts(
  361. "show-line-counts-or-regions", cl::Optional,
  362. cl::desc("Show the execution counts for each line, or the execution "
  363. "counts for each region on lines that have multiple regions"),
  364. cl::cat(ViewCategory));
  365. cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
  366. cl::desc("Show expanded source regions"),
  367. cl::cat(ViewCategory));
  368. cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
  369. cl::desc("Show function instantiations"),
  370. cl::cat(ViewCategory));
  371. cl::opt<std::string> ShowOutputDirectory(
  372. "output-dir", cl::init(""),
  373. cl::desc("Directory in which coverage information is written out"));
  374. cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
  375. cl::aliasopt(ShowOutputDirectory));
  376. auto Err = commandLineParser(argc, argv);
  377. if (Err)
  378. return Err;
  379. ViewOpts.ShowLineNumbers = true;
  380. ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
  381. !ShowRegions || ShowBestLineRegionsCounts;
  382. ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
  383. ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
  384. ViewOpts.ShowExpandedRegions = ShowExpansions;
  385. ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
  386. ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
  387. if (ViewOpts.hasOutputDirectory()) {
  388. if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
  389. error("Could not create output directory!", E.message());
  390. return 1;
  391. }
  392. }
  393. auto Coverage = load();
  394. if (!Coverage)
  395. return 1;
  396. auto Printer = CoveragePrinter::create(ViewOpts);
  397. if (!Filters.empty()) {
  398. auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
  399. if (Error E = OSOrErr.takeError()) {
  400. error(toString(std::move(E)));
  401. return 1;
  402. }
  403. auto OS = std::move(OSOrErr.get());
  404. // Show functions.
  405. for (const auto &Function : Coverage->getCoveredFunctions()) {
  406. if (!Filters.matches(Function))
  407. continue;
  408. auto mainView = createFunctionView(Function, *Coverage);
  409. if (!mainView) {
  410. ViewOpts.colored_ostream(errs(), raw_ostream::RED)
  411. << "warning: Could not read coverage for '" << Function.Name << "'."
  412. << "\n";
  413. continue;
  414. }
  415. mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
  416. }
  417. Printer->closeViewFile(std::move(OS));
  418. return 0;
  419. }
  420. // Show files
  421. bool ShowFilenames = SourceFiles.size() != 1;
  422. if (SourceFiles.empty())
  423. // Get the source files from the function coverage mapping.
  424. for (StringRef Filename : Coverage->getUniqueSourceFiles())
  425. SourceFiles.push_back(Filename);
  426. // Create an index out of the source files.
  427. if (ViewOpts.hasOutputDirectory()) {
  428. if (Error E = Printer->createIndexFile(SourceFiles)) {
  429. error(toString(std::move(E)));
  430. return 1;
  431. }
  432. }
  433. for (const auto &SourceFile : SourceFiles) {
  434. auto mainView = createSourceFileView(SourceFile, *Coverage);
  435. if (!mainView) {
  436. ViewOpts.colored_ostream(errs(), raw_ostream::RED)
  437. << "warning: The file '" << SourceFile << "' isn't covered.";
  438. errs() << "\n";
  439. continue;
  440. }
  441. auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
  442. if (Error E = OSOrErr.takeError()) {
  443. error(toString(std::move(E)));
  444. return 1;
  445. }
  446. auto OS = std::move(OSOrErr.get());
  447. mainView->print(*OS.get(), /*Wholefile=*/true,
  448. /*ShowSourceName=*/ShowFilenames);
  449. Printer->closeViewFile(std::move(OS));
  450. }
  451. return 0;
  452. }
  453. int CodeCoverageTool::report(int argc, const char **argv,
  454. CommandLineParserType commandLineParser) {
  455. auto Err = commandLineParser(argc, argv);
  456. if (Err)
  457. return Err;
  458. if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
  459. error("HTML output for summary reports is not yet supported.");
  460. auto Coverage = load();
  461. if (!Coverage)
  462. return 1;
  463. CoverageReport Report(ViewOpts, std::move(Coverage));
  464. if (SourceFiles.empty())
  465. Report.renderFileReports(llvm::outs());
  466. else
  467. Report.renderFunctionReports(SourceFiles, llvm::outs());
  468. return 0;
  469. }
  470. int showMain(int argc, const char *argv[]) {
  471. CodeCoverageTool Tool;
  472. return Tool.run(CodeCoverageTool::Show, argc, argv);
  473. }
  474. int reportMain(int argc, const char *argv[]) {
  475. CodeCoverageTool Tool;
  476. return Tool.run(CodeCoverageTool::Report, argc, argv);
  477. }