CodeCoverage.cpp 46 KB

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