CodeCoverage.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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/MemoryBuffer.h"
  29. #include "llvm/Support/Path.h"
  30. #include "llvm/Support/Process.h"
  31. #include "llvm/Support/Program.h"
  32. #include "llvm/Support/ThreadPool.h"
  33. #include "llvm/Support/ToolOutputFile.h"
  34. #include <functional>
  35. #include <system_error>
  36. using namespace llvm;
  37. using namespace coverage;
  38. void exportCoverageDataToJson(StringRef ObjectFilename,
  39. const coverage::CoverageMapping &CoverageMapping,
  40. raw_ostream &OS);
  41. namespace {
  42. /// \brief The implementation of the coverage tool.
  43. class CodeCoverageTool {
  44. public:
  45. enum Command {
  46. /// \brief The show command.
  47. Show,
  48. /// \brief The report command.
  49. Report,
  50. /// \brief The export command.
  51. Export
  52. };
  53. int run(Command Cmd, int argc, const char **argv);
  54. private:
  55. /// \brief Print the error message to the error output stream.
  56. void error(const Twine &Message, StringRef Whence = "");
  57. /// \brief Print the warning message to the error output stream.
  58. void warning(const Twine &Message, StringRef Whence = "");
  59. /// \brief Convert \p Path into an absolute path and append it to the list
  60. /// of collected paths.
  61. void addCollectedPath(const std::string &Path);
  62. /// \brief If \p Path is a regular file, collect the path. If it's a
  63. /// directory, recursively collect all of the paths within the directory.
  64. void collectPaths(const std::string &Path);
  65. /// \brief Return a memory buffer for the given source file.
  66. ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
  67. /// \brief Create source views for the expansions of the view.
  68. void attachExpansionSubViews(SourceCoverageView &View,
  69. ArrayRef<ExpansionRecord> Expansions,
  70. const CoverageMapping &Coverage);
  71. /// \brief Create the source view of a particular function.
  72. std::unique_ptr<SourceCoverageView>
  73. createFunctionView(const FunctionRecord &Function,
  74. const CoverageMapping &Coverage);
  75. /// \brief Create the main source view of a particular source file.
  76. std::unique_ptr<SourceCoverageView>
  77. createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
  78. /// \brief Load the coverage mapping data. Return nullptr if an error occured.
  79. std::unique_ptr<CoverageMapping> load();
  80. /// \brief If a demangler is available, demangle all symbol names.
  81. void demangleSymbols(const CoverageMapping &Coverage);
  82. /// \brief Demangle \p Sym if possible. Otherwise, just return \p Sym.
  83. StringRef getSymbolForHumans(StringRef Sym) const;
  84. typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
  85. int show(int argc, const char **argv,
  86. CommandLineParserType commandLineParser);
  87. int report(int argc, const char **argv,
  88. CommandLineParserType commandLineParser);
  89. int export_(int argc, const char **argv,
  90. CommandLineParserType commandLineParser);
  91. std::string ObjectFilename;
  92. CoverageViewOptions ViewOpts;
  93. CoverageFiltersMatchAll Filters;
  94. /// The path to the indexed profile.
  95. std::string PGOFilename;
  96. /// A list of input source files.
  97. std::vector<std::string> SourceFiles;
  98. /// Whether or not we're in -filename-equivalence mode.
  99. bool CompareFilenamesOnly;
  100. /// In -filename-equivalence mode, this maps absolute paths from the
  101. /// coverage mapping data to input source files.
  102. StringMap<std::string> RemappedFilenames;
  103. /// The architecture the coverage mapping data targets.
  104. std::string CoverageArch;
  105. /// A cache for demangled symbol names.
  106. StringMap<std::string> DemangledNames;
  107. /// Errors and warnings which have not been printed.
  108. std::mutex ErrsLock;
  109. /// A container for input source file buffers.
  110. std::mutex LoadedSourceFilesLock;
  111. std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
  112. LoadedSourceFiles;
  113. };
  114. }
  115. static std::string getErrorString(const Twine &Message, StringRef Whence,
  116. bool Warning) {
  117. std::string Str = (Warning ? "warning" : "error");
  118. Str += ": ";
  119. if (!Whence.empty())
  120. Str += Whence.str() + ": ";
  121. Str += Message.str() + "\n";
  122. return Str;
  123. }
  124. void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
  125. std::unique_lock<std::mutex> Guard{ErrsLock};
  126. ViewOpts.colored_ostream(errs(), raw_ostream::RED)
  127. << getErrorString(Message, Whence, false);
  128. }
  129. void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
  130. std::unique_lock<std::mutex> Guard{ErrsLock};
  131. ViewOpts.colored_ostream(errs(), raw_ostream::RED)
  132. << getErrorString(Message, Whence, true);
  133. }
  134. void CodeCoverageTool::addCollectedPath(const std::string &Path) {
  135. if (CompareFilenamesOnly) {
  136. SourceFiles.emplace_back(Path);
  137. } else {
  138. SmallString<128> EffectivePath(Path);
  139. if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
  140. error(EC.message(), Path);
  141. return;
  142. }
  143. sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
  144. SourceFiles.emplace_back(EffectivePath.str());
  145. }
  146. }
  147. void CodeCoverageTool::collectPaths(const std::string &Path) {
  148. llvm::sys::fs::file_status Status;
  149. llvm::sys::fs::status(Path, Status);
  150. if (!llvm::sys::fs::exists(Status)) {
  151. if (CompareFilenamesOnly)
  152. addCollectedPath(Path);
  153. else
  154. error("Missing source file", Path);
  155. return;
  156. }
  157. if (llvm::sys::fs::is_regular_file(Status)) {
  158. addCollectedPath(Path);
  159. return;
  160. }
  161. if (llvm::sys::fs::is_directory(Status)) {
  162. std::error_code EC;
  163. for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
  164. F != E && !EC; F.increment(EC)) {
  165. if (llvm::sys::fs::is_regular_file(F->path()))
  166. addCollectedPath(F->path());
  167. }
  168. if (EC)
  169. warning(EC.message(), Path);
  170. }
  171. }
  172. ErrorOr<const MemoryBuffer &>
  173. CodeCoverageTool::getSourceFile(StringRef SourceFile) {
  174. // If we've remapped filenames, look up the real location for this file.
  175. std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
  176. if (!RemappedFilenames.empty()) {
  177. auto Loc = RemappedFilenames.find(SourceFile);
  178. if (Loc != RemappedFilenames.end())
  179. SourceFile = Loc->second;
  180. }
  181. for (const auto &Files : LoadedSourceFiles)
  182. if (sys::fs::equivalent(SourceFile, Files.first))
  183. return *Files.second;
  184. auto Buffer = MemoryBuffer::getFile(SourceFile);
  185. if (auto EC = Buffer.getError()) {
  186. error(EC.message(), SourceFile);
  187. return EC;
  188. }
  189. LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
  190. return *LoadedSourceFiles.back().second;
  191. }
  192. void CodeCoverageTool::attachExpansionSubViews(
  193. SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
  194. const CoverageMapping &Coverage) {
  195. if (!ViewOpts.ShowExpandedRegions)
  196. return;
  197. for (const auto &Expansion : Expansions) {
  198. auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
  199. if (ExpansionCoverage.empty())
  200. continue;
  201. auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
  202. if (!SourceBuffer)
  203. continue;
  204. auto SubViewExpansions = ExpansionCoverage.getExpansions();
  205. auto SubView =
  206. SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
  207. ViewOpts, std::move(ExpansionCoverage));
  208. attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
  209. View.addExpansion(Expansion.Region, std::move(SubView));
  210. }
  211. }
  212. std::unique_ptr<SourceCoverageView>
  213. CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
  214. const CoverageMapping &Coverage) {
  215. auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
  216. if (FunctionCoverage.empty())
  217. return nullptr;
  218. auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
  219. if (!SourceBuffer)
  220. return nullptr;
  221. auto Expansions = FunctionCoverage.getExpansions();
  222. auto View = SourceCoverageView::create(getSymbolForHumans(Function.Name),
  223. SourceBuffer.get(), ViewOpts,
  224. std::move(FunctionCoverage));
  225. attachExpansionSubViews(*View, Expansions, Coverage);
  226. return View;
  227. }
  228. std::unique_ptr<SourceCoverageView>
  229. CodeCoverageTool::createSourceFileView(StringRef SourceFile,
  230. const CoverageMapping &Coverage) {
  231. auto SourceBuffer = getSourceFile(SourceFile);
  232. if (!SourceBuffer)
  233. return nullptr;
  234. auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
  235. if (FileCoverage.empty())
  236. return nullptr;
  237. auto Expansions = FileCoverage.getExpansions();
  238. auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
  239. ViewOpts, std::move(FileCoverage));
  240. attachExpansionSubViews(*View, Expansions, Coverage);
  241. for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
  242. std::unique_ptr<SourceCoverageView> SubView{nullptr};
  243. StringRef Funcname = getSymbolForHumans(Function->Name);
  244. if (Function->ExecutionCount > 0) {
  245. auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
  246. auto SubViewExpansions = SubViewCoverage.getExpansions();
  247. SubView = SourceCoverageView::create(
  248. Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
  249. attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
  250. }
  251. unsigned FileID = Function->CountedRegions.front().FileID;
  252. unsigned Line = 0;
  253. for (const auto &CR : Function->CountedRegions)
  254. if (CR.FileID == FileID)
  255. Line = std::max(CR.LineEnd, Line);
  256. View->addInstantiation(Funcname, Line, std::move(SubView));
  257. }
  258. return View;
  259. }
  260. static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
  261. sys::fs::file_status Status;
  262. if (sys::fs::status(LHS, Status))
  263. return false;
  264. auto LHSTime = Status.getLastModificationTime();
  265. if (sys::fs::status(RHS, Status))
  266. return false;
  267. auto RHSTime = Status.getLastModificationTime();
  268. return LHSTime > RHSTime;
  269. }
  270. std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
  271. if (modifiedTimeGT(ObjectFilename, PGOFilename))
  272. warning("profile data may be out of date - object is newer",
  273. ObjectFilename);
  274. auto CoverageOrErr =
  275. CoverageMapping::load(ObjectFilename, PGOFilename, CoverageArch);
  276. if (Error E = CoverageOrErr.takeError()) {
  277. error("Failed to load coverage: " + toString(std::move(E)), ObjectFilename);
  278. return nullptr;
  279. }
  280. auto Coverage = std::move(CoverageOrErr.get());
  281. unsigned Mismatched = Coverage->getMismatchedCount();
  282. if (Mismatched)
  283. warning(utostr(Mismatched) + " functions have mismatched data");
  284. std::vector<StringRef> CoveredFiles = Coverage.get()->getUniqueSourceFiles();
  285. auto UncoveredFilesIt = SourceFiles.end();
  286. if (!CompareFilenamesOnly) {
  287. // The user may have specified source files which aren't in the coverage
  288. // mapping. Filter these files away.
  289. UncoveredFilesIt = std::remove_if(
  290. SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
  291. return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
  292. SF);
  293. });
  294. } else {
  295. for (auto &SF : SourceFiles) {
  296. StringRef SFBase = sys::path::filename(SF);
  297. for (const auto &CF : CoveredFiles) {
  298. if (SFBase == sys::path::filename(CF)) {
  299. RemappedFilenames[CF] = SF;
  300. SF = CF;
  301. break;
  302. }
  303. }
  304. }
  305. UncoveredFilesIt = std::remove_if(
  306. SourceFiles.begin(), SourceFiles.end(),
  307. [&](const std::string &SF) { return !RemappedFilenames.count(SF); });
  308. }
  309. SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
  310. demangleSymbols(*Coverage);
  311. return Coverage;
  312. }
  313. void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
  314. if (!ViewOpts.hasDemangler())
  315. return;
  316. // Pass function names to the demangler in a temporary file.
  317. int InputFD;
  318. SmallString<256> InputPath;
  319. std::error_code EC =
  320. sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
  321. if (EC) {
  322. error(InputPath, EC.message());
  323. return;
  324. }
  325. tool_output_file InputTOF{InputPath, InputFD};
  326. unsigned NumSymbols = 0;
  327. for (const auto &Function : Coverage.getCoveredFunctions()) {
  328. InputTOF.os() << Function.Name << '\n';
  329. ++NumSymbols;
  330. }
  331. InputTOF.os().close();
  332. // Use another temporary file to store the demangler's output.
  333. int OutputFD;
  334. SmallString<256> OutputPath;
  335. EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
  336. OutputPath);
  337. if (EC) {
  338. error(OutputPath, EC.message());
  339. return;
  340. }
  341. tool_output_file OutputTOF{OutputPath, OutputFD};
  342. OutputTOF.os().close();
  343. // Invoke the demangler.
  344. std::vector<const char *> ArgsV;
  345. for (const std::string &Arg : ViewOpts.DemanglerOpts)
  346. ArgsV.push_back(Arg.c_str());
  347. ArgsV.push_back(nullptr);
  348. StringRef InputPathRef = InputPath.str();
  349. StringRef OutputPathRef = OutputPath.str();
  350. StringRef StderrRef;
  351. const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
  352. std::string ErrMsg;
  353. int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
  354. /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
  355. /*memoryLimit=*/0, &ErrMsg);
  356. if (RC) {
  357. error(ErrMsg, ViewOpts.DemanglerOpts[0]);
  358. return;
  359. }
  360. // Parse the demangler's output.
  361. auto BufOrError = MemoryBuffer::getFile(OutputPath);
  362. if (!BufOrError) {
  363. error(OutputPath, BufOrError.getError().message());
  364. return;
  365. }
  366. std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
  367. SmallVector<StringRef, 8> Symbols;
  368. StringRef DemanglerData = DemanglerBuf->getBuffer();
  369. DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
  370. /*KeepEmpty=*/false);
  371. if (Symbols.size() != NumSymbols) {
  372. error("Demangler did not provide expected number of symbols");
  373. return;
  374. }
  375. // Cache the demangled names.
  376. unsigned I = 0;
  377. for (const auto &Function : Coverage.getCoveredFunctions())
  378. DemangledNames[Function.Name] = Symbols[I++];
  379. }
  380. StringRef CodeCoverageTool::getSymbolForHumans(StringRef Sym) const {
  381. const auto DemangledName = DemangledNames.find(Sym);
  382. if (DemangledName == DemangledNames.end())
  383. return Sym;
  384. return DemangledName->getValue();
  385. }
  386. int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
  387. cl::opt<std::string, true> ObjectFilename(
  388. cl::Positional, cl::Required, cl::location(this->ObjectFilename),
  389. cl::desc("Covered executable or object file."));
  390. cl::list<std::string> InputSourceFiles(
  391. cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
  392. cl::opt<bool> DebugDumpCollectedPaths(
  393. "dump-collected-paths", cl::Optional, cl::Hidden,
  394. cl::desc("Show the collected paths to source files"));
  395. cl::opt<std::string, true> PGOFilename(
  396. "instr-profile", cl::Required, cl::location(this->PGOFilename),
  397. cl::desc(
  398. "File with the profile data obtained after an instrumented run"));
  399. cl::opt<std::string> Arch(
  400. "arch", cl::desc("architecture of the coverage mapping binary"));
  401. cl::opt<bool> DebugDump("dump", cl::Optional,
  402. cl::desc("Show internal debug dump"));
  403. cl::opt<CoverageViewOptions::OutputFormat> Format(
  404. "format", cl::desc("Output format for line-based coverage reports"),
  405. cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
  406. "Text output"),
  407. clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
  408. "HTML output"),
  409. clEnumValEnd),
  410. cl::init(CoverageViewOptions::OutputFormat::Text));
  411. cl::opt<bool> FilenameEquivalence(
  412. "filename-equivalence", cl::Optional,
  413. cl::desc("Treat source files as equivalent to paths in the coverage data "
  414. "when the file names match, even if the full paths do not"));
  415. cl::OptionCategory FilteringCategory("Function filtering options");
  416. cl::list<std::string> NameFilters(
  417. "name", cl::Optional,
  418. cl::desc("Show code coverage only for functions with the given name"),
  419. cl::ZeroOrMore, cl::cat(FilteringCategory));
  420. cl::list<std::string> NameRegexFilters(
  421. "name-regex", cl::Optional,
  422. cl::desc("Show code coverage only for functions that match the given "
  423. "regular expression"),
  424. cl::ZeroOrMore, cl::cat(FilteringCategory));
  425. cl::opt<double> RegionCoverageLtFilter(
  426. "region-coverage-lt", cl::Optional,
  427. cl::desc("Show code coverage only for functions with region coverage "
  428. "less than the given threshold"),
  429. cl::cat(FilteringCategory));
  430. cl::opt<double> RegionCoverageGtFilter(
  431. "region-coverage-gt", cl::Optional,
  432. cl::desc("Show code coverage only for functions with region coverage "
  433. "greater than the given threshold"),
  434. cl::cat(FilteringCategory));
  435. cl::opt<double> LineCoverageLtFilter(
  436. "line-coverage-lt", cl::Optional,
  437. cl::desc("Show code coverage only for functions with line coverage less "
  438. "than the given threshold"),
  439. cl::cat(FilteringCategory));
  440. cl::opt<double> LineCoverageGtFilter(
  441. "line-coverage-gt", cl::Optional,
  442. cl::desc("Show code coverage only for functions with line coverage "
  443. "greater than the given threshold"),
  444. cl::cat(FilteringCategory));
  445. cl::opt<cl::boolOrDefault> UseColor(
  446. "use-color", cl::desc("Emit colored output (default=autodetect)"),
  447. cl::init(cl::BOU_UNSET));
  448. cl::list<std::string> DemanglerOpts(
  449. "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
  450. auto commandLineParser = [&, this](int argc, const char **argv) -> int {
  451. cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
  452. ViewOpts.Debug = DebugDump;
  453. CompareFilenamesOnly = FilenameEquivalence;
  454. ViewOpts.Format = Format;
  455. SmallString<128> ObjectFilePath(this->ObjectFilename);
  456. if (std::error_code EC = sys::fs::make_absolute(ObjectFilePath)) {
  457. error(EC.message(), this->ObjectFilename);
  458. return 1;
  459. }
  460. sys::path::native(ObjectFilePath);
  461. ViewOpts.ObjectFilename = ObjectFilePath.c_str();
  462. switch (ViewOpts.Format) {
  463. case CoverageViewOptions::OutputFormat::Text:
  464. ViewOpts.Colors = UseColor == cl::BOU_UNSET
  465. ? sys::Process::StandardOutHasColors()
  466. : UseColor == cl::BOU_TRUE;
  467. break;
  468. case CoverageViewOptions::OutputFormat::HTML:
  469. if (UseColor == cl::BOU_FALSE)
  470. error("Color output cannot be disabled when generating html.");
  471. ViewOpts.Colors = true;
  472. break;
  473. }
  474. // If a demangler is supplied, check if it exists and register it.
  475. if (DemanglerOpts.size()) {
  476. auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
  477. if (!DemanglerPathOrErr) {
  478. error("Could not find the demangler!",
  479. DemanglerPathOrErr.getError().message());
  480. return 1;
  481. }
  482. DemanglerOpts[0] = *DemanglerPathOrErr;
  483. ViewOpts.DemanglerOpts.swap(DemanglerOpts);
  484. }
  485. // Create the function filters
  486. if (!NameFilters.empty() || !NameRegexFilters.empty()) {
  487. auto NameFilterer = new CoverageFilters;
  488. for (const auto &Name : NameFilters)
  489. NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
  490. for (const auto &Regex : NameRegexFilters)
  491. NameFilterer->push_back(
  492. llvm::make_unique<NameRegexCoverageFilter>(Regex));
  493. Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
  494. }
  495. if (RegionCoverageLtFilter.getNumOccurrences() ||
  496. RegionCoverageGtFilter.getNumOccurrences() ||
  497. LineCoverageLtFilter.getNumOccurrences() ||
  498. LineCoverageGtFilter.getNumOccurrences()) {
  499. auto StatFilterer = new CoverageFilters;
  500. if (RegionCoverageLtFilter.getNumOccurrences())
  501. StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
  502. RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
  503. if (RegionCoverageGtFilter.getNumOccurrences())
  504. StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
  505. RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
  506. if (LineCoverageLtFilter.getNumOccurrences())
  507. StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
  508. LineCoverageFilter::LessThan, LineCoverageLtFilter));
  509. if (LineCoverageGtFilter.getNumOccurrences())
  510. StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
  511. RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
  512. Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
  513. }
  514. if (!Arch.empty() &&
  515. Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
  516. error("Unknown architecture: " + Arch);
  517. return 1;
  518. }
  519. CoverageArch = Arch;
  520. for (const std::string &File : InputSourceFiles)
  521. collectPaths(File);
  522. if (DebugDumpCollectedPaths) {
  523. for (const std::string &SF : SourceFiles)
  524. outs() << SF << '\n';
  525. ::exit(0);
  526. }
  527. return 0;
  528. };
  529. switch (Cmd) {
  530. case Show:
  531. return show(argc, argv, commandLineParser);
  532. case Report:
  533. return report(argc, argv, commandLineParser);
  534. case Export:
  535. return export_(argc, argv, commandLineParser);
  536. }
  537. return 0;
  538. }
  539. int CodeCoverageTool::show(int argc, const char **argv,
  540. CommandLineParserType commandLineParser) {
  541. cl::OptionCategory ViewCategory("Viewing options");
  542. cl::opt<bool> ShowLineExecutionCounts(
  543. "show-line-counts", cl::Optional,
  544. cl::desc("Show the execution counts for each line"), cl::init(true),
  545. cl::cat(ViewCategory));
  546. cl::opt<bool> ShowRegions(
  547. "show-regions", cl::Optional,
  548. cl::desc("Show the execution counts for each region"),
  549. cl::cat(ViewCategory));
  550. cl::opt<bool> ShowBestLineRegionsCounts(
  551. "show-line-counts-or-regions", cl::Optional,
  552. cl::desc("Show the execution counts for each line, or the execution "
  553. "counts for each region on lines that have multiple regions"),
  554. cl::cat(ViewCategory));
  555. cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
  556. cl::desc("Show expanded source regions"),
  557. cl::cat(ViewCategory));
  558. cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
  559. cl::desc("Show function instantiations"),
  560. cl::cat(ViewCategory));
  561. cl::opt<std::string> ShowOutputDirectory(
  562. "output-dir", cl::init(""),
  563. cl::desc("Directory in which coverage information is written out"));
  564. cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
  565. cl::aliasopt(ShowOutputDirectory));
  566. cl::opt<uint32_t> TabSize(
  567. "tab-size", cl::init(2),
  568. cl::desc(
  569. "Set tab expansion size for html coverage reports (default = 2)"));
  570. cl::opt<std::string> ProjectTitle(
  571. "project-title", cl::Optional,
  572. cl::desc("Set project title for the coverage report"));
  573. auto Err = commandLineParser(argc, argv);
  574. if (Err)
  575. return Err;
  576. ViewOpts.ShowLineNumbers = true;
  577. ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
  578. !ShowRegions || ShowBestLineRegionsCounts;
  579. ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
  580. ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
  581. ViewOpts.ShowExpandedRegions = ShowExpansions;
  582. ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
  583. ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
  584. ViewOpts.TabSize = TabSize;
  585. ViewOpts.ProjectTitle = ProjectTitle;
  586. if (ViewOpts.hasOutputDirectory()) {
  587. if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
  588. error("Could not create output directory!", E.message());
  589. return 1;
  590. }
  591. }
  592. sys::fs::file_status Status;
  593. if (sys::fs::status(PGOFilename, Status)) {
  594. error("profdata file error: can not get the file status. \n");
  595. return 1;
  596. }
  597. auto ModifiedTime = Status.getLastModificationTime();
  598. std::string ModifiedTimeStr = ModifiedTime.str();
  599. size_t found = ModifiedTimeStr.rfind(":");
  600. ViewOpts.CreatedTimeStr = (found != std::string::npos)
  601. ? "Created: " + ModifiedTimeStr.substr(0, found)
  602. : "Created: " + ModifiedTimeStr;
  603. auto Coverage = load();
  604. if (!Coverage)
  605. return 1;
  606. auto Printer = CoveragePrinter::create(ViewOpts);
  607. if (!Filters.empty()) {
  608. auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
  609. if (Error E = OSOrErr.takeError()) {
  610. error("Could not create view file!", toString(std::move(E)));
  611. return 1;
  612. }
  613. auto OS = std::move(OSOrErr.get());
  614. // Show functions.
  615. for (const auto &Function : Coverage->getCoveredFunctions()) {
  616. if (!Filters.matches(Function))
  617. continue;
  618. auto mainView = createFunctionView(Function, *Coverage);
  619. if (!mainView) {
  620. warning("Could not read coverage for '" + Function.Name + "'.");
  621. continue;
  622. }
  623. mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
  624. }
  625. Printer->closeViewFile(std::move(OS));
  626. return 0;
  627. }
  628. // Show files
  629. bool ShowFilenames =
  630. (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
  631. (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
  632. if (SourceFiles.empty())
  633. // Get the source files from the function coverage mapping.
  634. for (StringRef Filename : Coverage->getUniqueSourceFiles())
  635. SourceFiles.push_back(Filename);
  636. // Create an index out of the source files.
  637. if (ViewOpts.hasOutputDirectory()) {
  638. if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
  639. error("Could not create index file!", toString(std::move(E)));
  640. return 1;
  641. }
  642. }
  643. // In -output-dir mode, it's safe to use multiple threads to print files.
  644. unsigned ThreadCount = 1;
  645. if (ViewOpts.hasOutputDirectory())
  646. ThreadCount = std::thread::hardware_concurrency();
  647. ThreadPool Pool(ThreadCount);
  648. for (const std::string &SourceFile : SourceFiles) {
  649. Pool.async([this, &SourceFile, &Coverage, &Printer, ShowFilenames] {
  650. auto View = createSourceFileView(SourceFile, *Coverage);
  651. if (!View) {
  652. warning("The file '" + SourceFile + "' isn't covered.");
  653. return;
  654. }
  655. auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
  656. if (Error E = OSOrErr.takeError()) {
  657. error("Could not create view file!", toString(std::move(E)));
  658. return;
  659. }
  660. auto OS = std::move(OSOrErr.get());
  661. View->print(*OS.get(), /*Wholefile=*/true,
  662. /*ShowSourceName=*/ShowFilenames);
  663. Printer->closeViewFile(std::move(OS));
  664. });
  665. }
  666. Pool.wait();
  667. return 0;
  668. }
  669. int CodeCoverageTool::report(int argc, const char **argv,
  670. CommandLineParserType commandLineParser) {
  671. auto Err = commandLineParser(argc, argv);
  672. if (Err)
  673. return Err;
  674. if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
  675. error("HTML output for summary reports is not yet supported.");
  676. auto Coverage = load();
  677. if (!Coverage)
  678. return 1;
  679. CoverageReport Report(ViewOpts, *Coverage.get());
  680. if (SourceFiles.empty())
  681. Report.renderFileReports(llvm::outs());
  682. else
  683. Report.renderFunctionReports(SourceFiles, llvm::outs());
  684. return 0;
  685. }
  686. int CodeCoverageTool::export_(int argc, const char **argv,
  687. CommandLineParserType commandLineParser) {
  688. auto Err = commandLineParser(argc, argv);
  689. if (Err)
  690. return Err;
  691. auto Coverage = load();
  692. if (!Coverage) {
  693. error("Could not load coverage information");
  694. return 1;
  695. }
  696. exportCoverageDataToJson(ObjectFilename, *Coverage.get(), outs());
  697. return 0;
  698. }
  699. int showMain(int argc, const char *argv[]) {
  700. CodeCoverageTool Tool;
  701. return Tool.run(CodeCoverageTool::Show, argc, argv);
  702. }
  703. int reportMain(int argc, const char *argv[]) {
  704. CodeCoverageTool Tool;
  705. return Tool.run(CodeCoverageTool::Report, argc, argv);
  706. }
  707. int exportMain(int argc, const char *argv[]) {
  708. CodeCoverageTool Tool;
  709. return Tool.run(CodeCoverageTool::Export, argc, argv);
  710. }