1 //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The 'CodeCoverageTool' class implements a command line tool to analyze and
11 // report coverage information using the profiling instrumentation and code
14 //===----------------------------------------------------------------------===//
16 #include "CoverageFilters.h"
17 #include "CoverageReport.h"
18 #include "CoverageSummaryInfo.h"
19 #include "CoverageViewOptions.h"
20 #include "RenderingSupport.h"
21 #include "SourceCoverageView.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
26 #include "llvm/ProfileData/InstrProfReader.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/ScopedPrinter.h"
35 #include "llvm/Support/Threading.h"
36 #include "llvm/Support/ThreadPool.h"
37 #include "llvm/Support/ToolOutputFile.h"
41 #include <system_error>
44 using namespace coverage;
46 void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
47 const CoverageViewOptions &Options,
51 /// \brief The implementation of the coverage tool.
52 class CodeCoverageTool {
55 /// \brief The show command.
57 /// \brief The report command.
59 /// \brief The export command.
63 int run(Command Cmd, int argc, const char **argv);
66 /// \brief Print the error message to the error output stream.
67 void error(const Twine &Message, StringRef Whence = "");
69 /// \brief Print the warning message to the error output stream.
70 void warning(const Twine &Message, StringRef Whence = "");
72 /// \brief Convert \p Path into an absolute path and append it to the list
73 /// of collected paths.
74 void addCollectedPath(const std::string &Path);
76 /// \brief If \p Path is a regular file, collect the path. If it's a
77 /// directory, recursively collect all of the paths within the directory.
78 void collectPaths(const std::string &Path);
80 /// \brief Return a memory buffer for the given source file.
81 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
83 /// \brief Create source views for the expansions of the view.
84 void attachExpansionSubViews(SourceCoverageView &View,
85 ArrayRef<ExpansionRecord> Expansions,
86 const CoverageMapping &Coverage);
88 /// \brief Create the source view of a particular function.
89 std::unique_ptr<SourceCoverageView>
90 createFunctionView(const FunctionRecord &Function,
91 const CoverageMapping &Coverage);
93 /// \brief Create the main source view of a particular source file.
94 std::unique_ptr<SourceCoverageView>
95 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
97 /// \brief Load the coverage mapping data. Return nullptr if an error occurred.
98 std::unique_ptr<CoverageMapping> load();
100 /// \brief Create a mapping from files in the Coverage data to local copies
101 /// (path-equivalence).
102 void remapPathNames(const CoverageMapping &Coverage);
104 /// \brief Remove input source files which aren't mapped by \p Coverage.
105 void removeUnmappedInputs(const CoverageMapping &Coverage);
107 /// \brief If a demangler is available, demangle all symbol names.
108 void demangleSymbols(const CoverageMapping &Coverage);
110 /// \brief Write out a source file view to the filesystem.
111 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
112 CoveragePrinter *Printer, bool ShowFilenames);
114 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
116 int show(int argc, const char **argv,
117 CommandLineParserType commandLineParser);
119 int report(int argc, const char **argv,
120 CommandLineParserType commandLineParser);
122 int export_(int argc, const char **argv,
123 CommandLineParserType commandLineParser);
125 std::vector<StringRef> ObjectFilenames;
126 CoverageViewOptions ViewOpts;
127 CoverageFiltersMatchAll Filters;
129 /// The path to the indexed profile.
130 std::string PGOFilename;
132 /// A list of input source files.
133 std::vector<std::string> SourceFiles;
135 /// In -path-equivalence mode, this maps the absolute paths from the coverage
136 /// mapping data to the input source files.
137 StringMap<std::string> RemappedFilenames;
139 /// The coverage data path to be remapped from, and the source path to be
140 /// remapped to, when using -path-equivalence.
141 Optional<std::pair<std::string, std::string>> PathRemapping;
143 /// The architecture the coverage mapping data targets.
144 std::vector<StringRef> CoverageArches;
146 /// A cache for demangled symbols.
149 /// A lock which guards printing to stderr.
152 /// A container for input source file buffers.
153 std::mutex LoadedSourceFilesLock;
154 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
157 /// Whitelist from -name-whitelist to be used for filtering.
158 std::unique_ptr<SpecialCaseList> NameWhitelist;
162 static std::string getErrorString(const Twine &Message, StringRef Whence,
164 std::string Str = (Warning ? "warning" : "error");
167 Str += Whence.str() + ": ";
168 Str += Message.str() + "\n";
172 void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
173 std::unique_lock<std::mutex> Guard{ErrsLock};
174 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
175 << getErrorString(Message, Whence, false);
178 void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
179 std::unique_lock<std::mutex> Guard{ErrsLock};
180 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
181 << getErrorString(Message, Whence, true);
184 void CodeCoverageTool::addCollectedPath(const std::string &Path) {
185 SmallString<128> EffectivePath(Path);
186 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
187 error(EC.message(), Path);
190 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
191 SourceFiles.emplace_back(EffectivePath.str());
194 void CodeCoverageTool::collectPaths(const std::string &Path) {
195 llvm::sys::fs::file_status Status;
196 llvm::sys::fs::status(Path, Status);
197 if (!llvm::sys::fs::exists(Status)) {
199 addCollectedPath(Path);
201 error("Missing source file", Path);
205 if (llvm::sys::fs::is_regular_file(Status)) {
206 addCollectedPath(Path);
210 if (llvm::sys::fs::is_directory(Status)) {
212 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
213 F != E && !EC; F.increment(EC)) {
214 if (llvm::sys::fs::is_regular_file(F->path()))
215 addCollectedPath(F->path());
218 warning(EC.message(), Path);
222 ErrorOr<const MemoryBuffer &>
223 CodeCoverageTool::getSourceFile(StringRef SourceFile) {
224 // If we've remapped filenames, look up the real location for this file.
225 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
226 if (!RemappedFilenames.empty()) {
227 auto Loc = RemappedFilenames.find(SourceFile);
228 if (Loc != RemappedFilenames.end())
229 SourceFile = Loc->second;
231 for (const auto &Files : LoadedSourceFiles)
232 if (sys::fs::equivalent(SourceFile, Files.first))
233 return *Files.second;
234 auto Buffer = MemoryBuffer::getFile(SourceFile);
235 if (auto EC = Buffer.getError()) {
236 error(EC.message(), SourceFile);
239 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
240 return *LoadedSourceFiles.back().second;
243 void CodeCoverageTool::attachExpansionSubViews(
244 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
245 const CoverageMapping &Coverage) {
246 if (!ViewOpts.ShowExpandedRegions)
248 for (const auto &Expansion : Expansions) {
249 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
250 if (ExpansionCoverage.empty())
252 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
256 auto SubViewExpansions = ExpansionCoverage.getExpansions();
258 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
259 ViewOpts, std::move(ExpansionCoverage));
260 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
261 View.addExpansion(Expansion.Region, std::move(SubView));
265 std::unique_ptr<SourceCoverageView>
266 CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
267 const CoverageMapping &Coverage) {
268 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
269 if (FunctionCoverage.empty())
271 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
275 auto Expansions = FunctionCoverage.getExpansions();
276 auto View = SourceCoverageView::create(DC.demangle(Function.Name),
277 SourceBuffer.get(), ViewOpts,
278 std::move(FunctionCoverage));
279 attachExpansionSubViews(*View, Expansions, Coverage);
284 std::unique_ptr<SourceCoverageView>
285 CodeCoverageTool::createSourceFileView(StringRef SourceFile,
286 const CoverageMapping &Coverage) {
287 auto SourceBuffer = getSourceFile(SourceFile);
290 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
291 if (FileCoverage.empty())
294 auto Expansions = FileCoverage.getExpansions();
295 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
296 ViewOpts, std::move(FileCoverage));
297 attachExpansionSubViews(*View, Expansions, Coverage);
298 if (!ViewOpts.ShowFunctionInstantiations)
301 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
302 // Skip functions which have a single instantiation.
303 if (Group.size() < 2)
306 for (const FunctionRecord *Function : Group.getInstantiations()) {
307 std::unique_ptr<SourceCoverageView> SubView{nullptr};
309 StringRef Funcname = DC.demangle(Function->Name);
311 if (Function->ExecutionCount > 0) {
312 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
313 auto SubViewExpansions = SubViewCoverage.getExpansions();
314 SubView = SourceCoverageView::create(
315 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
316 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
319 unsigned FileID = Function->CountedRegions.front().FileID;
321 for (const auto &CR : Function->CountedRegions)
322 if (CR.FileID == FileID)
323 Line = std::max(CR.LineEnd, Line);
324 View->addInstantiation(Funcname, Line, std::move(SubView));
330 static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
331 sys::fs::file_status Status;
332 if (sys::fs::status(LHS, Status))
334 auto LHSTime = Status.getLastModificationTime();
335 if (sys::fs::status(RHS, Status))
337 auto RHSTime = Status.getLastModificationTime();
338 return LHSTime > RHSTime;
341 std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
342 for (StringRef ObjectFilename : ObjectFilenames)
343 if (modifiedTimeGT(ObjectFilename, PGOFilename))
344 warning("profile data may be out of date - object is newer",
347 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
348 if (Error E = CoverageOrErr.takeError()) {
349 error("Failed to load coverage: " + toString(std::move(E)),
350 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
353 auto Coverage = std::move(CoverageOrErr.get());
354 unsigned Mismatched = Coverage->getMismatchedCount();
356 warning(Twine(Mismatched) + " functions have mismatched data");
358 if (ViewOpts.Debug) {
359 for (const auto &HashMismatch : Coverage->getHashMismatches())
360 errs() << "hash-mismatch: "
361 << "No profile record found for '" << HashMismatch.first << "'"
362 << " with hash = 0x" << Twine::utohexstr(HashMismatch.second)
365 for (const auto &CounterMismatch : Coverage->getCounterMismatches())
366 errs() << "counter-mismatch: "
367 << "Coverage mapping for " << CounterMismatch.first
368 << " only has " << CounterMismatch.second
369 << " valid counter expressions\n";
373 remapPathNames(*Coverage);
375 if (!SourceFiles.empty())
376 removeUnmappedInputs(*Coverage);
378 demangleSymbols(*Coverage);
383 void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
387 // Convert remapping paths to native paths with trailing seperators.
388 auto nativeWithTrailing = [](StringRef Path) -> std::string {
391 SmallString<128> NativePath;
392 sys::path::native(Path, NativePath);
393 if (!sys::path::is_separator(NativePath.back()))
394 NativePath += sys::path::get_separator();
395 return NativePath.c_str();
397 std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
398 std::string RemapTo = nativeWithTrailing(PathRemapping->second);
400 // Create a mapping from coverage data file paths to local paths.
401 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
402 SmallString<128> NativeFilename;
403 sys::path::native(Filename, NativeFilename);
404 if (NativeFilename.startswith(RemapFrom)) {
405 RemappedFilenames[Filename] =
406 RemapTo + NativeFilename.substr(RemapFrom.size()).str();
410 // Convert input files from local paths to coverage data file paths.
411 StringMap<std::string> InvRemappedFilenames;
412 for (const auto &RemappedFilename : RemappedFilenames)
413 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
415 for (std::string &Filename : SourceFiles) {
416 SmallString<128> NativeFilename;
417 sys::path::native(Filename, NativeFilename);
418 auto CovFileName = InvRemappedFilenames.find(NativeFilename);
419 if (CovFileName != InvRemappedFilenames.end())
420 Filename = CovFileName->second;
424 void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
425 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
427 auto UncoveredFilesIt = SourceFiles.end();
428 // The user may have specified source files which aren't in the coverage
429 // mapping. Filter these files away.
430 UncoveredFilesIt = std::remove_if(
431 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
432 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
436 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
439 void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
440 if (!ViewOpts.hasDemangler())
443 // Pass function names to the demangler in a temporary file.
445 SmallString<256> InputPath;
447 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
449 error(InputPath, EC.message());
452 ToolOutputFile InputTOF{InputPath, InputFD};
454 unsigned NumSymbols = 0;
455 for (const auto &Function : Coverage.getCoveredFunctions()) {
456 InputTOF.os() << Function.Name << '\n';
459 InputTOF.os().close();
461 // Use another temporary file to store the demangler's output.
463 SmallString<256> OutputPath;
464 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
467 error(OutputPath, EC.message());
470 ToolOutputFile OutputTOF{OutputPath, OutputFD};
471 OutputTOF.os().close();
473 // Invoke the demangler.
474 std::vector<const char *> ArgsV;
475 for (const std::string &Arg : ViewOpts.DemanglerOpts)
476 ArgsV.push_back(Arg.c_str());
477 ArgsV.push_back(nullptr);
478 Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
480 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
481 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
482 /*memoryLimit=*/0, &ErrMsg);
484 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
488 // Parse the demangler's output.
489 auto BufOrError = MemoryBuffer::getFile(OutputPath);
491 error(OutputPath, BufOrError.getError().message());
495 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
497 SmallVector<StringRef, 8> Symbols;
498 StringRef DemanglerData = DemanglerBuf->getBuffer();
499 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
500 /*KeepEmpty=*/false);
501 if (Symbols.size() != NumSymbols) {
502 error("Demangler did not provide expected number of symbols");
506 // Cache the demangled names.
508 for (const auto &Function : Coverage.getCoveredFunctions())
509 // On Windows, lines in the demangler's output file end with "\r\n".
510 // Splitting by '\n' keeps '\r's, so cut them now.
511 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
514 void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
515 CoverageMapping *Coverage,
516 CoveragePrinter *Printer,
517 bool ShowFilenames) {
518 auto View = createSourceFileView(SourceFile, *Coverage);
520 warning("The file '" + SourceFile + "' isn't covered.");
524 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
525 if (Error E = OSOrErr.takeError()) {
526 error("Could not create view file!", toString(std::move(E)));
529 auto OS = std::move(OSOrErr.get());
531 View->print(*OS.get(), /*Wholefile=*/true,
532 /*ShowSourceName=*/ShowFilenames,
533 /*ShowTitle=*/ViewOpts.hasOutputDirectory());
534 Printer->closeViewFile(std::move(OS));
537 int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
538 cl::opt<std::string> CovFilename(
539 cl::Positional, cl::desc("Covered executable or object file."));
541 cl::list<std::string> CovFilenames(
542 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
545 cl::list<std::string> InputSourceFiles(
546 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
548 cl::opt<bool> DebugDumpCollectedPaths(
549 "dump-collected-paths", cl::Optional, cl::Hidden,
550 cl::desc("Show the collected paths to source files"));
552 cl::opt<std::string, true> PGOFilename(
553 "instr-profile", cl::Required, cl::location(this->PGOFilename),
555 "File with the profile data obtained after an instrumented run"));
557 cl::list<std::string> Arches(
558 "arch", cl::desc("architectures of the coverage mapping binaries"));
560 cl::opt<bool> DebugDump("dump", cl::Optional,
561 cl::desc("Show internal debug dump"));
563 cl::opt<CoverageViewOptions::OutputFormat> Format(
564 "format", cl::desc("Output format for line-based coverage reports"),
565 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
567 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
569 cl::init(CoverageViewOptions::OutputFormat::Text));
571 cl::opt<std::string> PathRemap(
572 "path-equivalence", cl::Optional,
573 cl::desc("<from>,<to> Map coverage data paths to local source file "
576 cl::OptionCategory FilteringCategory("Function filtering options");
578 cl::list<std::string> NameFilters(
579 "name", cl::Optional,
580 cl::desc("Show code coverage only for functions with the given name"),
581 cl::ZeroOrMore, cl::cat(FilteringCategory));
583 cl::list<std::string> NameFilterFiles(
584 "name-whitelist", cl::Optional,
585 cl::desc("Show code coverage only for functions listed in the given "
587 cl::ZeroOrMore, cl::cat(FilteringCategory));
589 cl::list<std::string> NameRegexFilters(
590 "name-regex", cl::Optional,
591 cl::desc("Show code coverage only for functions that match the given "
592 "regular expression"),
593 cl::ZeroOrMore, cl::cat(FilteringCategory));
595 cl::opt<double> RegionCoverageLtFilter(
596 "region-coverage-lt", cl::Optional,
597 cl::desc("Show code coverage only for functions with region coverage "
598 "less than the given threshold"),
599 cl::cat(FilteringCategory));
601 cl::opt<double> RegionCoverageGtFilter(
602 "region-coverage-gt", cl::Optional,
603 cl::desc("Show code coverage only for functions with region coverage "
604 "greater than the given threshold"),
605 cl::cat(FilteringCategory));
607 cl::opt<double> LineCoverageLtFilter(
608 "line-coverage-lt", cl::Optional,
609 cl::desc("Show code coverage only for functions with line coverage less "
610 "than the given threshold"),
611 cl::cat(FilteringCategory));
613 cl::opt<double> LineCoverageGtFilter(
614 "line-coverage-gt", cl::Optional,
615 cl::desc("Show code coverage only for functions with line coverage "
616 "greater than the given threshold"),
617 cl::cat(FilteringCategory));
619 cl::opt<cl::boolOrDefault> UseColor(
620 "use-color", cl::desc("Emit colored output (default=autodetect)"),
621 cl::init(cl::BOU_UNSET));
623 cl::list<std::string> DemanglerOpts(
624 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
626 cl::opt<bool> RegionSummary(
627 "show-region-summary", cl::Optional,
628 cl::desc("Show region statistics in summary table"),
631 cl::opt<bool> InstantiationSummary(
632 "show-instantiation-summary", cl::Optional,
633 cl::desc("Show instantiation statistics in summary table"));
635 cl::opt<bool> SummaryOnly(
636 "summary-only", cl::Optional,
637 cl::desc("Export only summary information for each source file"));
639 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
640 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
641 ViewOpts.Debug = DebugDump;
643 if (!CovFilename.empty())
644 ObjectFilenames.emplace_back(CovFilename);
645 for (const std::string &Filename : CovFilenames)
646 ObjectFilenames.emplace_back(Filename);
647 if (ObjectFilenames.empty()) {
648 errs() << "No filenames specified!\n";
652 ViewOpts.Format = Format;
653 switch (ViewOpts.Format) {
654 case CoverageViewOptions::OutputFormat::Text:
655 ViewOpts.Colors = UseColor == cl::BOU_UNSET
656 ? sys::Process::StandardOutHasColors()
657 : UseColor == cl::BOU_TRUE;
659 case CoverageViewOptions::OutputFormat::HTML:
660 if (UseColor == cl::BOU_FALSE)
661 errs() << "Color output cannot be disabled when generating html.\n";
662 ViewOpts.Colors = true;
666 // If path-equivalence was given and is a comma seperated pair then set
668 auto EquivPair = StringRef(PathRemap).split(',');
669 if (!(EquivPair.first.empty() && EquivPair.second.empty()))
670 PathRemapping = EquivPair;
672 // If a demangler is supplied, check if it exists and register it.
673 if (DemanglerOpts.size()) {
674 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
675 if (!DemanglerPathOrErr) {
676 error("Could not find the demangler!",
677 DemanglerPathOrErr.getError().message());
680 DemanglerOpts[0] = *DemanglerPathOrErr;
681 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
684 // Read in -name-whitelist files.
685 if (!NameFilterFiles.empty()) {
686 std::string SpecialCaseListErr;
688 SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
690 error(SpecialCaseListErr);
693 // Create the function filters
694 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) {
695 auto NameFilterer = llvm::make_unique<CoverageFilters>();
696 for (const auto &Name : NameFilters)
697 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
699 NameFilterer->push_back(
700 llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
701 for (const auto &Regex : NameRegexFilters)
702 NameFilterer->push_back(
703 llvm::make_unique<NameRegexCoverageFilter>(Regex));
704 Filters.push_back(std::move(NameFilterer));
706 if (RegionCoverageLtFilter.getNumOccurrences() ||
707 RegionCoverageGtFilter.getNumOccurrences() ||
708 LineCoverageLtFilter.getNumOccurrences() ||
709 LineCoverageGtFilter.getNumOccurrences()) {
710 auto StatFilterer = llvm::make_unique<CoverageFilters>();
711 if (RegionCoverageLtFilter.getNumOccurrences())
712 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
713 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
714 if (RegionCoverageGtFilter.getNumOccurrences())
715 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
716 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
717 if (LineCoverageLtFilter.getNumOccurrences())
718 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
719 LineCoverageFilter::LessThan, LineCoverageLtFilter));
720 if (LineCoverageGtFilter.getNumOccurrences())
721 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
722 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
723 Filters.push_back(std::move(StatFilterer));
726 if (!Arches.empty()) {
727 for (const std::string &Arch : Arches) {
728 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
729 error("Unknown architecture: " + Arch);
732 CoverageArches.emplace_back(Arch);
734 if (CoverageArches.size() != ObjectFilenames.size()) {
735 error("Number of architectures doesn't match the number of objects");
740 for (const std::string &File : InputSourceFiles)
743 if (DebugDumpCollectedPaths) {
744 for (const std::string &SF : SourceFiles)
745 outs() << SF << '\n';
749 ViewOpts.ShowRegionSummary = RegionSummary;
750 ViewOpts.ShowInstantiationSummary = InstantiationSummary;
751 ViewOpts.ExportSummaryOnly = SummaryOnly;
758 return show(argc, argv, commandLineParser);
760 return report(argc, argv, commandLineParser);
762 return export_(argc, argv, commandLineParser);
767 int CodeCoverageTool::show(int argc, const char **argv,
768 CommandLineParserType commandLineParser) {
770 cl::OptionCategory ViewCategory("Viewing options");
772 cl::opt<bool> ShowLineExecutionCounts(
773 "show-line-counts", cl::Optional,
774 cl::desc("Show the execution counts for each line"), cl::init(true),
775 cl::cat(ViewCategory));
777 cl::opt<bool> ShowRegions(
778 "show-regions", cl::Optional,
779 cl::desc("Show the execution counts for each region"),
780 cl::cat(ViewCategory));
782 cl::opt<bool> ShowBestLineRegionsCounts(
783 "show-line-counts-or-regions", cl::Optional,
784 cl::desc("Show the execution counts for each line, or the execution "
785 "counts for each region on lines that have multiple regions"),
786 cl::cat(ViewCategory));
788 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
789 cl::desc("Show expanded source regions"),
790 cl::cat(ViewCategory));
792 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
793 cl::desc("Show function instantiations"),
794 cl::init(true), cl::cat(ViewCategory));
796 cl::opt<std::string> ShowOutputDirectory(
797 "output-dir", cl::init(""),
798 cl::desc("Directory in which coverage information is written out"));
799 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
800 cl::aliasopt(ShowOutputDirectory));
802 cl::opt<uint32_t> TabSize(
803 "tab-size", cl::init(2),
805 "Set tab expansion size for html coverage reports (default = 2)"));
807 cl::opt<std::string> ProjectTitle(
808 "project-title", cl::Optional,
809 cl::desc("Set project title for the coverage report"));
811 cl::opt<unsigned> NumThreads(
812 "num-threads", cl::init(0),
813 cl::desc("Number of merge threads to use (default: autodetect)"));
814 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
815 cl::aliasopt(NumThreads));
817 auto Err = commandLineParser(argc, argv);
821 ViewOpts.ShowLineNumbers = true;
822 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
823 !ShowRegions || ShowBestLineRegionsCounts;
824 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
825 ViewOpts.ShowExpandedRegions = ShowExpansions;
826 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
827 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
828 ViewOpts.TabSize = TabSize;
829 ViewOpts.ProjectTitle = ProjectTitle;
831 if (ViewOpts.hasOutputDirectory()) {
832 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
833 error("Could not create output directory!", E.message());
838 sys::fs::file_status Status;
839 if (sys::fs::status(PGOFilename, Status)) {
840 error("profdata file error: can not get the file status. \n");
844 auto ModifiedTime = Status.getLastModificationTime();
845 std::string ModifiedTimeStr = to_string(ModifiedTime);
846 size_t found = ModifiedTimeStr.rfind(':');
847 ViewOpts.CreatedTimeStr = (found != std::string::npos)
848 ? "Created: " + ModifiedTimeStr.substr(0, found)
849 : "Created: " + ModifiedTimeStr;
851 auto Coverage = load();
855 auto Printer = CoveragePrinter::create(ViewOpts);
857 if (SourceFiles.empty())
858 // Get the source files from the function coverage mapping.
859 for (StringRef Filename : Coverage->getUniqueSourceFiles())
860 SourceFiles.push_back(Filename);
862 // Create an index out of the source files.
863 if (ViewOpts.hasOutputDirectory()) {
864 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) {
865 error("Could not create index file!", toString(std::move(E)));
870 if (!Filters.empty()) {
871 // Build the map of filenames to functions.
872 std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
874 for (const auto &SourceFile : SourceFiles)
875 for (const auto &Function : Coverage->getCoveredFunctions(SourceFile))
876 if (Filters.matches(*Coverage.get(), Function))
877 FilenameFunctionMap[SourceFile].push_back(&Function);
879 // Only print filter matching functions for each file.
880 for (const auto &FileFunc : FilenameFunctionMap) {
881 StringRef File = FileFunc.first;
882 const auto &Functions = FileFunc.second;
884 auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false);
885 if (Error E = OSOrErr.takeError()) {
886 error("Could not create view file!", toString(std::move(E)));
889 auto OS = std::move(OSOrErr.get());
891 bool ShowTitle = ViewOpts.hasOutputDirectory();
892 for (const auto *Function : Functions) {
893 auto FunctionView = createFunctionView(*Function, *Coverage);
895 warning("Could not read coverage for '" + Function->Name + "'.");
898 FunctionView->print(*OS.get(), /*WholeFile=*/false,
899 /*ShowSourceName=*/true, ShowTitle);
903 Printer->closeViewFile(std::move(OS));
910 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
911 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
913 // If NumThreads is not specified, auto-detect a good default.
916 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
917 unsigned(SourceFiles.size())));
919 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
920 for (const std::string &SourceFile : SourceFiles)
921 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
924 // In -output-dir mode, it's safe to use multiple threads to print files.
925 ThreadPool Pool(NumThreads);
926 for (const std::string &SourceFile : SourceFiles)
927 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
928 Coverage.get(), Printer.get(), ShowFilenames);
935 int CodeCoverageTool::report(int argc, const char **argv,
936 CommandLineParserType commandLineParser) {
937 cl::opt<bool> ShowFunctionSummaries(
938 "show-functions", cl::Optional, cl::init(false),
939 cl::desc("Show coverage summaries for each function"));
941 auto Err = commandLineParser(argc, argv);
945 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
946 error("HTML output for summary reports is not yet supported.");
950 auto Coverage = load();
954 CoverageReport Report(ViewOpts, *Coverage.get());
955 if (!ShowFunctionSummaries) {
956 if (SourceFiles.empty())
957 Report.renderFileReports(llvm::outs());
959 Report.renderFileReports(llvm::outs(), SourceFiles);
961 if (SourceFiles.empty()) {
962 error("Source files must be specified when -show-functions=true is "
967 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
972 int CodeCoverageTool::export_(int argc, const char **argv,
973 CommandLineParserType commandLineParser) {
975 auto Err = commandLineParser(argc, argv);
979 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
980 error("Coverage data can only be exported as textual JSON.");
984 auto Coverage = load();
986 error("Could not load coverage information");
990 exportCoverageDataToJson(*Coverage.get(), ViewOpts, outs());
995 int showMain(int argc, const char *argv[]) {
996 CodeCoverageTool Tool;
997 return Tool.run(CodeCoverageTool::Show, argc, argv);
1000 int reportMain(int argc, const char *argv[]) {
1001 CodeCoverageTool Tool;
1002 return Tool.run(CodeCoverageTool::Report, argc, argv);
1005 int exportMain(int argc, const char *argv[]) {
1006 CodeCoverageTool Tool;
1007 return Tool.run(CodeCoverageTool::Export, argc, argv);