CodeCoverage.cpp 19 KB

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