CodeCoverage.cpp 36 KB

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