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