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