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
15#include "CoverageExporterJson.h"
16#include "CoverageExporterLcov.h"
17#include "CoverageFilters.h"
18#include "CoverageReport.h"
19#include "CoverageSummaryInfo.h"
20#include "CoverageViewOptions.h"
21#include "RenderingSupport.h"
22#include "SourceCoverageView.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Debuginfod/BuildIDFetcher.h"
26#include "llvm/Debuginfod/Debuginfod.h"
27#include "llvm/HTTP/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 "llvm/TargetParser/Triple.h"
45
46#include <functional>
47#include <map>
48#include <optional>
49#include <system_error>
50
51using namespace llvm;
52using namespace coverage;
53
54namespace {
55/// The implementation of the coverage tool.
56class CodeCoverageTool {
57public:
58 enum Command {
59 /// The show command.
60 Show,
61 /// The report command.
62 Report,
63 /// The export command.
64 Export
65 };
66
67 int run(Command Cmd, int argc, const char **argv);
68
69private:
70 /// Print the error message to the error output stream.
71 void error(const Twine &Message, StringRef Whence = "");
72
73 /// Print the warning message to the error output stream.
74 void warning(const Twine &Message, StringRef Whence = "");
75
76 /// Convert \p Path into an absolute path and append it to the list
77 /// of collected paths.
78 void addCollectedPath(const std::string &Path);
79
80 /// If \p Path is a regular file, collect the path. If it's a
81 /// directory, recursively collect all of the paths within the directory.
82 void collectPaths(const std::string &Path);
83
84 /// Check if the two given files are the same file.
85 bool isEquivalentFile(StringRef FilePath1, StringRef FilePath2);
86
87 /// Retrieve a file status with a cache.
88 std::optional<sys::fs::file_status> getFileStatus(StringRef FilePath);
89
90 /// Return a memory buffer for the given source file.
91 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
92
93 /// Create source views for the expansions of the view.
94 void attachExpansionSubViews(SourceCoverageView &View,
95 ArrayRef<ExpansionRecord> Expansions,
96 const CoverageMapping &Coverage);
97
98 /// Create source views for the branches of the view.
99 void attachBranchSubViews(SourceCoverageView &View,
100 ArrayRef<CountedRegion> Branches);
101
102 /// Create source views for the MCDC records.
103 void attachMCDCSubViews(SourceCoverageView &View,
104 ArrayRef<MCDCRecord> MCDCRecords);
105
106 /// Create the source view of a particular function.
107 std::unique_ptr<SourceCoverageView>
108 createFunctionView(const FunctionRecord &Function,
109 const CoverageMapping &Coverage);
110
111 /// Create the main source view of a particular source file.
112 std::unique_ptr<SourceCoverageView>
113 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
114
115 /// Load the coverage mapping data. Return nullptr if an error occurred.
116 std::unique_ptr<CoverageMapping> load();
117
118 /// Create a mapping from files in the Coverage data to local copies
119 /// (path-equivalence).
120 void remapPathNames(const CoverageMapping &Coverage);
121
122 /// Remove input source files which aren't mapped by \p Coverage.
123 void removeUnmappedInputs(const CoverageMapping &Coverage);
124
125 /// If a demangler is available, demangle all symbol names.
126 void demangleSymbols(const CoverageMapping &Coverage);
127
128 /// Write out a source file view to the filesystem.
129 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
130 CoveragePrinter *Printer, bool ShowFilenames);
131
132 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
133
134 int doShow(int argc, const char **argv,
135 CommandLineParserType commandLineParser);
136
137 int doReport(int argc, const char **argv,
138 CommandLineParserType commandLineParser);
139
140 int doExport(int argc, const char **argv,
141 CommandLineParserType commandLineParser);
142
143 std::vector<StringRef> ObjectFilenames;
144 CoverageViewOptions ViewOpts;
145 CoverageFiltersMatchAll Filters;
146 CoverageFilters FilenameFilters;
147
148 /// True if InputSourceFiles are provided.
149 bool HadSourceFiles = false;
150
151 /// The path to the indexed profile.
152 std::optional<std::string> PGOFilename;
153
154 /// A list of input source files.
155 std::vector<std::string> SourceFiles;
156
157 /// In -path-equivalence mode, this maps the absolute paths from the coverage
158 /// mapping data to the input source files.
159 StringMap<std::string> RemappedFilenames;
160
161 /// The coverage data path to be remapped from, and the source path to be
162 /// remapped to, when using -path-equivalence.
163 std::optional<std::vector<std::pair<std::string, std::string>>>
164 PathRemappings;
165
166 /// File status cache used when finding the same file.
167 StringMap<std::optional<sys::fs::file_status>> FileStatusCache;
168
169 /// The architecture the coverage mapping data targets.
170 std::vector<StringRef> CoverageArches;
171
172 /// A cache for demangled symbols.
173 DemangleCache DC;
174
175 /// A lock which guards printing to stderr.
176 std::mutex ErrsLock;
177
178 /// A container for input source file buffers.
179 std::mutex LoadedSourceFilesLock;
180 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
181 LoadedSourceFiles;
182
183 /// Allowlist from -name-allowlist to be used for filtering.
184 std::unique_ptr<SpecialCaseList> NameAllowlist;
185
186 std::unique_ptr<object::BuildIDFetcher> BIDFetcher;
187
188 bool CheckBinaryIDs;
189};
190}
191
192static std::string getErrorString(const Twine &Message, StringRef Whence,
193 bool Warning) {
194 std::string Str = (Warning ? "warning" : "error");
195 Str += ": ";
196 if (!Whence.empty())
197 Str += Whence.str() + ": ";
198 Str += Message.str() + "\n";
199 return Str;
200}
201
202void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
203 std::unique_lock<std::mutex> Guard{ErrsLock};
204 ViewOpts.colored_ostream(OS&: errs(), Color: raw_ostream::RED)
205 << getErrorString(Message, Whence, Warning: false);
206}
207
208void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
209 std::unique_lock<std::mutex> Guard{ErrsLock};
210 ViewOpts.colored_ostream(OS&: errs(), Color: raw_ostream::RED)
211 << getErrorString(Message, Whence, Warning: true);
212}
213
214void CodeCoverageTool::addCollectedPath(const std::string &Path) {
215 SmallString<128> EffectivePath(Path);
216 if (std::error_code EC = sys::fs::make_absolute(path&: EffectivePath)) {
217 error(Message: EC.message(), Whence: Path);
218 return;
219 }
220 sys::path::remove_dots(path&: EffectivePath, /*remove_dot_dot=*/true);
221 if (!FilenameFilters.matchesFilename(Filename: EffectivePath))
222 SourceFiles.emplace_back(args: EffectivePath.str());
223 HadSourceFiles = !SourceFiles.empty();
224}
225
226void CodeCoverageTool::collectPaths(const std::string &Path) {
227 llvm::sys::fs::file_status Status;
228 llvm::sys::fs::status(path: Path, result&: Status);
229 if (!llvm::sys::fs::exists(status: Status)) {
230 if (PathRemappings)
231 addCollectedPath(Path);
232 else
233 warning(Message: "Source file doesn't exist, proceeded by ignoring it.", Whence: Path);
234 return;
235 }
236
237 if (llvm::sys::fs::is_regular_file(status: Status)) {
238 addCollectedPath(Path);
239 return;
240 }
241
242 if (llvm::sys::fs::is_directory(status: Status)) {
243 std::error_code EC;
244 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
245 F != E; F.increment(ec&: EC)) {
246
247 auto Status = F->status();
248 if (!Status) {
249 warning(Message: Status.getError().message(), Whence: F->path());
250 continue;
251 }
252
253 if (Status->type() == llvm::sys::fs::file_type::regular_file)
254 addCollectedPath(Path: F->path());
255 }
256 }
257}
258
259std::optional<sys::fs::file_status>
260CodeCoverageTool::getFileStatus(StringRef FilePath) {
261 auto It = FileStatusCache.try_emplace(Key: FilePath);
262 auto &CachedStatus = It.first->getValue();
263 if (!It.second)
264 return CachedStatus;
265
266 sys::fs::file_status Status;
267 if (!sys::fs::status(path: FilePath, result&: Status))
268 CachedStatus = Status;
269 return CachedStatus;
270}
271
272bool CodeCoverageTool::isEquivalentFile(StringRef FilePath1,
273 StringRef FilePath2) {
274 auto Status1 = getFileStatus(FilePath: FilePath1);
275 auto Status2 = getFileStatus(FilePath: FilePath2);
276 return Status1 && Status2 && sys::fs::equivalent(A: *Status1, B: *Status2);
277}
278
279ErrorOr<const MemoryBuffer &>
280CodeCoverageTool::getSourceFile(StringRef SourceFile) {
281 // If we've remapped filenames, look up the real location for this file.
282 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
283 if (!RemappedFilenames.empty()) {
284 auto Loc = RemappedFilenames.find(Key: SourceFile);
285 if (Loc != RemappedFilenames.end())
286 SourceFile = Loc->second;
287 }
288 for (const auto &Files : LoadedSourceFiles)
289 if (isEquivalentFile(FilePath1: SourceFile, FilePath2: Files.first))
290 return *Files.second;
291 auto Buffer = MemoryBuffer::getFile(Filename: SourceFile);
292 if (auto EC = Buffer.getError()) {
293 error(Message: EC.message(), Whence: SourceFile);
294 return EC;
295 }
296 LoadedSourceFiles.emplace_back(args: std::string(SourceFile),
297 args: std::move(Buffer.get()));
298 return *LoadedSourceFiles.back().second;
299}
300
301void CodeCoverageTool::attachExpansionSubViews(
302 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
303 const CoverageMapping &Coverage) {
304 if (!ViewOpts.ShowExpandedRegions)
305 return;
306 for (const auto &Expansion : Expansions) {
307 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
308 if (ExpansionCoverage.empty())
309 continue;
310 auto SourceBuffer = getSourceFile(SourceFile: ExpansionCoverage.getFilename());
311 if (!SourceBuffer)
312 continue;
313
314 auto SubViewBranches = ExpansionCoverage.getBranches();
315 auto SubViewExpansions = ExpansionCoverage.getExpansions();
316 auto SubView =
317 SourceCoverageView::create(SourceName: Expansion.Function.Name, File: SourceBuffer.get(),
318 Options: ViewOpts, CoverageInfo: std::move(ExpansionCoverage));
319 attachExpansionSubViews(View&: *SubView, Expansions: SubViewExpansions, Coverage);
320 attachBranchSubViews(View&: *SubView, Branches: SubViewBranches);
321 View.addExpansion(Region: Expansion.Region, View: std::move(SubView));
322 }
323}
324
325void CodeCoverageTool::attachBranchSubViews(SourceCoverageView &View,
326 ArrayRef<CountedRegion> Branches) {
327 if (!ViewOpts.ShowBranchCounts && !ViewOpts.ShowBranchPercents)
328 return;
329
330 const auto *NextBranch = Branches.begin();
331 const auto *EndBranch = Branches.end();
332
333 // Group branches that have the same line number into the same subview.
334 while (NextBranch != EndBranch) {
335 SmallVector<CountedRegion, 0> ViewBranches;
336 unsigned CurrentLine = NextBranch->LineStart;
337 while (NextBranch != EndBranch && CurrentLine == NextBranch->LineStart)
338 ViewBranches.push_back(Elt: *NextBranch++);
339
340 View.addBranch(Line: CurrentLine, Regions: std::move(ViewBranches));
341 }
342}
343
344void CodeCoverageTool::attachMCDCSubViews(SourceCoverageView &View,
345 ArrayRef<MCDCRecord> MCDCRecords) {
346 if (!ViewOpts.ShowMCDC)
347 return;
348
349 const auto *NextRecord = MCDCRecords.begin();
350 const auto *EndRecord = MCDCRecords.end();
351
352 // Group and process MCDC records that have the same line number into the
353 // same subview.
354 while (NextRecord != EndRecord) {
355 SmallVector<MCDCRecord, 0> ViewMCDCRecords;
356 unsigned CurrentLine = NextRecord->getDecisionRegion().LineEnd;
357 while (NextRecord != EndRecord &&
358 CurrentLine == NextRecord->getDecisionRegion().LineEnd)
359 ViewMCDCRecords.push_back(Elt: *NextRecord++);
360
361 View.addMCDCRecord(Line: CurrentLine, Records: std::move(ViewMCDCRecords));
362 }
363}
364
365std::unique_ptr<SourceCoverageView>
366CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
367 const CoverageMapping &Coverage) {
368 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
369 if (FunctionCoverage.empty())
370 return nullptr;
371 auto SourceBuffer = getSourceFile(SourceFile: FunctionCoverage.getFilename());
372 if (!SourceBuffer)
373 return nullptr;
374
375 auto Branches = FunctionCoverage.getBranches();
376 auto Expansions = FunctionCoverage.getExpansions();
377 auto MCDCRecords = FunctionCoverage.getMCDCRecords();
378 auto View = SourceCoverageView::create(SourceName: DC.demangle(Sym: Function.Name),
379 File: SourceBuffer.get(), Options: ViewOpts,
380 CoverageInfo: std::move(FunctionCoverage));
381 attachExpansionSubViews(View&: *View, Expansions, Coverage);
382 attachBranchSubViews(View&: *View, Branches);
383 attachMCDCSubViews(View&: *View, MCDCRecords);
384
385 return View;
386}
387
388std::unique_ptr<SourceCoverageView>
389CodeCoverageTool::createSourceFileView(StringRef SourceFile,
390 const CoverageMapping &Coverage) {
391 auto SourceBuffer = getSourceFile(SourceFile);
392 if (!SourceBuffer)
393 return nullptr;
394 auto FileCoverage = Coverage.getCoverageForFile(Filename: SourceFile);
395 if (FileCoverage.empty())
396 return nullptr;
397
398 auto Branches = FileCoverage.getBranches();
399 auto Expansions = FileCoverage.getExpansions();
400 auto MCDCRecords = FileCoverage.getMCDCRecords();
401 auto View = SourceCoverageView::create(SourceName: SourceFile, File: SourceBuffer.get(),
402 Options: ViewOpts, CoverageInfo: std::move(FileCoverage));
403 attachExpansionSubViews(View&: *View, Expansions, Coverage);
404 attachBranchSubViews(View&: *View, Branches);
405 attachMCDCSubViews(View&: *View, MCDCRecords);
406 if (!ViewOpts.ShowFunctionInstantiations)
407 return View;
408
409 for (const auto &Group : Coverage.getInstantiationGroups(Filename: SourceFile)) {
410 // Skip functions which have a single instantiation.
411 if (Group.size() < 2)
412 continue;
413
414 for (const FunctionRecord *Function : Group.getInstantiations()) {
415 std::unique_ptr<SourceCoverageView> SubView{nullptr};
416
417 StringRef Funcname = DC.demangle(Sym: Function->Name);
418
419 if (Function->ExecutionCount > 0) {
420 auto SubViewCoverage = Coverage.getCoverageForFunction(Function: *Function);
421 auto SubViewExpansions = SubViewCoverage.getExpansions();
422 auto SubViewBranches = SubViewCoverage.getBranches();
423 auto SubViewMCDCRecords = SubViewCoverage.getMCDCRecords();
424 SubView = SourceCoverageView::create(
425 SourceName: Funcname, File: SourceBuffer.get(), Options: ViewOpts, CoverageInfo: std::move(SubViewCoverage));
426 attachExpansionSubViews(View&: *SubView, Expansions: SubViewExpansions, Coverage);
427 attachBranchSubViews(View&: *SubView, Branches: SubViewBranches);
428 attachMCDCSubViews(View&: *SubView, MCDCRecords: SubViewMCDCRecords);
429 }
430
431 unsigned FileID = Function->CountedRegions.front().FileID;
432 unsigned Line = 0;
433 for (const auto &CR : Function->CountedRegions)
434 if (CR.FileID == FileID)
435 Line = std::max(a: CR.LineEnd, b: Line);
436 View->addInstantiation(FunctionName: Funcname, Line, View: std::move(SubView));
437 }
438 }
439 return View;
440}
441
442static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
443 sys::fs::file_status Status;
444 if (sys::fs::status(path: LHS, result&: Status))
445 return false;
446 auto LHSTime = Status.getLastModificationTime();
447 if (sys::fs::status(path: RHS, result&: Status))
448 return false;
449 auto RHSTime = Status.getLastModificationTime();
450 return LHSTime > RHSTime;
451}
452
453std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
454 if (PGOFilename) {
455 for (StringRef ObjectFilename : ObjectFilenames)
456 if (modifiedTimeGT(LHS: ObjectFilename, RHS: PGOFilename.value()))
457 warning(Message: "profile data may be out of date - object is newer",
458 Whence: ObjectFilename);
459 }
460 auto FS = vfs::getRealFileSystem();
461 auto CoverageOrErr = CoverageMapping::load(
462 ObjectFilenames, ProfileFilename: PGOFilename, FS&: *FS, Arches: CoverageArches,
463 CompilationDir: ViewOpts.CompilationDirectory, BIDFetcher: BIDFetcher.get(), CheckBinaryIDs);
464 if (Error E = CoverageOrErr.takeError()) {
465 error(Message: "failed to load coverage: " + toString(E: std::move(E)));
466 return nullptr;
467 }
468 auto Coverage = std::move(CoverageOrErr.get());
469 unsigned Mismatched = Coverage->getMismatchedCount();
470 if (Mismatched) {
471 warning(Message: Twine(Mismatched) + " functions have mismatched data");
472
473 if (ViewOpts.Debug) {
474 for (const auto &HashMismatch : Coverage->getHashMismatches())
475 errs() << "hash-mismatch: "
476 << "No profile record found for '" << HashMismatch.first << "'"
477 << " with hash = 0x" << Twine::utohexstr(Val: HashMismatch.second)
478 << '\n';
479 }
480 }
481
482 remapPathNames(Coverage: *Coverage);
483
484 if (!SourceFiles.empty())
485 removeUnmappedInputs(Coverage: *Coverage);
486
487 demangleSymbols(Coverage: *Coverage);
488
489 return Coverage;
490}
491
492void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
493 if (!PathRemappings)
494 return;
495
496 // Convert remapping paths to native paths with trailing separators.
497 auto nativeWithTrailing = [](StringRef Path) -> std::string {
498 if (Path.empty())
499 return "";
500 SmallString<128> NativePath;
501 sys::path::native(path: Path, result&: NativePath);
502 sys::path::remove_dots(path&: NativePath, remove_dot_dot: true);
503 if (!NativePath.empty() && !sys::path::is_separator(value: NativePath.back()))
504 NativePath += sys::path::get_separator();
505 return NativePath.c_str();
506 };
507
508 for (std::pair<std::string, std::string> &PathRemapping : *PathRemappings) {
509 std::string RemapFrom = nativeWithTrailing(PathRemapping.first);
510 std::string RemapTo = nativeWithTrailing(PathRemapping.second);
511
512 // Create a mapping from coverage data file paths to local paths.
513 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
514 if (RemappedFilenames.count(Key: Filename) == 1)
515 continue;
516
517 SmallString<128> NativeFilename;
518 sys::path::native(path: Filename, result&: NativeFilename);
519 sys::path::remove_dots(path&: NativeFilename, remove_dot_dot: true);
520 if (NativeFilename.starts_with(Prefix: RemapFrom)) {
521 RemappedFilenames[Filename] =
522 RemapTo + NativeFilename.substr(Start: RemapFrom.size()).str();
523 }
524 }
525 }
526
527 // Convert input files from local paths to coverage data file paths.
528 StringMap<std::string> InvRemappedFilenames;
529 for (const auto &RemappedFilename : RemappedFilenames)
530 InvRemappedFilenames[RemappedFilename.getValue()] =
531 std::string(RemappedFilename.getKey());
532
533 for (std::string &Filename : SourceFiles) {
534 SmallString<128> NativeFilename;
535 sys::path::native(path: Filename, result&: NativeFilename);
536 auto CovFileName = InvRemappedFilenames.find(Key: NativeFilename);
537 if (CovFileName != InvRemappedFilenames.end())
538 Filename = CovFileName->second;
539 }
540}
541
542void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
543 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
544
545 // The user may have specified source files which aren't in the coverage
546 // mapping. Filter these files away.
547 llvm::erase_if(C&: SourceFiles, P: [&](const std::string &SF) {
548 return !llvm::binary_search(Range&: CoveredFiles, Value: SF);
549 });
550}
551
552void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
553 if (!ViewOpts.hasDemangler())
554 return;
555
556 // Pass function names to the demangler in a temporary file.
557 int InputFD;
558 SmallString<256> InputPath;
559 std::error_code EC =
560 sys::fs::createTemporaryFile(Prefix: "demangle-in", Suffix: "list", ResultFD&: InputFD, ResultPath&: InputPath);
561 if (EC) {
562 error(Message: InputPath, Whence: EC.message());
563 return;
564 }
565 ToolOutputFile InputTOF{InputPath, InputFD};
566
567 unsigned NumSymbols = 0;
568 for (const auto &Function : Coverage.getCoveredFunctions()) {
569 InputTOF.os() << Function.Name << '\n';
570 ++NumSymbols;
571 }
572 InputTOF.os().close();
573
574 // Use another temporary file to store the demangler's output.
575 int OutputFD;
576 SmallString<256> OutputPath;
577 EC = sys::fs::createTemporaryFile(Prefix: "demangle-out", Suffix: "list", ResultFD&: OutputFD,
578 ResultPath&: OutputPath);
579 if (EC) {
580 error(Message: OutputPath, Whence: EC.message());
581 return;
582 }
583 ToolOutputFile OutputTOF{OutputPath, OutputFD};
584 OutputTOF.os().close();
585
586 // Invoke the demangler.
587 std::vector<StringRef> ArgsV;
588 ArgsV.reserve(n: ViewOpts.DemanglerOpts.size());
589 llvm::append_range(C&: ArgsV, R&: ViewOpts.DemanglerOpts);
590 std::optional<StringRef> Redirects[] = {
591 InputPath.str(), OutputPath.str(), {""}};
592 std::string ErrMsg;
593 int RC =
594 sys::ExecuteAndWait(Program: ViewOpts.DemanglerOpts[0], Args: ArgsV,
595 /*env=*/Env: std::nullopt, Redirects, /*secondsToWait=*/SecondsToWait: 0,
596 /*memoryLimit=*/MemoryLimit: 0, ErrMsg: &ErrMsg);
597 if (RC) {
598 error(Message: ErrMsg, Whence: ViewOpts.DemanglerOpts[0]);
599 return;
600 }
601
602 // Parse the demangler's output.
603 auto BufOrError = MemoryBuffer::getFile(Filename: OutputPath);
604 if (!BufOrError) {
605 error(Message: OutputPath, Whence: BufOrError.getError().message());
606 return;
607 }
608
609 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
610
611 SmallVector<StringRef, 8> Symbols;
612 StringRef DemanglerData = DemanglerBuf->getBuffer();
613 DemanglerData.split(A&: Symbols, Separator: '\n', /*MaxSplit=*/NumSymbols,
614 /*KeepEmpty=*/false);
615 if (Symbols.size() != NumSymbols) {
616 error(Message: "demangler did not provide expected number of symbols");
617 return;
618 }
619
620 // Cache the demangled names.
621 unsigned I = 0;
622 for (const auto &Function : Coverage.getCoveredFunctions())
623 // On Windows, lines in the demangler's output file end with "\r\n".
624 // Splitting by '\n' keeps '\r's, so cut them now.
625 DC.DemangledNames[Function.Name] = std::string(Symbols[I++].rtrim());
626}
627
628void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
629 CoverageMapping *Coverage,
630 CoveragePrinter *Printer,
631 bool ShowFilenames) {
632 auto View = createSourceFileView(SourceFile, Coverage: *Coverage);
633 if (!View) {
634 warning(Message: "The file '" + SourceFile + "' isn't covered.");
635 return;
636 }
637
638 auto OSOrErr = Printer->createViewFile(Path: SourceFile, /*InToplevel=*/false);
639 if (Error E = OSOrErr.takeError()) {
640 error(Message: "could not create view file!", Whence: toString(E: std::move(E)));
641 return;
642 }
643 auto OS = std::move(OSOrErr.get());
644
645 View->print(OS&: *OS.get(), /*Wholefile=*/WholeFile: true,
646 /*ShowSourceName=*/ShowFilenames,
647 /*ShowTitle=*/ViewOpts.hasOutputDirectory());
648 Printer->closeViewFile(OS: std::move(OS));
649}
650
651int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
652 cl::opt<std::string> CovFilename(
653 cl::Positional, cl::desc("Covered executable or object file."));
654
655 cl::list<std::string> CovFilenames(
656 "object", cl::desc("Coverage executable or object file"));
657
658 cl::opt<bool> DebugDumpCollectedObjects(
659 "dump-collected-objects", cl::Hidden,
660 cl::desc("Show the collected coverage object files"));
661
662 cl::list<std::string> InputSourceFiles("sources", cl::Positional,
663 cl::desc("<Source files>"));
664
665 cl::opt<bool> DebugDumpCollectedPaths(
666 "dump-collected-paths", cl::Hidden,
667 cl::desc("Show the collected paths to source files"));
668
669 cl::opt<std::string> PGOFilename(
670 "instr-profile",
671 cl::desc(
672 "File with the profile data obtained after an instrumented run"));
673
674 cl::opt<bool> EmptyProfile(
675 "empty-profile",
676 cl::desc("Use a synthetic profile with no data to generate "
677 "baseline coverage"));
678
679 cl::list<std::string> Arches(
680 "arch", cl::desc("architectures of the coverage mapping binaries"));
681
682 cl::opt<bool> DebugDump("dump", cl::desc("Show internal debug dump"));
683
684 cl::list<std::string> DebugFileDirectory(
685 "debug-file-directory",
686 cl::desc("Directories to search for object files by build ID"));
687 cl::opt<bool> Debuginfod(
688 "debuginfod",
689 cl::desc("Use debuginfod to look up object files from profile"),
690 cl::init(Val: canUseDebuginfod()));
691
692 cl::opt<CoverageViewOptions::OutputFormat> Format(
693 "format", cl::desc("Output format for line-based coverage reports"),
694 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
695 "Text output"),
696 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
697 "HTML output"),
698 clEnumValN(CoverageViewOptions::OutputFormat::Lcov, "lcov",
699 "lcov tracefile output")),
700 cl::init(Val: CoverageViewOptions::OutputFormat::Text));
701
702 cl::list<std::string> PathRemaps(
703 "path-equivalence",
704 cl::desc("<from>,<to> Map coverage data paths to local source file "
705 "paths"));
706
707 cl::OptionCategory FilteringCategory("Function filtering options");
708
709 cl::list<std::string> NameFilters(
710 "name",
711 cl::desc("Show code coverage only for functions with the given name"),
712 cl::cat(FilteringCategory));
713
714 cl::list<std::string> NameFilterFiles(
715 "name-allowlist",
716 cl::desc("Show code coverage only for functions listed in the given "
717 "file"),
718 cl::cat(FilteringCategory));
719
720 cl::list<std::string> NameRegexFilters(
721 "name-regex",
722 cl::desc("Show code coverage only for functions that match the given "
723 "regular expression"),
724 cl::cat(FilteringCategory));
725
726 cl::list<std::string> IgnoreFilenameRegexFilters(
727 "ignore-filename-regex",
728 cl::desc("Skip source code files with file paths that match the given "
729 "regular expression"),
730 cl::cat(FilteringCategory));
731
732 cl::list<std::string> IncludeFilenameRegexFilters(
733 "include-filename-regex",
734 cl::desc("Only include source code files with file paths that match the "
735 "given regular expression"),
736 cl::cat(FilteringCategory));
737
738 cl::opt<double> RegionCoverageLtFilter(
739 "region-coverage-lt",
740 cl::desc("Show code coverage only for functions with region coverage "
741 "less than the given threshold"),
742 cl::cat(FilteringCategory));
743
744 cl::opt<double> RegionCoverageGtFilter(
745 "region-coverage-gt",
746 cl::desc("Show code coverage only for functions with region coverage "
747 "greater than the given threshold"),
748 cl::cat(FilteringCategory));
749
750 cl::opt<double> LineCoverageLtFilter(
751 "line-coverage-lt",
752 cl::desc("Show code coverage only for functions with line coverage less "
753 "than the given threshold"),
754 cl::cat(FilteringCategory));
755
756 cl::opt<double> LineCoverageGtFilter(
757 "line-coverage-gt",
758 cl::desc("Show code coverage only for functions with line coverage "
759 "greater than the given threshold"),
760 cl::cat(FilteringCategory));
761
762 cl::opt<cl::boolOrDefault> UseColor(
763 "use-color", cl::desc("Emit colored output (default=autodetect)"),
764 cl::init(Val: cl::boolOrDefault::BOU_UNSET));
765
766 cl::list<std::string> DemanglerOpts(
767 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
768
769 cl::opt<bool> RegionSummary(
770 "show-region-summary",
771 cl::desc("Show region statistics in summary table"), cl::init(Val: true));
772
773 cl::opt<bool> FunctionSummary(
774 "show-function-summary",
775 cl::desc("Show function statistics in summary table"), cl::init(Val: true));
776
777 cl::opt<bool> BranchSummary(
778 "show-branch-summary",
779 cl::desc("Show branch condition statistics in summary table"),
780 cl::init(Val: true));
781
782 cl::opt<bool> MCDCSummary("show-mcdc-summary",
783 cl::desc("Show MCDC statistics in summary table"),
784 cl::init(Val: false));
785
786 cl::opt<bool> InstantiationSummary(
787 "show-instantiation-summary",
788 cl::desc("Show instantiation statistics in summary table"));
789
790 cl::opt<bool> SummaryOnly(
791 "summary-only",
792 cl::desc("Export only summary information for each source file"));
793
794 cl::opt<unsigned> NumThreads(
795 "num-threads", cl::init(Val: 0),
796 cl::desc("Number of merge threads to use (default: autodetect)"));
797 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
798 cl::aliasopt(NumThreads));
799
800 cl::opt<std::string> CompilationDirectory(
801 "compilation-dir", cl::init(Val: ""),
802 cl::desc("Directory used as a base for relative coverage mapping paths"));
803
804 cl::opt<bool> CheckBinaryIDs(
805 "check-binary-ids", cl::desc("Fail if an object couldn't be found for a "
806 "binary ID in the profile"));
807
808 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
809 cl::ParseCommandLineOptions(argc, argv, Overview: "LLVM code coverage tool\n");
810 ViewOpts.Debug = DebugDump;
811
812 // Initialize `Format` and `Colors` before any call to `error()` or
813 // `warning()`, which use `ViewOpts.colored_ostream()` and would read
814 // uninitialized `Colors`.
815 ViewOpts.Format = Format;
816 switch (ViewOpts.Format) {
817 case CoverageViewOptions::OutputFormat::Text:
818 ViewOpts.Colors = UseColor == cl::boolOrDefault::BOU_UNSET
819 ? sys::Process::StandardOutHasColors()
820 : UseColor == cl::boolOrDefault::BOU_TRUE;
821 break;
822 case CoverageViewOptions::OutputFormat::HTML:
823 if (UseColor == cl::boolOrDefault::BOU_FALSE)
824 errs() << "Color output cannot be disabled when generating html.\n";
825 ViewOpts.Colors = true;
826 break;
827 case CoverageViewOptions::OutputFormat::Lcov:
828 if (UseColor == cl::boolOrDefault::BOU_TRUE)
829 errs() << "Color output cannot be enabled when generating lcov.\n";
830 ViewOpts.Colors = false;
831 break;
832 }
833
834 if (Debuginfod) {
835 HTTPClient::initialize();
836 BIDFetcher = std::make_unique<DebuginfodFetcher>(args&: DebugFileDirectory);
837 } else {
838 BIDFetcher = std::make_unique<object::BuildIDFetcher>(args&: DebugFileDirectory);
839 }
840 this->CheckBinaryIDs = CheckBinaryIDs;
841
842 if (!PGOFilename.empty() == EmptyProfile) {
843 error(
844 Message: "exactly one of -instr-profile and -empty-profile must be specified");
845 return 1;
846 }
847 if (!PGOFilename.empty()) {
848 this->PGOFilename = std::make_optional(t&: PGOFilename.getValue());
849 }
850
851 if (!CovFilename.empty())
852 ObjectFilenames.emplace_back(args&: CovFilename);
853 for (const std::string &Filename : CovFilenames)
854 ObjectFilenames.emplace_back(args: Filename);
855 if (ObjectFilenames.empty() && !Debuginfod && DebugFileDirectory.empty()) {
856 errs() << "No filenames specified!\n";
857 ::exit(status: 1);
858 }
859
860 if (DebugDumpCollectedObjects) {
861 for (StringRef OF : ObjectFilenames)
862 outs() << OF << '\n';
863 ::exit(status: 0);
864 }
865
866 if (!PathRemaps.empty()) {
867 std::vector<std::pair<std::string, std::string>> Remappings;
868
869 for (const std::string &PathRemap : PathRemaps) {
870 auto EquivPair = StringRef(PathRemap).split(Separator: ',');
871 if (EquivPair.first.empty() || EquivPair.second.empty()) {
872 error(Message: "invalid argument '" + PathRemap +
873 "', must be in format 'from,to'",
874 Whence: "-path-equivalence");
875 return 1;
876 }
877
878 Remappings.push_back(
879 x: {std::string(EquivPair.first), std::string(EquivPair.second)});
880 }
881
882 PathRemappings = Remappings;
883 }
884
885 // If a demangler is supplied, check if it exists and register it.
886 if (!DemanglerOpts.empty()) {
887 auto DemanglerPathOrErr = sys::findProgramByName(Name: DemanglerOpts[0]);
888 if (!DemanglerPathOrErr) {
889 error(Message: "could not find the demangler!",
890 Whence: DemanglerPathOrErr.getError().message());
891 return 1;
892 }
893 DemanglerOpts[0] = *DemanglerPathOrErr;
894 ViewOpts.DemanglerOpts.swap(x&: DemanglerOpts);
895 }
896
897 // Read in -name-allowlist files.
898 if (!NameFilterFiles.empty()) {
899 std::string SpecialCaseListErr;
900 NameAllowlist = SpecialCaseList::create(
901 Paths: NameFilterFiles, FS&: *vfs::getRealFileSystem(), Error&: SpecialCaseListErr);
902 if (!NameAllowlist)
903 error(Message: SpecialCaseListErr);
904 }
905
906 // Create the function filters
907 if (!NameFilters.empty() || NameAllowlist || !NameRegexFilters.empty()) {
908 auto NameFilterer = std::make_unique<CoverageFilters>();
909 for (const auto &Name : NameFilters)
910 NameFilterer->push_back(Filter: std::make_unique<NameCoverageFilter>(args: Name));
911 if (NameAllowlist && !NameFilterFiles.empty())
912 NameFilterer->push_back(
913 Filter: std::make_unique<NameAllowlistCoverageFilter>(args&: *NameAllowlist));
914 for (const auto &Regex : NameRegexFilters)
915 NameFilterer->push_back(
916 Filter: std::make_unique<NameRegexCoverageFilter>(args: Regex));
917 Filters.push_back(Filter: std::move(NameFilterer));
918 }
919
920 if (RegionCoverageLtFilter.getNumOccurrences() ||
921 RegionCoverageGtFilter.getNumOccurrences() ||
922 LineCoverageLtFilter.getNumOccurrences() ||
923 LineCoverageGtFilter.getNumOccurrences()) {
924 auto StatFilterer = std::make_unique<CoverageFilters>();
925 if (RegionCoverageLtFilter.getNumOccurrences())
926 StatFilterer->push_back(Filter: std::make_unique<RegionCoverageFilter>(
927 args: RegionCoverageFilter::LessThan, args&: RegionCoverageLtFilter));
928 if (RegionCoverageGtFilter.getNumOccurrences())
929 StatFilterer->push_back(Filter: std::make_unique<RegionCoverageFilter>(
930 args: RegionCoverageFilter::GreaterThan, args&: RegionCoverageGtFilter));
931 if (LineCoverageLtFilter.getNumOccurrences())
932 StatFilterer->push_back(Filter: std::make_unique<LineCoverageFilter>(
933 args: LineCoverageFilter::LessThan, args&: LineCoverageLtFilter));
934 if (LineCoverageGtFilter.getNumOccurrences())
935 StatFilterer->push_back(Filter: std::make_unique<LineCoverageFilter>(
936 args: RegionCoverageFilter::GreaterThan, args&: LineCoverageGtFilter));
937 Filters.push_back(Filter: std::move(StatFilterer));
938 }
939
940 // Create the ignore filename filters.
941 for (const auto &RE : IgnoreFilenameRegexFilters)
942 FilenameFilters.push_back(Filter: std::make_unique<NameRegexCoverageFilter>(args: RE));
943
944 for (const auto &RE : IncludeFilenameRegexFilters)
945 FilenameFilters.push_back(Filter: std::make_unique<NameRegexCoverageFilter>(
946 args: RE, args: NameRegexCoverageFilter::FilterType::Include));
947
948 if (!Arches.empty()) {
949 for (const std::string &Arch : Arches) {
950 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
951 error(Message: "unknown architecture: " + Arch);
952 return 1;
953 }
954 CoverageArches.emplace_back(args: Arch);
955 }
956 if (CoverageArches.size() != 1 &&
957 CoverageArches.size() != ObjectFilenames.size()) {
958 error(Message: "number of architectures doesn't match the number of objects");
959 return 1;
960 }
961 }
962
963 // FilenameFilters are applied even when InputSourceFiles specified.
964 for (const std::string &File : InputSourceFiles)
965 collectPaths(Path: File);
966
967 if (DebugDumpCollectedPaths) {
968 for (const std::string &SF : SourceFiles)
969 outs() << SF << '\n';
970 ::exit(status: 0);
971 }
972
973 ViewOpts.ShowMCDCSummary = MCDCSummary;
974 ViewOpts.ShowBranchSummary = BranchSummary;
975 ViewOpts.ShowRegionSummary = RegionSummary;
976 ViewOpts.ShowFunctionSummary = FunctionSummary;
977 ViewOpts.ShowInstantiationSummary = InstantiationSummary;
978 ViewOpts.ExportSummaryOnly = SummaryOnly;
979 ViewOpts.NumThreads = NumThreads;
980 ViewOpts.CompilationDirectory = CompilationDirectory;
981
982 return 0;
983 };
984
985 switch (Cmd) {
986 case Show:
987 return doShow(argc, argv, commandLineParser);
988 case Report:
989 return doReport(argc, argv, commandLineParser);
990 case Export:
991 return doExport(argc, argv, commandLineParser);
992 }
993 return 0;
994}
995
996int CodeCoverageTool::doShow(int argc, const char **argv,
997 CommandLineParserType commandLineParser) {
998
999 cl::OptionCategory ViewCategory("Viewing options");
1000
1001 cl::opt<bool> ShowLineExecutionCounts(
1002 "show-line-counts", cl::desc("Show the execution counts for each line"),
1003 cl::init(Val: true), cl::cat(ViewCategory));
1004
1005 cl::opt<bool> ShowRegions(
1006 "show-regions", cl::desc("Show the execution counts for each region"),
1007 cl::cat(ViewCategory));
1008
1009 cl::opt<CoverageViewOptions::BranchOutputType> ShowBranches(
1010 "show-branches", cl::desc("Show coverage for branch conditions"),
1011 cl::cat(ViewCategory),
1012 cl::values(clEnumValN(CoverageViewOptions::BranchOutputType::Count,
1013 "count", "Show True/False counts"),
1014 clEnumValN(CoverageViewOptions::BranchOutputType::Percent,
1015 "percent", "Show True/False percent")),
1016 cl::init(Val: CoverageViewOptions::BranchOutputType::Off));
1017
1018 cl::opt<bool> ShowMCDC(
1019 "show-mcdc",
1020 cl::desc("Show the MCDC Coverage for each applicable boolean expression"),
1021 cl::cat(ViewCategory));
1022
1023 cl::opt<bool> ShowMCDCNonExecutedVectors(
1024 "show-mcdc-non-executed-vectors",
1025 cl::desc("Show MC/DC test vectors that were not executed"),
1026 cl::cat(ViewCategory));
1027
1028 cl::opt<bool> ShowBestLineRegionsCounts(
1029 "show-line-counts-or-regions",
1030 cl::desc("Show the execution counts for each line, or the execution "
1031 "counts for each region on lines that have multiple regions"),
1032 cl::cat(ViewCategory));
1033
1034 cl::opt<bool> ShowExpansions("show-expansions",
1035 cl::desc("Show expanded source regions"),
1036 cl::cat(ViewCategory));
1037
1038 cl::opt<bool> ShowInstantiations("show-instantiations",
1039 cl::desc("Show function instantiations"),
1040 cl::init(Val: true), cl::cat(ViewCategory));
1041
1042 cl::opt<bool> ShowDirectoryCoverage("show-directory-coverage",
1043 cl::desc("Show directory coverage"),
1044 cl::cat(ViewCategory));
1045
1046 cl::opt<bool> ShowCreatedTime("show-created-time",
1047 cl::desc("Show created time for each page."),
1048 cl::init(Val: true), cl::cat(ViewCategory));
1049
1050 cl::opt<std::string> ShowOutputDirectory(
1051 "output-dir", cl::init(Val: ""),
1052 cl::desc("Directory in which coverage information is written out"));
1053 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
1054 cl::aliasopt(ShowOutputDirectory));
1055
1056 cl::opt<bool> BinaryCounters(
1057 "binary-counters",
1058 cl::desc("Show binary counters (1/0) in lines and branches instead of "
1059 "integer execution counts"),
1060 cl::cat(ViewCategory));
1061
1062 cl::opt<uint32_t> TabSize(
1063 "tab-size", cl::init(Val: 2),
1064 cl::desc(
1065 "Set tab expansion size for html coverage reports (default = 2)"));
1066
1067 cl::opt<std::string> ProjectTitle(
1068 "project-title", cl::desc("Set project title for the coverage report"));
1069
1070 cl::opt<std::string> CovWatermark(
1071 "coverage-watermark",
1072 cl::desc("<high>,<low> value indicate thresholds for high and low"
1073 "coverage watermark"));
1074
1075 auto Err = commandLineParser(argc, argv);
1076 if (Err)
1077 return Err;
1078
1079 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
1080 error(Message: "lcov format should be used with 'llvm-cov export'.");
1081 return 1;
1082 }
1083
1084 ViewOpts.HighCovWatermark = 100.0;
1085 ViewOpts.LowCovWatermark = 80.0;
1086 if (!CovWatermark.empty()) {
1087 auto WaterMarkPair = StringRef(CovWatermark).split(Separator: ',');
1088 if (WaterMarkPair.first.empty() || WaterMarkPair.second.empty()) {
1089 error(Message: "invalid argument '" + CovWatermark +
1090 "', must be in format 'high,low'",
1091 Whence: "-coverage-watermark");
1092 return 1;
1093 }
1094
1095 char *EndPointer = nullptr;
1096 ViewOpts.HighCovWatermark =
1097 strtod(nptr: WaterMarkPair.first.begin(), endptr: &EndPointer);
1098 if (EndPointer != WaterMarkPair.first.end()) {
1099 error(Message: "invalid number '" + WaterMarkPair.first +
1100 "', invalid value for 'high'",
1101 Whence: "-coverage-watermark");
1102 return 1;
1103 }
1104
1105 ViewOpts.LowCovWatermark =
1106 strtod(nptr: WaterMarkPair.second.begin(), endptr: &EndPointer);
1107 if (EndPointer != WaterMarkPair.second.end()) {
1108 error(Message: "invalid number '" + WaterMarkPair.second +
1109 "', invalid value for 'low'",
1110 Whence: "-coverage-watermark");
1111 return 1;
1112 }
1113
1114 if (ViewOpts.HighCovWatermark > 100 || ViewOpts.LowCovWatermark < 0 ||
1115 ViewOpts.HighCovWatermark <= ViewOpts.LowCovWatermark) {
1116 error(
1117 Message: "invalid number range '" + CovWatermark +
1118 "', must be both high and low should be between 0-100, and high "
1119 "> low",
1120 Whence: "-coverage-watermark");
1121 return 1;
1122 }
1123 }
1124
1125 ViewOpts.ShowLineNumbers = true;
1126 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
1127 !ShowRegions || ShowBestLineRegionsCounts;
1128 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
1129 ViewOpts.ShowExpandedRegions = ShowExpansions;
1130 ViewOpts.ShowBranchCounts =
1131 ShowBranches == CoverageViewOptions::BranchOutputType::Count;
1132 ViewOpts.ShowMCDC = ShowMCDC;
1133 ViewOpts.ShowMCDCNonExecutedVectors = ShowMCDCNonExecutedVectors;
1134 ViewOpts.ShowBranchPercents =
1135 ShowBranches == CoverageViewOptions::BranchOutputType::Percent;
1136 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
1137 ViewOpts.ShowDirectoryCoverage = ShowDirectoryCoverage;
1138 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
1139 ViewOpts.BinaryCounters = BinaryCounters;
1140 ViewOpts.TabSize = TabSize;
1141 ViewOpts.ProjectTitle = ProjectTitle;
1142
1143 if (ViewOpts.hasOutputDirectory()) {
1144 if (auto E = sys::fs::create_directories(path: ViewOpts.ShowOutputDirectory)) {
1145 error(Message: "could not create output directory!", Whence: E.message());
1146 return 1;
1147 }
1148 }
1149
1150 if (PGOFilename) {
1151 sys::fs::file_status Status;
1152 if (std::error_code EC = sys::fs::status(path: PGOFilename.value(), result&: Status)) {
1153 error(Message: "could not read profile data!" + EC.message(), Whence: PGOFilename.value());
1154 return 1;
1155 }
1156
1157 if (ShowCreatedTime) {
1158 auto ModifiedTime = Status.getLastModificationTime();
1159 std::string ModifiedTimeStr = to_string(Value: ModifiedTime);
1160 size_t found = ModifiedTimeStr.rfind(c: ':');
1161 ViewOpts.CreatedTimeStr =
1162 (found != std::string::npos)
1163 ? "Created: " + ModifiedTimeStr.substr(pos: 0, n: found)
1164 : "Created: " + ModifiedTimeStr;
1165 }
1166 }
1167
1168 auto Coverage = load();
1169 if (!Coverage)
1170 return 1;
1171
1172 auto Printer = CoveragePrinter::create(Opts: ViewOpts);
1173
1174 if (SourceFiles.empty() && !HadSourceFiles)
1175 // Get the source files from the function coverage mapping.
1176 for (StringRef Filename : Coverage->getUniqueSourceFiles()) {
1177 if (!FilenameFilters.matchesFilename(Filename))
1178 SourceFiles.push_back(x: std::string(Filename));
1179 }
1180
1181 // Create an index out of the source files.
1182 if (ViewOpts.hasOutputDirectory()) {
1183 if (Error E = Printer->createIndexFile(SourceFiles, Coverage: *Coverage, Filters)) {
1184 error(Message: "could not create index file!", Whence: toString(E: std::move(E)));
1185 return 1;
1186 }
1187 }
1188
1189 if (!Filters.empty()) {
1190 // Build the map of filenames to functions.
1191 std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
1192 FilenameFunctionMap;
1193 for (const auto &SourceFile : SourceFiles)
1194 for (const auto &Function : Coverage->getCoveredFunctions(Filename: SourceFile))
1195 if (Filters.matches(CM: *Coverage, Function))
1196 FilenameFunctionMap[SourceFile].push_back(x: &Function);
1197
1198 // Only print filter matching functions for each file.
1199 for (const auto &FileFunc : FilenameFunctionMap) {
1200 StringRef File = FileFunc.first;
1201 const auto &Functions = FileFunc.second;
1202
1203 auto OSOrErr = Printer->createViewFile(Path: File, /*InToplevel=*/false);
1204 if (Error E = OSOrErr.takeError()) {
1205 error(Message: "could not create view file!", Whence: toString(E: std::move(E)));
1206 return 1;
1207 }
1208 auto OS = std::move(OSOrErr.get());
1209
1210 bool ShowTitle = ViewOpts.hasOutputDirectory();
1211 for (const auto *Function : Functions) {
1212 auto FunctionView = createFunctionView(Function: *Function, Coverage: *Coverage);
1213 if (!FunctionView) {
1214 warning(Message: "Could not read coverage for '" + Function->Name + "'.");
1215 continue;
1216 }
1217 FunctionView->print(OS&: *OS.get(), /*WholeFile=*/false,
1218 /*ShowSourceName=*/true, ShowTitle);
1219 ShowTitle = false;
1220 }
1221
1222 Printer->closeViewFile(OS: std::move(OS));
1223 }
1224 return 0;
1225 }
1226
1227 // Show files
1228 bool ShowFilenames =
1229 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
1230 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
1231
1232 ThreadPoolStrategy S = hardware_concurrency(ThreadCount: ViewOpts.NumThreads);
1233 if (ViewOpts.NumThreads == 0) {
1234 // If NumThreads is not specified, create one thread for each input, up to
1235 // the number of hardware cores.
1236 S = heavyweight_hardware_concurrency(ThreadCount: SourceFiles.size());
1237 S.Limit = true;
1238 }
1239
1240 if (!ViewOpts.hasOutputDirectory() || S.ThreadsRequested == 1) {
1241 for (const std::string &SourceFile : SourceFiles)
1242 writeSourceFileView(SourceFile, Coverage: Coverage.get(), Printer: Printer.get(),
1243 ShowFilenames);
1244 } else {
1245 // In -output-dir mode, it's safe to use multiple threads to print files.
1246 DefaultThreadPool Pool(S);
1247 for (const std::string &SourceFile : SourceFiles)
1248 Pool.async(F: &CodeCoverageTool::writeSourceFileView, ArgList: this, ArgList: SourceFile,
1249 ArgList: Coverage.get(), ArgList: Printer.get(), ArgList&: ShowFilenames);
1250 Pool.wait();
1251 }
1252
1253 return 0;
1254}
1255
1256int CodeCoverageTool::doReport(int argc, const char **argv,
1257 CommandLineParserType commandLineParser) {
1258 cl::opt<bool> ShowFunctionSummaries(
1259 "show-functions", cl::init(Val: false),
1260 cl::desc("Show coverage summaries for each function"));
1261
1262 auto Err = commandLineParser(argc, argv);
1263 if (Err)
1264 return Err;
1265
1266 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
1267 error(Message: "HTML output for summary reports is not yet supported.");
1268 return 1;
1269 } else if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) {
1270 error(Message: "lcov format should be used with 'llvm-cov export'.");
1271 return 1;
1272 }
1273
1274 if (PGOFilename) {
1275 sys::fs::file_status Status;
1276 if (std::error_code EC = sys::fs::status(path: PGOFilename.value(), result&: Status)) {
1277 error(Message: "could not read profile data!" + EC.message(), Whence: PGOFilename.value());
1278 return 1;
1279 }
1280 }
1281
1282 auto Coverage = load();
1283 if (!Coverage)
1284 return 1;
1285
1286 CoverageReport Report(ViewOpts, *Coverage);
1287 if (!ShowFunctionSummaries) {
1288 if (SourceFiles.empty())
1289 Report.renderFileReports(OS&: llvm::outs(), IgnoreFilenameFilters: FilenameFilters);
1290 else
1291 Report.renderFileReports(OS&: llvm::outs(), Files: SourceFiles);
1292 } else {
1293 if (SourceFiles.empty()) {
1294 error(Message: "source files must be specified when -show-functions=true is "
1295 "specified");
1296 return 1;
1297 }
1298
1299 Report.renderFunctionReports(Files: SourceFiles, DC, OS&: llvm::outs());
1300 }
1301 return 0;
1302}
1303
1304int CodeCoverageTool::doExport(int argc, const char **argv,
1305 CommandLineParserType commandLineParser) {
1306
1307 cl::OptionCategory ExportCategory("Exporting options");
1308
1309 cl::opt<bool> SkipExpansions("skip-expansions",
1310 cl::desc("Don't export expanded source regions"),
1311 cl::cat(ExportCategory));
1312
1313 cl::opt<bool> SkipFunctions("skip-functions",
1314 cl::desc("Don't export per-function data"),
1315 cl::cat(ExportCategory));
1316
1317 cl::opt<bool> SkipBranches("skip-branches",
1318 cl::desc("Don't export branch data (LCOV)"),
1319 cl::cat(ExportCategory));
1320
1321 cl::opt<bool> UnifyInstantiations("unify-instantiations",
1322 cl::desc("Unify function instantiations"),
1323 cl::init(Val: true), cl::cat(ExportCategory));
1324
1325 cl::opt<bool> ShowMCDCNonExecutedVectors(
1326 "show-mcdc-non-executed-vectors",
1327 cl::desc("Include MC/DC test vectors that were not executed in the "
1328 "export"),
1329 cl::cat(ExportCategory));
1330
1331 auto Err = commandLineParser(argc, argv);
1332 if (Err)
1333 return Err;
1334
1335 ViewOpts.SkipExpansions = SkipExpansions;
1336 ViewOpts.SkipFunctions = SkipFunctions;
1337 ViewOpts.SkipBranches = SkipBranches;
1338 ViewOpts.UnifyFunctionInstantiations = UnifyInstantiations;
1339 ViewOpts.ShowMCDCNonExecutedVectors = ShowMCDCNonExecutedVectors;
1340
1341 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text &&
1342 ViewOpts.Format != CoverageViewOptions::OutputFormat::Lcov) {
1343 error(Message: "coverage data can only be exported as textual JSON or an "
1344 "lcov tracefile.");
1345 return 1;
1346 }
1347
1348 if (PGOFilename) {
1349 sys::fs::file_status Status;
1350 if (std::error_code EC = sys::fs::status(path: PGOFilename.value(), result&: Status)) {
1351 error(Message: "could not read profile data!" + EC.message(), Whence: PGOFilename.value());
1352 return 1;
1353 }
1354 }
1355
1356 auto Coverage = load();
1357 if (!Coverage) {
1358 error(Message: "could not load coverage information");
1359 return 1;
1360 }
1361
1362 std::unique_ptr<CoverageExporter> Exporter;
1363
1364 switch (ViewOpts.Format) {
1365 case CoverageViewOptions::OutputFormat::Text:
1366 Exporter =
1367 std::make_unique<CoverageExporterJson>(args&: *Coverage, args&: ViewOpts, args&: outs());
1368 break;
1369 case CoverageViewOptions::OutputFormat::HTML:
1370 // Unreachable because we should have gracefully terminated with an error
1371 // above.
1372 llvm_unreachable("Export in HTML is not supported!");
1373 case CoverageViewOptions::OutputFormat::Lcov:
1374 Exporter =
1375 std::make_unique<CoverageExporterLcov>(args&: *Coverage, args&: ViewOpts, args&: outs());
1376 break;
1377 }
1378
1379 if (SourceFiles.empty())
1380 Exporter->renderRoot(IgnoreFilters: FilenameFilters);
1381 else
1382 Exporter->renderRoot(SourceFiles);
1383
1384 return 0;
1385}
1386
1387int showMain(int argc, const char *argv[]) {
1388 CodeCoverageTool Tool;
1389 return Tool.run(Cmd: CodeCoverageTool::Show, argc, argv);
1390}
1391
1392int reportMain(int argc, const char *argv[]) {
1393 CodeCoverageTool Tool;
1394 return Tool.run(Cmd: CodeCoverageTool::Report, argc, argv);
1395}
1396
1397int exportMain(int argc, const char *argv[]) {
1398 CodeCoverageTool Tool;
1399 return Tool.run(Cmd: CodeCoverageTool::Export, argc, argv);
1400}
1401