CodeCoverage.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===//
  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. // The 'CodeCoverageTool' class implements a command line tool to analyze and
  10. // report coverage information using the profiling instrumentation and code
  11. // coverage mapping.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CoverageExporterJson.h"
  15. #include "CoverageExporterLcov.h"
  16. #include "CoverageFilters.h"
  17. #include "CoverageReport.h"
  18. #include "CoverageSummaryInfo.h"
  19. #include "CoverageViewOptions.h"
  20. #include "RenderingSupport.h"
  21. #include "SourceCoverageView.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/Triple.h"
  25. #include "llvm/ProfileData/Coverage/CoverageMapping.h"
  26. #include "llvm/ProfileData/InstrProfReader.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/Format.h"
  30. #include "llvm/Support/MemoryBuffer.h"
  31. #include "llvm/Support/Path.h"
  32. #include "llvm/Support/Process.h"
  33. #include "llvm/Support/Program.h"
  34. #include "llvm/Support/ScopedPrinter.h"
  35. #include "llvm/Support/SpecialCaseList.h"
  36. #include "llvm/Support/ThreadPool.h"
  37. #include "llvm/Support/Threading.h"
  38. #include "llvm/Support/ToolOutputFile.h"
  39. #include "llvm/Support/VirtualFileSystem.h"
  40. #include <functional>
  41. #include <map>
  42. #include <system_error>
  43. using namespace llvm;
  44. using namespace coverage;
  45. void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
  46. const CoverageViewOptions &Options,
  47. raw_ostream &OS);
  48. namespace {
  49. /// The implementation of the coverage tool.
  50. class CodeCoverageTool {
  51. public:
  52. enum Command {
  53. /// The show command.
  54. Show,
  55. /// The report command.
  56. Report,
  57. /// The export command.
  58. Export
  59. };
  60. int run(Command Cmd, int argc, const char **argv);
  61. private:
  62. /// Print the error message to the error output stream.
  63. void error(const Twine &Message, StringRef Whence = "");
  64. /// Print the warning message to the error output stream.
  65. void warning(const Twine &Message, StringRef Whence = "");
  66. /// Convert \p Path into an absolute path and append it to the list
  67. /// of collected paths.
  68. void addCollectedPath(const std::string &Path);
  69. /// If \p Path is a regular file, collect the path. If it's a
  70. /// directory, recursively collect all of the paths within the directory.
  71. void collectPaths(const std::string &Path);
  72. /// Check if the two given files are the same file.
  73. bool isEquivalentFile(StringRef FilePath1, StringRef FilePath2);
  74. /// Retrieve a file status with a cache.
  75. Optional<sys::fs::file_status> getFileStatus(StringRef FilePath);
  76. /// Return a memory buffer for the given source file.
  77. ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
  78. /// Create source views for the expansions of the view.
  79. void attachExpansionSubViews(SourceCoverageView &View,
  80. ArrayRef<ExpansionRecord> Expansions,
  81. const CoverageMapping &Coverage);
  82. /// Create source views for the branches of the view.
  83. void attachBranchSubViews(SourceCoverageView &View, StringRef SourceName,
  84. ArrayRef<CountedRegion> Branches,
  85. const MemoryBuffer &File,
  86. CoverageData &CoverageInfo);
  87. /// Create the source view of a particular function.
  88. std::unique_ptr<SourceCoverageView>
  89. createFunctionView(const FunctionRecord &Function,
  90. const CoverageMapping &Coverage);
  91. /// Create the main source view of a particular source file.
  92. std::unique_ptr<SourceCoverageView>
  93. createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
  94. /// Load the coverage mapping data. Return nullptr if an error occurred.
  95. std::unique_ptr<CoverageMapping> load();
  96. /// Create a mapping from files in the Coverage data to local copies
  97. /// (path-equivalence).
  98. void remapPathNames(const CoverageMapping &Coverage);
  99. /// Remove input source files which aren't mapped by \p Coverage.
  100. void removeUnmappedInputs(const CoverageMapping &Coverage);
  101. /// If a demangler is available, demangle all symbol names.
  102. void demangleSymbols(const CoverageMapping &Coverage);
  103. /// Write out a source file view to the filesystem.
  104. void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
  105. CoveragePrinter *Printer, bool ShowFilenames);
  106. typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
  107. int doShow(int argc, const char **argv,
  108. CommandLineParserType commandLineParser);
  109. int doReport(int argc, const char **argv,
  110. CommandLineParserType commandLineParser);
  111. int doExport(int argc, const char **argv,
  112. CommandLineParserType commandLineParser);
  113. std::vector<StringRef> ObjectFilenames;
  114. CoverageViewOptions ViewOpts;
  115. CoverageFiltersMatchAll Filters;
  116. CoverageFilters IgnoreFilenameFilters;
  117. /// True if InputSourceFiles are provided.
  118. bool HadSourceFiles = false;
  119. /// The path to the indexed profile.
  120. std::string PGOFilename;
  121. /// A list of input source files.
  122. std::vector<std::string> SourceFiles;
  123. /// In -path-equivalence mode, this maps the absolute paths from the coverage
  124. /// mapping data to the input source files.
  125. StringMap<std::string> RemappedFilenames;
  126. /// The coverage data path to be remapped from, and the source path to be
  127. /// remapped to, when using -path-equivalence.
  128. Optional<std::pair<std::string, std::string>> PathRemapping;
  129. /// File status cache used when finding the same file.
  130. StringMap<Optional<sys::fs::file_status>> FileStatusCache;
  131. /// The architecture the coverage mapping data targets.
  132. std::vector<StringRef> CoverageArches;
  133. /// A cache for demangled symbols.
  134. DemangleCache DC;
  135. /// A lock which guards printing to stderr.
  136. std::mutex ErrsLock;
  137. /// A container for input source file buffers.
  138. std::mutex LoadedSourceFilesLock;
  139. std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
  140. LoadedSourceFiles;
  141. /// Allowlist from -name-allowlist to be used for filtering.
  142. std::unique_ptr<SpecialCaseList> NameAllowlist;
  143. };
  144. }
  145. static std::string getErrorString(const Twine &Message, StringRef Whence,
  146. bool Warning) {
  147. std::string Str = (Warning ? "warning" : "error");
  148. Str += ": ";
  149. if (!Whence.empty())
  150. Str += Whence.str() + ": ";
  151. Str += Message.str() + "\n";
  152. return Str;
  153. }
  154. void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
  155. std::unique_lock<std::mutex> Guard{ErrsLock};
  156. ViewOpts.colored_ostream(errs(), raw_ostream::RED)
  157. << getErrorString(Message, Whence, false);
  158. }
  159. void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
  160. std::unique_lock<std::mutex> Guard{ErrsLock};
  161. ViewOpts.colored_ostream(errs(), raw_ostream::RED)
  162. << getErrorString(Message, Whence, true);
  163. }
  164. void CodeCoverageTool::addCollectedPath(const std::string &Path) {
  165. SmallString<128> EffectivePath(Path);
  166. if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
  167. error(EC.message(), Path);
  168. return;
  169. }
  170. sys::path::remove_dots(EffectivePath, /*remove_dot_dot=*/true);
  171. if (!IgnoreFilenameFilters.matchesFilename(EffectivePath))
  172. SourceFiles.emplace_back(EffectivePath.str());
  173. HadSourceFiles = !SourceFiles.empty();
  174. }
  175. void CodeCoverageTool::collectPaths(const std::string &Path) {
  176. llvm::sys::fs::file_status Status;
  177. llvm::sys::fs::status(Path, Status);
  178. if (!llvm::sys::fs::exists(Status)) {
  179. if (PathRemapping)
  180. addCollectedPath(Path);
  181. else
  182. warning("Source file doesn't exist, proceeded by ignoring it.", Path);
  183. return;
  184. }
  185. if (llvm::sys::fs::is_regular_file(Status)) {
  186. addCollectedPath(Path);
  187. return;
  188. }
  189. if (llvm::sys::fs::is_directory(Status)) {
  190. std::error_code EC;
  191. for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
  192. F != E; F.increment(EC)) {
  193. auto Status = F->status();
  194. if (!Status) {
  195. warning(Status.getError().message(), F->path());
  196. continue;
  197. }
  198. if (Status->type() == llvm::sys::fs::file_type::regular_file)
  199. addCollectedPath(F->path());
  200. }
  201. }
  202. }
  203. Optional<sys::fs::file_status>
  204. CodeCoverageTool::getFileStatus(StringRef FilePath) {
  205. auto It = FileStatusCache.try_emplace(FilePath);
  206. auto &CachedStatus = It.first->getValue();
  207. if (!It.second)
  208. return CachedStatus;
  209. sys::fs::file_status Status;
  210. if (!sys::fs::status(FilePath, Status))
  211. CachedStatus = Status;
  212. return CachedStatus;
  213. }
  214. bool CodeCoverageTool::isEquivalentFile(StringRef FilePath1,
  215. StringRef FilePath2) {
  216. auto Status1 = getFileStatus(FilePath1);
  217. auto Status2 = getFileStatus(FilePath2);
  218. return Status1.hasValue() && Status2.hasValue() &&
  219. sys::fs::equivalent(Status1.getValue(), Status2.getValue());
  220. }
  221. ErrorOr<const MemoryBuffer &>
  222. CodeCoverageTool::getSourceFile(StringRef SourceFile) {
  223. // If we've remapped filenames, look up the real location for this file.
  224. std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
  225. if (!RemappedFilenames.empty()) {
  226. auto Loc = RemappedFilenames.find(SourceFile);
  227. if (Loc != RemappedFilenames.end())
  228. SourceFile = Loc->second;
  229. }
  230. for (const auto &Files : LoadedSourceFiles)
  231. if (isEquivalentFile(SourceFile, Files.first))
  232. return *Files.second;
  233. auto Buffer = MemoryBuffer::getFile(SourceFile);
  234. if (auto EC = Buffer.getError()) {
  235. error(EC.message(), SourceFile);
  236. return EC;
  237. }
  238. LoadedSourceFiles.emplace_back(std::string(SourceFile),
  239. std::move(Buffer.get()));
  240. return *LoadedSourceFiles.back().second;
  241. }
  242. void CodeCoverageTool::attachExpansionSubViews(
  243. SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
  244. const CoverageMapping &Coverage) {
  245. if (!ViewOpts.ShowExpandedRegions)
  246. return;
  247. for (const auto &Expansion : Expansions) {
  248. auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
  249. if (ExpansionCoverage.empty())
  250. continue;
  251. auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
  252. if (!SourceBuffer)
  253. continue;
  254. auto SubViewBranches = ExpansionCoverage.getBranches();
  255. auto SubViewExpansions = ExpansionCoverage.getExpansions();
  256. auto SubView =
  257. SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
  258. ViewOpts, std::move(ExpansionCoverage));
  259. attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
  260. attachBranchSubViews(*SubView, Expansion.Function.Name, SubViewBranches,
  261. SourceBuffer.get(), ExpansionCoverage);
  262. View.addExpansion(Expansion.Region, std::move(SubView));
  263. }
  264. }
  265. void CodeCoverageTool::attachBranchSubViews(SourceCoverageView &View,
  266. StringRef SourceName,
  267. ArrayRef<CountedRegion> Branches,
  268. const MemoryBuffer &File,
  269. CoverageData &CoverageInfo) {
  270. if (!ViewOpts.ShowBranchCounts && !ViewOpts.ShowBranchPercents)
  271. return;
  272. const auto *NextBranch = Branches.begin();
  273. const auto *EndBranch = Branches.end();
  274. // Group branches that have the same line number into the same subview.
  275. while (NextBranch != EndBranch) {
  276. std::vector<CountedRegion> ViewBranches;
  277. unsigned CurrentLine = NextBranch->LineStart;
  278. while (NextBranch != EndBranch && CurrentLine == NextBranch->LineStart)
  279. ViewBranches.push_back(*NextBranch++);
  280. if (!ViewBranches.empty()) {
  281. auto SubView = SourceCoverageView::create(SourceName, File, ViewOpts,
  282. std::move(CoverageInfo));
  283. View.addBranch(CurrentLine, ViewBranches, std::move(SubView));
  284. }
  285. }
  286. }
  287. std::unique_ptr<SourceCoverageView>
  288. CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
  289. const CoverageMapping &Coverage) {
  290. auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
  291. if (FunctionCoverage.empty())
  292. return nullptr;
  293. auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
  294. if (!SourceBuffer)
  295. return nullptr;
  296. auto Branches = FunctionCoverage.getBranches();
  297. auto Expansions = FunctionCoverage.getExpansions();
  298. auto View = SourceCoverageView::create(DC.demangle(Function.Name),
  299. SourceBuffer.get(), ViewOpts,
  300. std::move(FunctionCoverage));
  301. attachExpansionSubViews(*View, Expansions, Coverage);
  302. attachBranchSubViews(*View, DC.demangle(Function.Name), Branches,
  303. SourceBuffer.get(), FunctionCoverage);
  304. return View;
  305. }
  306. std::unique_ptr<SourceCoverageView>
  307. CodeCoverageTool::createSourceFileView(StringRef SourceFile,
  308. const CoverageMapping &Coverage) {
  309. auto SourceBuffer = getSourceFile(SourceFile);
  310. if (!SourceBuffer)
  311. return nullptr;
  312. auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
  313. if (FileCoverage.empty())
  314. return nullptr;
  315. auto Branches = FileCoverage.getBranches();
  316. auto Expansions = FileCoverage.getExpansions();
  317. auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
  318. ViewOpts, std::move(FileCoverage));
  319. attachExpansionSubViews(*View, Expansions, Coverage);
  320. attachBranchSubViews(*View, SourceFile, Branches, SourceBuffer.get(),
  321. FileCoverage);
  322. if (!ViewOpts.ShowFunctionInstantiations)
  323. return View;
  324. for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
  325. // Skip functions which have a single instantiation.
  326. if (Group.size() < 2)
  327. continue;
  328. for (const FunctionRecord *Function : Group.getInstantiations()) {
  329. std::unique_ptr<SourceCoverageView> SubView{nullptr};
  330. StringRef Funcname = DC.demangle(Function->Name);
  331. if (Function->ExecutionCount > 0) {
  332. auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
  333. auto SubViewExpansions = SubViewCoverage.getExpansions();
  334. auto SubViewBranches = SubViewCoverage.getBranches();
  335. SubView = SourceCoverageView::create(
  336. Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
  337. attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
  338. attachBranchSubViews(*SubView, SourceFile, SubViewBranches,
  339. SourceBuffer.get(), SubViewCoverage);
  340. }
  341. unsigned FileID = Function->CountedRegions.front().FileID;
  342. unsigned Line = 0;
  343. for (const auto &CR : Function->CountedRegions)
  344. if (CR.FileID == FileID)
  345. Line = std::max(CR.LineEnd, Line);
  346. View->addInstantiation(Funcname, Line, std::move(SubView));
  347. }
  348. }
  349. return View;
  350. }
  351. static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
  352. sys::fs::file_status Status;
  353. if (sys::fs::status(LHS, Status))
  354. return false;
  355. auto LHSTime = Status.getLastModificationTime();
  356. if (sys::fs::status(RHS, Status))
  357. return false;
  358. auto RHSTime = Status.getLastModificationTime();
  359. return LHSTime > RHSTime;
  360. }
  361. std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
  362. for (StringRef ObjectFilename : ObjectFilenames)
  363. if (modifiedTimeGT(ObjectFilename, PGOFilename))
  364. warning("profile data may be out of date - object is newer",
  365. ObjectFilename);
  366. auto CoverageOrErr =
  367. CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches,
  368. ViewOpts.CompilationDirectory);
  369. if (Error E = CoverageOrErr.takeError()) {
  370. error("Failed to load coverage: " + toString(std::move(E)),
  371. join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
  372. return nullptr;
  373. }
  374. auto Coverage = std::move(CoverageOrErr.get());
  375. unsigned Mismatched = Coverage->getMismatchedCount();
  376. if (Mismatched) {
  377. warning(Twine(Mismatched) + " functions have mismatched data");
  378. if (ViewOpts.Debug) {
  379. for (const auto &HashMismatch : Coverage->getHashMismatches())
  380. errs() << "hash-mismatch: "
  381. << "No profile record found for '" << HashMismatch.first << "'"
  382. << " with hash = 0x" << Twine::utohexstr(HashMismatch.second)
  383. << '\n';
  384. }
  385. }
  386. remapPathNames(*Coverage);
  387. if (!SourceFiles.empty())
  388. removeUnmappedInputs(*Coverage);
  389. demangleSymbols(*Coverage);
  390. return Coverage;
  391. }
  392. void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
  393. if (!PathRemapping)
  394. return;
  395. // Convert remapping paths to native paths with trailing seperators.
  396. auto nativeWithTrailing = [](StringRef Path) -> std::string {
  397. if (Path.empty())
  398. return "";
  399. SmallString<128> NativePath;
  400. sys::path::native(Path, NativePath);
  401. sys::path::remove_dots(NativePath, true);
  402. if (!NativePath.empty() && !sys::path::is_separator(NativePath.back()))
  403. NativePath += sys::path::get_separator();
  404. return NativePath.c_str();
  405. };
  406. std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
  407. std::string RemapTo = nativeWithTrailing(PathRemapping->second);
  408. // Create a mapping from coverage data file paths to local paths.
  409. for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
  410. SmallString<128> NativeFilename;
  411. sys::path::native(Filename, NativeFilename);
  412. sys::path::remove_dots(NativeFilename, true);
  413. if (NativeFilename.startswith(RemapFrom)) {
  414. RemappedFilenames[Filename] =
  415. RemapTo + NativeFilename.substr(RemapFrom.size()).str();
  416. }
  417. }
  418. // Convert input files from local paths to coverage data file paths.
  419. StringMap<std::string> InvRemappedFilenames;
  420. for (const auto &RemappedFilename : RemappedFilenames)
  421. InvRemappedFilenames[RemappedFilename.getValue()] =
  422. std::string(RemappedFilename.getKey());
  423. for (std::string &Filename : SourceFiles) {
  424. SmallString<128> NativeFilename;
  425. sys::path::native(Filename, NativeFilename);
  426. auto CovFileName = InvRemappedFilenames.find(NativeFilename);
  427. if (CovFileName != InvRemappedFilenames.end())
  428. Filename = CovFileName->second;
  429. }
  430. }
  431. void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
  432. std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
  433. // The user may have specified source files which aren't in the coverage
  434. // mapping. Filter these files away.
  435. llvm::erase_if(SourceFiles, [&](const std::string &SF) {
  436. return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(), SF);
  437. });
  438. }
  439. void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
  440. if (!ViewOpts.hasDemangler())
  441. return;
  442. // Pass function names to the demangler in a temporary file.
  443. int InputFD;
  444. SmallString<256> InputPath;
  445. std::error_code EC =
  446. sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
  447. if (EC) {
  448. error(InputPath, EC.message());
  449. return;
  450. }
  451. ToolOutputFile InputTOF{InputPath, InputFD};
  452. unsigned NumSymbols = 0;
  453. for (const auto &Function : Coverage.getCoveredFunctions()) {
  454. InputTOF.os() << Function.Name << '\n';
  455. ++NumSymbols;
  456. }
  457. InputTOF.os().close();
  458. // Use another temporary file to store the demangler's output.
  459. int OutputFD;
  460. SmallString<256> OutputPath;
  461. EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
  462. OutputPath);
  463. if (EC) {
  464. error(OutputPath, EC.message());
  465. return;
  466. }
  467. ToolOutputFile OutputTOF{OutputPath, OutputFD};
  468. OutputTOF.os().close();
  469. // Invoke the demangler.
  470. std::vector<StringRef> ArgsV;
  471. for (StringRef Arg : ViewOpts.DemanglerOpts)
  472. ArgsV.push_back(Arg);
  473. Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
  474. std::string ErrMsg;
  475. int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV,
  476. /*env=*/None, Redirects, /*secondsToWait=*/0,
  477. /*memoryLimit=*/0, &ErrMsg);
  478. if (RC) {
  479. error(ErrMsg, ViewOpts.DemanglerOpts[0]);
  480. return;
  481. }
  482. // Parse the demangler's output.
  483. auto BufOrError = MemoryBuffer::getFile(OutputPath);
  484. if (!BufOrError) {
  485. error(OutputPath, BufOrError.getError().message());
  486. return;
  487. }
  488. std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
  489. SmallVector<StringRef, 8> Symbols;
  490. StringRef DemanglerData = DemanglerBuf->getBuffer();
  491. DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
  492. /*KeepEmpty=*/false);
  493. if (Symbols.size() != NumSymbols) {
  494. error("Demangler did not provide expected number of symbols");
  495. return;
  496. }
  497. // Cache the demangled names.
  498. unsigned I = 0;
  499. for (const auto &Function : Coverage.getCoveredFunctions())
  500. // On Windows, lines in the demangler's output file end with "\r\n".
  501. // Splitting by '\n' keeps '\r's, so cut them now.
  502. DC.DemangledNames[Function.Name] = std::string(Symbols[I++].rtrim());
  503. }
  504. void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
  505. CoverageMapping *Coverage,
  506. CoveragePrinter *Printer,
  507. bool ShowFilenames) {
  508. auto View = createSourceFileView(SourceFile, *Coverage);
  509. if (!View) {
  510. warning("The file '" + SourceFile + "' isn't covered.");
  511. return;
  512. }
  513. auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
  514. if (Error E = OSOrErr.takeError()) {
  515. error("Could not create view file!", toString(std::move(E)));
  516. return;
  517. }
  518. auto OS = std::move(OSOrErr.get());
  519. View->print(*OS.get(), /*Wholefile=*/true,
  520. /*ShowSourceName=*/ShowFilenames,
  521. /*ShowTitle=*/ViewOpts.hasOutputDirectory());
  522. Printer->closeViewFile(std::move(OS));
  523. }
  524. int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
  525. cl::opt<std::string> CovFilename(
  526. cl::Positional, cl::desc("Covered executable or object file."));
  527. cl::list<std::string> CovFilenames(
  528. "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore);
  529. cl::opt<bool> DebugDumpCollectedObjects(
  530. "dump-collected-objects", cl::Optional, cl::Hidden,
  531. cl::desc("Show the collected coverage object files"));
  532. cl::list<std::string> InputSourceFiles(
  533. cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
  534. cl::opt<bool> DebugDumpCollectedPaths(
  535. "dump-collected-paths", cl::Optional, cl::Hidden,
  536. cl::desc("Show the collected paths to source files"));
  537. cl::opt<std::string, true> PGOFilename(
  538. "instr-profile", cl::Required, cl::location(this->PGOFilename),
  539. cl::desc(
  540. "File with the profile data obtained after an instrumented run"));
  541. cl::list<std::string> Arches(
  542. "arch", cl::desc("architectures of the coverage mapping binaries"));
  543. cl::opt<bool> DebugDump("dump", cl::Optional,
  544. cl::desc("Show internal debug dump"));
  545. cl::opt<CoverageViewOptions::OutputFormat> Format(
  546. "format", cl::desc("Output format for line-based coverage reports"),
  547. cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
  548. "Text output"),
  549. clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
  550. "HTML output"),
  551. clEnumValN(CoverageViewOptions::OutputFormat::Lcov, "lcov",
  552. "lcov tracefile output")),
  553. cl::init(CoverageViewOptions::OutputFormat::Text));
  554. cl::opt<std::string> PathRemap(
  555. "path-equivalence", cl::Optional,
  556. cl::desc("<from>,<to> Map coverage data paths to local source file "
  557. "paths"));
  558. cl::OptionCategory FilteringCategory("Function filtering options");
  559. cl::list<std::string> NameFilters(
  560. "name", cl::Optional,
  561. cl::desc("Show code coverage only for functions with the given name"),
  562. cl::ZeroOrMore, cl::cat(FilteringCategory));
  563. cl::list<std::string> NameFilterFiles(
  564. "name-allowlist", cl::Optional,
  565. cl::desc("Show code coverage only for functions listed in the given "
  566. "file"),
  567. cl::ZeroOrMore, cl::cat(FilteringCategory));
  568. // Allow for accepting previous option name.
  569. cl::list<std::string> NameFilterFilesDeprecated(
  570. "name-whitelist", cl::Optional, cl::Hidden,
  571. cl::desc("Show code coverage only for functions listed in the given "
  572. "file. Deprecated, use -name-allowlist instead"),
  573. cl::ZeroOrMore, cl::cat(FilteringCategory));
  574. cl::list<std::string> NameRegexFilters(
  575. "name-regex", cl::Optional,
  576. cl::desc("Show code coverage only for functions that match the given "
  577. "regular expression"),
  578. cl::ZeroOrMore, cl::cat(FilteringCategory));
  579. cl::list<std::string> IgnoreFilenameRegexFilters(
  580. "ignore-filename-regex", cl::Optional,
  581. cl::desc("Skip source code files with file paths that match the given "
  582. "regular expression"),
  583. cl::ZeroOrMore, cl::cat(FilteringCategory));
  584. cl::opt<double> RegionCoverageLtFilter(
  585. "region-coverage-lt", cl::Optional,
  586. cl::desc("Show code coverage only for functions with region coverage "
  587. "less than the given threshold"),
  588. cl::cat(FilteringCategory));
  589. cl::opt<double> RegionCoverageGtFilter(
  590. "region-coverage-gt", cl::Optional,
  591. cl::desc("Show code coverage only for functions with region coverage "
  592. "greater than the given threshold"),
  593. cl::cat(FilteringCategory));
  594. cl::opt<double> LineCoverageLtFilter(
  595. "line-coverage-lt", cl::Optional,
  596. cl::desc("Show code coverage only for functions with line coverage less "
  597. "than the given threshold"),
  598. cl::cat(FilteringCategory));
  599. cl::opt<double> LineCoverageGtFilter(
  600. "line-coverage-gt", cl::Optional,
  601. cl::desc("Show code coverage only for functions with line coverage "
  602. "greater than the given threshold"),
  603. cl::cat(FilteringCategory));
  604. cl::opt<cl::boolOrDefault> UseColor(
  605. "use-color", cl::desc("Emit colored output (default=autodetect)"),
  606. cl::init(cl::BOU_UNSET));
  607. cl::list<std::string> DemanglerOpts(
  608. "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
  609. cl::opt<bool> RegionSummary(
  610. "show-region-summary", cl::Optional,
  611. cl::desc("Show region statistics in summary table"),
  612. cl::init(true));
  613. cl::opt<bool> BranchSummary(
  614. "show-branch-summary", cl::Optional,
  615. cl::desc("Show branch condition statistics in summary table"),
  616. cl::init(true));
  617. cl::opt<bool> InstantiationSummary(
  618. "show-instantiation-summary", cl::Optional,
  619. cl::desc("Show instantiation statistics in summary table"));
  620. cl::opt<bool> SummaryOnly(
  621. "summary-only", cl::Optional,
  622. cl::desc("Export only summary information for each source file"));
  623. cl::opt<unsigned> NumThreads(
  624. "num-threads", cl::init(0),
  625. cl::desc("Number of merge threads to use (default: autodetect)"));
  626. cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
  627. cl::aliasopt(NumThreads));
  628. cl::opt<std::string> CompilationDirectory(
  629. "compilation-dir", cl::init(""),
  630. cl::desc("Directory used as a base for relative coverage mapping paths"));
  631. auto commandLineParser = [&, this](int argc, const char **argv) -> int {
  632. cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
  633. ViewOpts.Debug = DebugDump;
  634. if (!CovFilename.empty())
  635. ObjectFilenames.emplace_back(CovFilename);
  636. for (const std::string &Filename : CovFilenames)
  637. ObjectFilenames.emplace_back(Filename);
  638. if (ObjectFilenames.empty()) {
  639. errs() << "No filenames specified!\n";
  640. ::exit(1);
  641. }
  642. if (DebugDumpCollectedObjects) {
  643. for (StringRef OF : ObjectFilenames)
  644. outs() << OF << '\n';
  645. ::exit(0);
  646. }
  647. ViewOpts.Format = Format;
  648. switch (ViewOpts.Format) {
  649. case CoverageViewOptions::OutputFormat::Text:
  650. ViewOpts.Colors = UseColor == cl::BOU_UNSET
  651. ? sys::Process::StandardOutHasColors()
  652. : UseColor == cl::BOU_TRUE;
  653. break;
  654. case CoverageViewOptions::OutputFormat::HTML:
  655. if (UseColor == cl::BOU_FALSE)
  656. errs() << "Color output cannot be disabled when generating html.\n";
  657. ViewOpts.Colors = true;
  658. break;
  659. case CoverageViewOptions::OutputFormat::Lcov:
  660. if (UseColor == cl::BOU_TRUE)
  661. errs() << "Color output cannot be enabled when generating lcov.\n";
  662. ViewOpts.Colors = false;
  663. break;
  664. }
  665. // If path-equivalence was given and is a comma seperated pair then set
  666. // PathRemapping.
  667. if (!PathRemap.empty()) {
  668. auto EquivPair = StringRef(PathRemap).split(',');
  669. if (EquivPair.first.empty() || EquivPair.second.empty()) {
  670. error("invalid argument '" + PathRemap +
  671. "', must be in format 'from,to'",
  672. "-path-equivalence");
  673. return 1;
  674. }
  675. PathRemapping = {std::string(EquivPair.first),
  676. std::string(EquivPair.second)};
  677. }
  678. // If a demangler is supplied, check if it exists and register it.
  679. if (!DemanglerOpts.empty()) {
  680. auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
  681. if (!DemanglerPathOrErr) {
  682. error("Could not find the demangler!",
  683. DemanglerPathOrErr.getError().message());
  684. return 1;
  685. }
  686. DemanglerOpts[0] = *DemanglerPathOrErr;
  687. ViewOpts.DemanglerOpts.swap(DemanglerOpts);
  688. }
  689. // Read in -name-allowlist files.
  690. if (!NameFilterFiles.empty() || !NameFilterFilesDeprecated.empty()) {
  691. std::string SpecialCaseListErr;
  692. if (!NameFilterFiles.empty())
  693. NameAllowlist = SpecialCaseList::create(
  694. NameFilterFiles, *vfs::getRealFileSystem(), SpecialCaseListErr);
  695. if (!NameFilterFilesDeprecated.empty())
  696. NameAllowlist = SpecialCaseList::create(NameFilterFilesDeprecated,
  697. *vfs::getRealFileSystem(),
  698. SpecialCaseListErr);
  699. if (!NameAllowlist)
  700. error(SpecialCaseListErr);
  701. }
  702. // Create the function filters
  703. if (!NameFilters.empty() || NameAllowlist || !NameRegexFilters.empty()) {
  704. auto NameFilterer = std::make_unique<CoverageFilters>();
  705. for (const auto &Name : NameFilters)
  706. NameFilterer->push_back(std::make_unique<NameCoverageFilter>(Name));
  707. if (NameAllowlist) {
  708. if (!NameFilterFiles.empty())
  709. NameFilterer->push_back(
  710. std::make_unique<NameAllowlistCoverageFilter>(*NameAllowlist));
  711. if (!NameFilterFilesDeprecated.empty())
  712. NameFilterer->push_back(
  713. std::make_unique<NameWhitelistCoverageFilter>(*NameAllowlist));
  714. }
  715. for (const auto &Regex : NameRegexFilters)
  716. NameFilterer->push_back(
  717. std::make_unique<NameRegexCoverageFilter>(Regex));
  718. Filters.push_back(std::move(NameFilterer));
  719. }
  720. if (RegionCoverageLtFilter.getNumOccurrences() ||
  721. RegionCoverageGtFilter.getNumOccurrences() ||
  722. LineCoverageLtFilter.getNumOccurrences() ||
  723. LineCoverageGtFilter.getNumOccurrences()) {
  724. auto StatFilterer = std::make_unique<CoverageFilters>();
  725. if (RegionCoverageLtFilter.getNumOccurrences())
  726. StatFilterer->push_back(std::make_unique<RegionCoverageFilter>(
  727. RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
  728. if (RegionCoverageGtFilter.getNumOccurrences())
  729. StatFilterer->push_back(std::make_unique<RegionCoverageFilter>(
  730. RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
  731. if (LineCoverageLtFilter.getNumOccurrences())
  732. StatFilterer->push_back(std::make_unique<LineCoverageFilter>(
  733. LineCoverageFilter::LessThan, LineCoverageLtFilter));
  734. if (LineCoverageGtFilter.getNumOccurrences())
  735. StatFilterer->push_back(std::make_unique<LineCoverageFilter>(
  736. RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
  737. Filters.push_back(std::move(StatFilterer));
  738. }
  739. // Create the ignore filename filters.
  740. for (const auto &RE : IgnoreFilenameRegexFilters)
  741. IgnoreFilenameFilters.push_back(
  742. std::make_unique<NameRegexCoverageFilter>(RE));
  743. if (!Arches.empty()) {
  744. for (const std::string &Arch : Arches) {
  745. if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
  746. error("Unknown architecture: " + Arch);
  747. return 1;
  748. }
  749. CoverageArches.emplace_back(Arch);
  750. }
  751. if (CoverageArches.size() != ObjectFilenames.size()) {
  752. error("Number of architectures doesn't match the number of objects");
  753. return 1;
  754. }
  755. }
  756. // IgnoreFilenameFilters are applied even when InputSourceFiles specified.
  757. for (const std::string &File : InputSourceFiles)
  758. collectPaths(File);
  759. if (DebugDumpCollectedPaths) {
  760. for (const std::string &SF : SourceFiles)
  761. outs() << SF << '\n';
  762. ::exit(0);
  763. }
  764. ViewOpts.ShowBranchSummary = BranchSummary;
  765. ViewOpts.ShowRegionSummary = RegionSummary;
  766. ViewOpts.ShowInstantiationSummary = InstantiationSummary;
  767. ViewOpts.ExportSummaryOnly = SummaryOnly;
  768. ViewOpts.NumThreads = NumThreads;
  769. ViewOpts.CompilationDirectory = CompilationDirectory;
  770. return 0;
  771. };
  772. switch (Cmd) {
  773. case Show:
  774. return doShow(argc, argv, commandLineParser);
  775. case Report:
  776. return doReport(argc, argv, commandLineParser);
  777. case Export:
  778. return doExport(argc, argv, commandLineParser);
  779. }
  780. return 0;
  781. }
  782. int CodeCoverageTool::doShow(int argc, const char **argv,
  783. CommandLineParserType commandLineParser) {
  784. cl::OptionCategory ViewCategory("Viewing options");
  785. cl::opt<bool> ShowLineExecutionCounts(
  786. "show-line-counts", cl::Optional,
  787. cl::desc("Show the execution counts for each line"), cl::init(true),
  788. cl::cat(ViewCategory));
  789. cl::opt<bool> ShowRegions(
  790. "show-regions", cl::Optional,
  791. cl::desc("Show the execution counts for each region"),
  792. cl::cat(ViewCategory));
  793. cl::opt<CoverageViewOptions::BranchOutputType> ShowBranches(
  794. "show-branches", cl::Optional,
  795. cl::desc("Show coverage for branch conditions"), cl::cat(ViewCategory),
  796. cl::values(clEnumValN(CoverageViewOptions::BranchOutputType::Count,
  797. "count", "Show True/False counts"),
  798. clEnumValN(CoverageViewOptions::BranchOutputType::Percent,
  799. "percent", "Show True/False percent")),
  800. cl::init(CoverageViewOptions::BranchOutputType::Off));
  801. cl::opt<bool> ShowBestLineRegionsCounts(
  802. "show-line-counts-or-regions", cl::Optional,
  803. cl::desc("Show the execution counts for each line, or the execution "
  804. "counts for each region on lines that have multiple regions"),
  805. cl::cat(ViewCategory));
  806. cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
  807. cl::desc("Show expanded source regions"),
  808. cl::cat(ViewCategory));
  809. cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
  810. cl::desc("Show function instantiations"),
  811. cl::init(true), cl::cat(ViewCategory));
  812. cl::opt<std::string> ShowOutputDirectory(
  813. "output-dir", cl::init(""),
  814. cl::desc("Directory in which coverage information is written out"));
  815. cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
  816. cl::aliasopt(ShowOutputDirectory));
  817. cl::opt<uint32_t> TabSize(
  818. "tab-size", cl::init(2),
  819. cl::desc(
  820. "Set tab expansion size for html coverage reports (default = 2)"));
  821. cl::opt<std::string> ProjectTitle(
  822. "project-title", cl::Optional,
  823. cl::desc("Set project title for the coverage report"));
  824. auto Err = commandLineParser(argc, argv);
  825. if (Err)
  826. return Err;
  827. if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
  828. error("Lcov format should be used with 'llvm-cov export'.");
  829. return 1;
  830. }
  831. ViewOpts.ShowLineNumbers = true;
  832. ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
  833. !ShowRegions || ShowBestLineRegionsCounts;
  834. ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
  835. ViewOpts.ShowExpandedRegions = ShowExpansions;
  836. ViewOpts.ShowBranchCounts =
  837. ShowBranches == CoverageViewOptions::BranchOutputType::Count;
  838. ViewOpts.ShowBranchPercents =
  839. ShowBranches == CoverageViewOptions::BranchOutputType::Percent;
  840. ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
  841. ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
  842. ViewOpts.TabSize = TabSize;
  843. ViewOpts.ProjectTitle = ProjectTitle;
  844. if (ViewOpts.hasOutputDirectory()) {
  845. if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
  846. error("Could not create output directory!", E.message());
  847. return 1;
  848. }
  849. }
  850. sys::fs::file_status Status;
  851. if (std::error_code EC = sys::fs::status(PGOFilename, Status)) {
  852. error("Could not read profile data!", EC.message());
  853. return 1;
  854. }
  855. auto ModifiedTime = Status.getLastModificationTime();
  856. std::string ModifiedTimeStr = to_string(ModifiedTime);
  857. size_t found = ModifiedTimeStr.rfind(':');
  858. ViewOpts.CreatedTimeStr = (found != std::string::npos)
  859. ? "Created: " + ModifiedTimeStr.substr(0, found)
  860. : "Created: " + ModifiedTimeStr;
  861. auto Coverage = load();
  862. if (!Coverage)
  863. return 1;
  864. auto Printer = CoveragePrinter::create(ViewOpts);
  865. if (SourceFiles.empty() && !HadSourceFiles)
  866. // Get the source files from the function coverage mapping.
  867. for (StringRef Filename : Coverage->getUniqueSourceFiles()) {
  868. if (!IgnoreFilenameFilters.matchesFilename(Filename))
  869. SourceFiles.push_back(std::string(Filename));
  870. }
  871. // Create an index out of the source files.
  872. if (ViewOpts.hasOutputDirectory()) {
  873. if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) {
  874. error("Could not create index file!", toString(std::move(E)));
  875. return 1;
  876. }
  877. }
  878. if (!Filters.empty()) {
  879. // Build the map of filenames to functions.
  880. std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
  881. FilenameFunctionMap;
  882. for (const auto &SourceFile : SourceFiles)
  883. for (const auto &Function : Coverage->getCoveredFunctions(SourceFile))
  884. if (Filters.matches(*Coverage.get(), Function))
  885. FilenameFunctionMap[SourceFile].push_back(&Function);
  886. // Only print filter matching functions for each file.
  887. for (const auto &FileFunc : FilenameFunctionMap) {
  888. StringRef File = FileFunc.first;
  889. const auto &Functions = FileFunc.second;
  890. auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false);
  891. if (Error E = OSOrErr.takeError()) {
  892. error("Could not create view file!", toString(std::move(E)));
  893. return 1;
  894. }
  895. auto OS = std::move(OSOrErr.get());
  896. bool ShowTitle = ViewOpts.hasOutputDirectory();
  897. for (const auto *Function : Functions) {
  898. auto FunctionView = createFunctionView(*Function, *Coverage);
  899. if (!FunctionView) {
  900. warning("Could not read coverage for '" + Function->Name + "'.");
  901. continue;
  902. }
  903. FunctionView->print(*OS.get(), /*WholeFile=*/false,
  904. /*ShowSourceName=*/true, ShowTitle);
  905. ShowTitle = false;
  906. }
  907. Printer->closeViewFile(std::move(OS));
  908. }
  909. return 0;
  910. }
  911. // Show files
  912. bool ShowFilenames =
  913. (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
  914. (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
  915. ThreadPoolStrategy S = hardware_concurrency(ViewOpts.NumThreads);
  916. if (ViewOpts.NumThreads == 0) {
  917. // If NumThreads is not specified, create one thread for each input, up to
  918. // the number of hardware cores.
  919. S = heavyweight_hardware_concurrency(SourceFiles.size());
  920. S.Limit = true;
  921. }
  922. if (!ViewOpts.hasOutputDirectory() || S.ThreadsRequested == 1) {
  923. for (const std::string &SourceFile : SourceFiles)
  924. writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
  925. ShowFilenames);
  926. } else {
  927. // In -output-dir mode, it's safe to use multiple threads to print files.
  928. ThreadPool Pool(S);
  929. for (const std::string &SourceFile : SourceFiles)
  930. Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
  931. Coverage.get(), Printer.get(), ShowFilenames);
  932. Pool.wait();
  933. }
  934. return 0;
  935. }
  936. int CodeCoverageTool::doReport(int argc, const char **argv,
  937. CommandLineParserType commandLineParser) {
  938. cl::opt<bool> ShowFunctionSummaries(
  939. "show-functions", cl::Optional, cl::init(false),
  940. cl::desc("Show coverage summaries for each function"));
  941. auto Err = commandLineParser(argc, argv);
  942. if (Err)
  943. return Err;
  944. if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
  945. error("HTML output for summary reports is not yet supported.");
  946. return 1;
  947. } else if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
  948. error("Lcov format should be used with 'llvm-cov export'.");
  949. return 1;
  950. }
  951. auto Coverage = load();
  952. if (!Coverage)
  953. return 1;
  954. CoverageReport Report(ViewOpts, *Coverage.get());
  955. if (!ShowFunctionSummaries) {
  956. if (SourceFiles.empty())
  957. Report.renderFileReports(llvm::outs(), IgnoreFilenameFilters);
  958. else
  959. Report.renderFileReports(llvm::outs(), SourceFiles);
  960. } else {
  961. if (SourceFiles.empty()) {
  962. error("Source files must be specified when -show-functions=true is "
  963. "specified");
  964. return 1;
  965. }
  966. Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
  967. }
  968. return 0;
  969. }
  970. int CodeCoverageTool::doExport(int argc, const char **argv,
  971. CommandLineParserType commandLineParser) {
  972. cl::OptionCategory ExportCategory("Exporting options");
  973. cl::opt<bool> SkipExpansions("skip-expansions", cl::Optional,
  974. cl::desc("Don't export expanded source regions"),
  975. cl::cat(ExportCategory));
  976. cl::opt<bool> SkipFunctions("skip-functions", cl::Optional,
  977. cl::desc("Don't export per-function data"),
  978. cl::cat(ExportCategory));
  979. auto Err = commandLineParser(argc, argv);
  980. if (Err)
  981. return Err;
  982. ViewOpts.SkipExpansions = SkipExpansions;
  983. ViewOpts.SkipFunctions = SkipFunctions;
  984. if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text &&
  985. ViewOpts.Format != CoverageViewOptions::OutputFormat::Lcov) {
  986. error("Coverage data can only be exported as textual JSON or an "
  987. "lcov tracefile.");
  988. return 1;
  989. }
  990. auto Coverage = load();
  991. if (!Coverage) {
  992. error("Could not load coverage information");
  993. return 1;
  994. }
  995. std::unique_ptr<CoverageExporter> Exporter;
  996. switch (ViewOpts.Format) {
  997. case CoverageViewOptions::OutputFormat::Text:
  998. Exporter = std::make_unique<CoverageExporterJson>(*Coverage.get(),
  999. ViewOpts, outs());
  1000. break;
  1001. case CoverageViewOptions::OutputFormat::HTML:
  1002. // Unreachable because we should have gracefully terminated with an error
  1003. // above.
  1004. llvm_unreachable("Export in HTML is not supported!");
  1005. case CoverageViewOptions::OutputFormat::Lcov:
  1006. Exporter = std::make_unique<CoverageExporterLcov>(*Coverage.get(),
  1007. ViewOpts, outs());
  1008. break;
  1009. }
  1010. if (SourceFiles.empty())
  1011. Exporter->renderRoot(IgnoreFilenameFilters);
  1012. else
  1013. Exporter->renderRoot(SourceFiles);
  1014. return 0;
  1015. }
  1016. int showMain(int argc, const char *argv[]) {
  1017. CodeCoverageTool Tool;
  1018. return Tool.run(CodeCoverageTool::Show, argc, argv);
  1019. }
  1020. int reportMain(int argc, const char *argv[]) {
  1021. CodeCoverageTool Tool;
  1022. return Tool.run(CodeCoverageTool::Report, argc, argv);
  1023. }
  1024. int exportMain(int argc, const char *argv[]) {
  1025. CodeCoverageTool Tool;
  1026. return Tool.run(CodeCoverageTool::Export, argc, argv);
  1027. }