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