1 //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The 'CodeCoverageTool' class implements a command line tool to analyze and 11 // report coverage information using the profiling instrumentation and code 12 // coverage mapping. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "CoverageFilters.h" 17 #include "CoverageReport.h" 18 #include "CoverageSummaryInfo.h" 19 #include "CoverageViewOptions.h" 20 #include "RenderingSupport.h" 21 #include "SourceCoverageView.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ProfileData/Coverage/CoverageMapping.h" 26 #include "llvm/ProfileData/InstrProfReader.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/Format.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/Process.h" 33 #include "llvm/Support/Program.h" 34 #include "llvm/Support/ScopedPrinter.h" 35 #include "llvm/Support/Threading.h" 36 #include "llvm/Support/ThreadPool.h" 37 #include "llvm/Support/ToolOutputFile.h" 38 #include <functional> 39 #include <system_error> 40 41 using namespace llvm; 42 using namespace coverage; 43 44 void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping, 45 const CoverageViewOptions &Options, 46 raw_ostream &OS); 47 48 namespace { 49 /// \brief The implementation of the coverage tool. 50 class CodeCoverageTool { 51 public: 52 enum Command { 53 /// \brief The show command. 54 Show, 55 /// \brief The report command. 56 Report, 57 /// \brief The export command. 58 Export 59 }; 60 61 int run(Command Cmd, int argc, const char **argv); 62 63 private: 64 /// \brief Print the error message to the error output stream. 65 void error(const Twine &Message, StringRef Whence = ""); 66 67 /// \brief Print the warning message to the error output stream. 68 void warning(const Twine &Message, StringRef Whence = ""); 69 70 /// \brief Convert \p Path into an absolute path and append it to the list 71 /// of collected paths. 72 void addCollectedPath(const std::string &Path); 73 74 /// \brief If \p Path is a regular file, collect the path. If it's a 75 /// directory, recursively collect all of the paths within the directory. 76 void collectPaths(const std::string &Path); 77 78 /// \brief Return a memory buffer for the given source file. 79 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile); 80 81 /// \brief Create source views for the expansions of the view. 82 void attachExpansionSubViews(SourceCoverageView &View, 83 ArrayRef<ExpansionRecord> Expansions, 84 const CoverageMapping &Coverage); 85 86 /// \brief Create the source view of a particular function. 87 std::unique_ptr<SourceCoverageView> 88 createFunctionView(const FunctionRecord &Function, 89 const CoverageMapping &Coverage); 90 91 /// \brief Create the main source view of a particular source file. 92 std::unique_ptr<SourceCoverageView> 93 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage); 94 95 /// \brief Load the coverage mapping data. Return nullptr if an error occurred. 96 std::unique_ptr<CoverageMapping> load(); 97 98 /// \brief Create a mapping from files in the Coverage data to local copies 99 /// (path-equivalence). 100 void remapPathNames(const CoverageMapping &Coverage); 101 102 /// \brief Remove input source files which aren't mapped by \p Coverage. 103 void removeUnmappedInputs(const CoverageMapping &Coverage); 104 105 /// \brief If a demangler is available, demangle all symbol names. 106 void demangleSymbols(const CoverageMapping &Coverage); 107 108 /// \brief Write out a source file view to the filesystem. 109 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage, 110 CoveragePrinter *Printer, bool ShowFilenames); 111 112 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType; 113 114 int show(int argc, const char **argv, 115 CommandLineParserType commandLineParser); 116 117 int report(int argc, const char **argv, 118 CommandLineParserType commandLineParser); 119 120 int export_(int argc, const char **argv, 121 CommandLineParserType commandLineParser); 122 123 std::vector<StringRef> ObjectFilenames; 124 CoverageViewOptions ViewOpts; 125 CoverageFiltersMatchAll Filters; 126 127 /// The path to the indexed profile. 128 std::string PGOFilename; 129 130 /// A list of input source files. 131 std::vector<std::string> SourceFiles; 132 133 /// In -path-equivalence mode, this maps the absolute paths from the coverage 134 /// mapping data to the input source files. 135 StringMap<std::string> RemappedFilenames; 136 137 /// The coverage data path to be remapped from, and the source path to be 138 /// remapped to, when using -path-equivalence. 139 Optional<std::pair<std::string, std::string>> PathRemapping; 140 141 /// The architecture the coverage mapping data targets. 142 std::vector<StringRef> CoverageArches; 143 144 /// A cache for demangled symbols. 145 DemangleCache DC; 146 147 /// A lock which guards printing to stderr. 148 std::mutex ErrsLock; 149 150 /// A container for input source file buffers. 151 std::mutex LoadedSourceFilesLock; 152 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>> 153 LoadedSourceFiles; 154 155 /// Whitelist from -name-whitelist to be used for filtering. 156 std::unique_ptr<SpecialCaseList> NameWhitelist; 157 }; 158 } 159 160 static std::string getErrorString(const Twine &Message, StringRef Whence, 161 bool Warning) { 162 std::string Str = (Warning ? "warning" : "error"); 163 Str += ": "; 164 if (!Whence.empty()) 165 Str += Whence.str() + ": "; 166 Str += Message.str() + "\n"; 167 return Str; 168 } 169 170 void CodeCoverageTool::error(const Twine &Message, StringRef Whence) { 171 std::unique_lock<std::mutex> Guard{ErrsLock}; 172 ViewOpts.colored_ostream(errs(), raw_ostream::RED) 173 << getErrorString(Message, Whence, false); 174 } 175 176 void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) { 177 std::unique_lock<std::mutex> Guard{ErrsLock}; 178 ViewOpts.colored_ostream(errs(), raw_ostream::RED) 179 << getErrorString(Message, Whence, true); 180 } 181 182 void CodeCoverageTool::addCollectedPath(const std::string &Path) { 183 SmallString<128> EffectivePath(Path); 184 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) { 185 error(EC.message(), Path); 186 return; 187 } 188 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true); 189 SourceFiles.emplace_back(EffectivePath.str()); 190 } 191 192 void CodeCoverageTool::collectPaths(const std::string &Path) { 193 llvm::sys::fs::file_status Status; 194 llvm::sys::fs::status(Path, Status); 195 if (!llvm::sys::fs::exists(Status)) { 196 if (PathRemapping) 197 addCollectedPath(Path); 198 else 199 error("Missing source file", Path); 200 return; 201 } 202 203 if (llvm::sys::fs::is_regular_file(Status)) { 204 addCollectedPath(Path); 205 return; 206 } 207 208 if (llvm::sys::fs::is_directory(Status)) { 209 std::error_code EC; 210 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E; 211 F != E && !EC; F.increment(EC)) { 212 if (llvm::sys::fs::is_regular_file(F->path())) 213 addCollectedPath(F->path()); 214 } 215 if (EC) 216 warning(EC.message(), Path); 217 } 218 } 219 220 ErrorOr<const MemoryBuffer &> 221 CodeCoverageTool::getSourceFile(StringRef SourceFile) { 222 // If we've remapped filenames, look up the real location for this file. 223 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock}; 224 if (!RemappedFilenames.empty()) { 225 auto Loc = RemappedFilenames.find(SourceFile); 226 if (Loc != RemappedFilenames.end()) 227 SourceFile = Loc->second; 228 } 229 for (const auto &Files : LoadedSourceFiles) 230 if (sys::fs::equivalent(SourceFile, Files.first)) 231 return *Files.second; 232 auto Buffer = MemoryBuffer::getFile(SourceFile); 233 if (auto EC = Buffer.getError()) { 234 error(EC.message(), SourceFile); 235 return EC; 236 } 237 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get())); 238 return *LoadedSourceFiles.back().second; 239 } 240 241 void CodeCoverageTool::attachExpansionSubViews( 242 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions, 243 const CoverageMapping &Coverage) { 244 if (!ViewOpts.ShowExpandedRegions) 245 return; 246 for (const auto &Expansion : Expansions) { 247 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion); 248 if (ExpansionCoverage.empty()) 249 continue; 250 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename()); 251 if (!SourceBuffer) 252 continue; 253 254 auto SubViewExpansions = ExpansionCoverage.getExpansions(); 255 auto SubView = 256 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(), 257 ViewOpts, std::move(ExpansionCoverage)); 258 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage); 259 View.addExpansion(Expansion.Region, std::move(SubView)); 260 } 261 } 262 263 std::unique_ptr<SourceCoverageView> 264 CodeCoverageTool::createFunctionView(const FunctionRecord &Function, 265 const CoverageMapping &Coverage) { 266 auto FunctionCoverage = Coverage.getCoverageForFunction(Function); 267 if (FunctionCoverage.empty()) 268 return nullptr; 269 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename()); 270 if (!SourceBuffer) 271 return nullptr; 272 273 auto Expansions = FunctionCoverage.getExpansions(); 274 auto View = SourceCoverageView::create(DC.demangle(Function.Name), 275 SourceBuffer.get(), ViewOpts, 276 std::move(FunctionCoverage)); 277 attachExpansionSubViews(*View, Expansions, Coverage); 278 279 return View; 280 } 281 282 std::unique_ptr<SourceCoverageView> 283 CodeCoverageTool::createSourceFileView(StringRef SourceFile, 284 const CoverageMapping &Coverage) { 285 auto SourceBuffer = getSourceFile(SourceFile); 286 if (!SourceBuffer) 287 return nullptr; 288 auto FileCoverage = Coverage.getCoverageForFile(SourceFile); 289 if (FileCoverage.empty()) 290 return nullptr; 291 292 auto Expansions = FileCoverage.getExpansions(); 293 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(), 294 ViewOpts, std::move(FileCoverage)); 295 attachExpansionSubViews(*View, Expansions, Coverage); 296 if (!ViewOpts.ShowFunctionInstantiations) 297 return View; 298 299 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) { 300 // Skip functions which have a single instantiation. 301 if (Group.size() < 2) 302 continue; 303 304 for (const FunctionRecord *Function : Group.getInstantiations()) { 305 std::unique_ptr<SourceCoverageView> SubView{nullptr}; 306 307 StringRef Funcname = DC.demangle(Function->Name); 308 309 if (Function->ExecutionCount > 0) { 310 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function); 311 auto SubViewExpansions = SubViewCoverage.getExpansions(); 312 SubView = SourceCoverageView::create( 313 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage)); 314 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage); 315 } 316 317 unsigned FileID = Function->CountedRegions.front().FileID; 318 unsigned Line = 0; 319 for (const auto &CR : Function->CountedRegions) 320 if (CR.FileID == FileID) 321 Line = std::max(CR.LineEnd, Line); 322 View->addInstantiation(Funcname, Line, std::move(SubView)); 323 } 324 } 325 return View; 326 } 327 328 static bool modifiedTimeGT(StringRef LHS, StringRef RHS) { 329 sys::fs::file_status Status; 330 if (sys::fs::status(LHS, Status)) 331 return false; 332 auto LHSTime = Status.getLastModificationTime(); 333 if (sys::fs::status(RHS, Status)) 334 return false; 335 auto RHSTime = Status.getLastModificationTime(); 336 return LHSTime > RHSTime; 337 } 338 339 std::unique_ptr<CoverageMapping> CodeCoverageTool::load() { 340 for (StringRef ObjectFilename : ObjectFilenames) 341 if (modifiedTimeGT(ObjectFilename, PGOFilename)) 342 warning("profile data may be out of date - object is newer", 343 ObjectFilename); 344 auto CoverageOrErr = 345 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches); 346 if (Error E = CoverageOrErr.takeError()) { 347 error("Failed to load coverage: " + toString(std::move(E)), 348 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", ")); 349 return nullptr; 350 } 351 auto Coverage = std::move(CoverageOrErr.get()); 352 unsigned Mismatched = Coverage->getMismatchedCount(); 353 if (Mismatched) 354 warning(utostr(Mismatched) + " functions have mismatched data"); 355 356 remapPathNames(*Coverage); 357 358 if (!SourceFiles.empty()) 359 removeUnmappedInputs(*Coverage); 360 361 demangleSymbols(*Coverage); 362 363 return Coverage; 364 } 365 366 void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) { 367 if (!PathRemapping) 368 return; 369 370 // Convert remapping paths to native paths with trailing seperators. 371 auto nativeWithTrailing = [](StringRef Path) -> std::string { 372 if (Path.empty()) 373 return ""; 374 SmallString<128> NativePath; 375 sys::path::native(Path, NativePath); 376 if (!sys::path::is_separator(NativePath.back())) 377 NativePath += sys::path::get_separator(); 378 return NativePath.c_str(); 379 }; 380 std::string RemapFrom = nativeWithTrailing(PathRemapping->first); 381 std::string RemapTo = nativeWithTrailing(PathRemapping->second); 382 383 // Create a mapping from coverage data file paths to local paths. 384 for (StringRef Filename : Coverage.getUniqueSourceFiles()) { 385 SmallString<128> NativeFilename; 386 sys::path::native(Filename, NativeFilename); 387 if (NativeFilename.startswith(RemapFrom)) { 388 RemappedFilenames[Filename] = 389 RemapTo + NativeFilename.substr(RemapFrom.size()).str(); 390 } 391 } 392 393 // Convert input files from local paths to coverage data file paths. 394 StringMap<std::string> InvRemappedFilenames; 395 for (const auto &RemappedFilename : RemappedFilenames) 396 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey(); 397 398 for (std::string &Filename : SourceFiles) { 399 SmallString<128> NativeFilename; 400 sys::path::native(Filename, NativeFilename); 401 auto CovFileName = InvRemappedFilenames.find(NativeFilename); 402 if (CovFileName != InvRemappedFilenames.end()) 403 Filename = CovFileName->second; 404 } 405 } 406 407 void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) { 408 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles(); 409 410 auto UncoveredFilesIt = SourceFiles.end(); 411 // The user may have specified source files which aren't in the coverage 412 // mapping. Filter these files away. 413 UncoveredFilesIt = std::remove_if( 414 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) { 415 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(), 416 SF); 417 }); 418 419 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end()); 420 } 421 422 void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) { 423 if (!ViewOpts.hasDemangler()) 424 return; 425 426 // Pass function names to the demangler in a temporary file. 427 int InputFD; 428 SmallString<256> InputPath; 429 std::error_code EC = 430 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath); 431 if (EC) { 432 error(InputPath, EC.message()); 433 return; 434 } 435 tool_output_file InputTOF{InputPath, InputFD}; 436 437 unsigned NumSymbols = 0; 438 for (const auto &Function : Coverage.getCoveredFunctions()) { 439 InputTOF.os() << Function.Name << '\n'; 440 ++NumSymbols; 441 } 442 InputTOF.os().close(); 443 444 // Use another temporary file to store the demangler's output. 445 int OutputFD; 446 SmallString<256> OutputPath; 447 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD, 448 OutputPath); 449 if (EC) { 450 error(OutputPath, EC.message()); 451 return; 452 } 453 tool_output_file OutputTOF{OutputPath, OutputFD}; 454 OutputTOF.os().close(); 455 456 // Invoke the demangler. 457 std::vector<const char *> ArgsV; 458 for (const std::string &Arg : ViewOpts.DemanglerOpts) 459 ArgsV.push_back(Arg.c_str()); 460 ArgsV.push_back(nullptr); 461 StringRef InputPathRef = InputPath.str(); 462 StringRef OutputPathRef = OutputPath.str(); 463 StringRef StderrRef; 464 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef}; 465 std::string ErrMsg; 466 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(), 467 /*env=*/nullptr, Redirects, /*secondsToWait=*/0, 468 /*memoryLimit=*/0, &ErrMsg); 469 if (RC) { 470 error(ErrMsg, ViewOpts.DemanglerOpts[0]); 471 return; 472 } 473 474 // Parse the demangler's output. 475 auto BufOrError = MemoryBuffer::getFile(OutputPath); 476 if (!BufOrError) { 477 error(OutputPath, BufOrError.getError().message()); 478 return; 479 } 480 481 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError); 482 483 SmallVector<StringRef, 8> Symbols; 484 StringRef DemanglerData = DemanglerBuf->getBuffer(); 485 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols, 486 /*KeepEmpty=*/false); 487 if (Symbols.size() != NumSymbols) { 488 error("Demangler did not provide expected number of symbols"); 489 return; 490 } 491 492 // Cache the demangled names. 493 unsigned I = 0; 494 for (const auto &Function : Coverage.getCoveredFunctions()) 495 // On Windows, lines in the demangler's output file end with "\r\n". 496 // Splitting by '\n' keeps '\r's, so cut them now. 497 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim(); 498 } 499 500 void CodeCoverageTool::writeSourceFileView(StringRef SourceFile, 501 CoverageMapping *Coverage, 502 CoveragePrinter *Printer, 503 bool ShowFilenames) { 504 auto View = createSourceFileView(SourceFile, *Coverage); 505 if (!View) { 506 warning("The file '" + SourceFile + "' isn't covered."); 507 return; 508 } 509 510 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false); 511 if (Error E = OSOrErr.takeError()) { 512 error("Could not create view file!", toString(std::move(E))); 513 return; 514 } 515 auto OS = std::move(OSOrErr.get()); 516 517 View->print(*OS.get(), /*Wholefile=*/true, 518 /*ShowSourceName=*/ShowFilenames); 519 Printer->closeViewFile(std::move(OS)); 520 } 521 522 int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) { 523 cl::opt<std::string> CovFilename( 524 cl::Positional, cl::desc("Covered executable or object file.")); 525 526 cl::list<std::string> CovFilenames( 527 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore, 528 cl::CommaSeparated); 529 530 cl::list<std::string> InputSourceFiles( 531 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore); 532 533 cl::opt<bool> DebugDumpCollectedPaths( 534 "dump-collected-paths", cl::Optional, cl::Hidden, 535 cl::desc("Show the collected paths to source files")); 536 537 cl::opt<std::string, true> PGOFilename( 538 "instr-profile", cl::Required, cl::location(this->PGOFilename), 539 cl::desc( 540 "File with the profile data obtained after an instrumented run")); 541 542 cl::list<std::string> Arches( 543 "arch", cl::desc("architectures of the coverage mapping binaries")); 544 545 cl::opt<bool> DebugDump("dump", cl::Optional, 546 cl::desc("Show internal debug dump")); 547 548 cl::opt<CoverageViewOptions::OutputFormat> Format( 549 "format", cl::desc("Output format for line-based coverage reports"), 550 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text", 551 "Text output"), 552 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html", 553 "HTML output")), 554 cl::init(CoverageViewOptions::OutputFormat::Text)); 555 556 cl::opt<std::string> PathRemap( 557 "path-equivalence", cl::Optional, 558 cl::desc("<from>,<to> Map coverage data paths to local source file " 559 "paths")); 560 561 cl::OptionCategory FilteringCategory("Function filtering options"); 562 563 cl::list<std::string> NameFilters( 564 "name", cl::Optional, 565 cl::desc("Show code coverage only for functions with the given name"), 566 cl::ZeroOrMore, cl::cat(FilteringCategory)); 567 568 cl::list<std::string> NameFilterFiles( 569 "name-whitelist", cl::Optional, 570 cl::desc("Show code coverage only for functions listed in the given " 571 "file"), 572 cl::ZeroOrMore, cl::cat(FilteringCategory)); 573 574 cl::list<std::string> NameRegexFilters( 575 "name-regex", cl::Optional, 576 cl::desc("Show code coverage only for functions that match the given " 577 "regular expression"), 578 cl::ZeroOrMore, cl::cat(FilteringCategory)); 579 580 cl::opt<double> RegionCoverageLtFilter( 581 "region-coverage-lt", cl::Optional, 582 cl::desc("Show code coverage only for functions with region coverage " 583 "less than the given threshold"), 584 cl::cat(FilteringCategory)); 585 586 cl::opt<double> RegionCoverageGtFilter( 587 "region-coverage-gt", cl::Optional, 588 cl::desc("Show code coverage only for functions with region coverage " 589 "greater than the given threshold"), 590 cl::cat(FilteringCategory)); 591 592 cl::opt<double> LineCoverageLtFilter( 593 "line-coverage-lt", cl::Optional, 594 cl::desc("Show code coverage only for functions with line coverage less " 595 "than the given threshold"), 596 cl::cat(FilteringCategory)); 597 598 cl::opt<double> LineCoverageGtFilter( 599 "line-coverage-gt", cl::Optional, 600 cl::desc("Show code coverage only for functions with line coverage " 601 "greater than the given threshold"), 602 cl::cat(FilteringCategory)); 603 604 cl::opt<cl::boolOrDefault> UseColor( 605 "use-color", cl::desc("Emit colored output (default=autodetect)"), 606 cl::init(cl::BOU_UNSET)); 607 608 cl::list<std::string> DemanglerOpts( 609 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>")); 610 611 auto commandLineParser = [&, this](int argc, const char **argv) -> int { 612 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n"); 613 ViewOpts.Debug = DebugDump; 614 615 if (!CovFilename.empty()) 616 ObjectFilenames.emplace_back(CovFilename); 617 for (const std::string &Filename : CovFilenames) 618 ObjectFilenames.emplace_back(Filename); 619 if (ObjectFilenames.empty()) { 620 errs() << "No filenames specified!\n"; 621 ::exit(1); 622 } 623 624 ViewOpts.Format = Format; 625 switch (ViewOpts.Format) { 626 case CoverageViewOptions::OutputFormat::Text: 627 ViewOpts.Colors = UseColor == cl::BOU_UNSET 628 ? sys::Process::StandardOutHasColors() 629 : UseColor == cl::BOU_TRUE; 630 break; 631 case CoverageViewOptions::OutputFormat::HTML: 632 if (UseColor == cl::BOU_FALSE) 633 errs() << "Color output cannot be disabled when generating html.\n"; 634 ViewOpts.Colors = true; 635 break; 636 } 637 638 // If path-equivalence was given and is a comma seperated pair then set 639 // PathRemapping. 640 auto EquivPair = StringRef(PathRemap).split(','); 641 if (!(EquivPair.first.empty() && EquivPair.second.empty())) 642 PathRemapping = EquivPair; 643 644 // If a demangler is supplied, check if it exists and register it. 645 if (DemanglerOpts.size()) { 646 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]); 647 if (!DemanglerPathOrErr) { 648 error("Could not find the demangler!", 649 DemanglerPathOrErr.getError().message()); 650 return 1; 651 } 652 DemanglerOpts[0] = *DemanglerPathOrErr; 653 ViewOpts.DemanglerOpts.swap(DemanglerOpts); 654 } 655 656 // Read in -name-whitelist files. 657 if (!NameFilterFiles.empty()) { 658 std::string SpecialCaseListErr; 659 NameWhitelist = 660 SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr); 661 if (!NameWhitelist) 662 error(SpecialCaseListErr); 663 } 664 665 // Create the function filters 666 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) { 667 auto NameFilterer = llvm::make_unique<CoverageFilters>(); 668 for (const auto &Name : NameFilters) 669 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name)); 670 if (NameWhitelist) 671 NameFilterer->push_back( 672 llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist)); 673 for (const auto &Regex : NameRegexFilters) 674 NameFilterer->push_back( 675 llvm::make_unique<NameRegexCoverageFilter>(Regex)); 676 Filters.push_back(std::move(NameFilterer)); 677 } 678 if (RegionCoverageLtFilter.getNumOccurrences() || 679 RegionCoverageGtFilter.getNumOccurrences() || 680 LineCoverageLtFilter.getNumOccurrences() || 681 LineCoverageGtFilter.getNumOccurrences()) { 682 auto StatFilterer = llvm::make_unique<CoverageFilters>(); 683 if (RegionCoverageLtFilter.getNumOccurrences()) 684 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>( 685 RegionCoverageFilter::LessThan, RegionCoverageLtFilter)); 686 if (RegionCoverageGtFilter.getNumOccurrences()) 687 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>( 688 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter)); 689 if (LineCoverageLtFilter.getNumOccurrences()) 690 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>( 691 LineCoverageFilter::LessThan, LineCoverageLtFilter)); 692 if (LineCoverageGtFilter.getNumOccurrences()) 693 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>( 694 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter)); 695 Filters.push_back(std::move(StatFilterer)); 696 } 697 698 if (!Arches.empty()) { 699 for (const std::string &Arch : Arches) { 700 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) { 701 error("Unknown architecture: " + Arch); 702 return 1; 703 } 704 CoverageArches.emplace_back(Arch); 705 } 706 if (CoverageArches.size() != ObjectFilenames.size()) { 707 error("Number of architectures doesn't match the number of objects"); 708 return 1; 709 } 710 } 711 712 for (const std::string &File : InputSourceFiles) 713 collectPaths(File); 714 715 if (DebugDumpCollectedPaths) { 716 for (const std::string &SF : SourceFiles) 717 outs() << SF << '\n'; 718 ::exit(0); 719 } 720 721 return 0; 722 }; 723 724 switch (Cmd) { 725 case Show: 726 return show(argc, argv, commandLineParser); 727 case Report: 728 return report(argc, argv, commandLineParser); 729 case Export: 730 return export_(argc, argv, commandLineParser); 731 } 732 return 0; 733 } 734 735 int CodeCoverageTool::show(int argc, const char **argv, 736 CommandLineParserType commandLineParser) { 737 738 cl::OptionCategory ViewCategory("Viewing options"); 739 740 cl::opt<bool> ShowLineExecutionCounts( 741 "show-line-counts", cl::Optional, 742 cl::desc("Show the execution counts for each line"), cl::init(true), 743 cl::cat(ViewCategory)); 744 745 cl::opt<bool> ShowRegions( 746 "show-regions", cl::Optional, 747 cl::desc("Show the execution counts for each region"), 748 cl::cat(ViewCategory)); 749 750 cl::opt<bool> ShowBestLineRegionsCounts( 751 "show-line-counts-or-regions", cl::Optional, 752 cl::desc("Show the execution counts for each line, or the execution " 753 "counts for each region on lines that have multiple regions"), 754 cl::cat(ViewCategory)); 755 756 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional, 757 cl::desc("Show expanded source regions"), 758 cl::cat(ViewCategory)); 759 760 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional, 761 cl::desc("Show function instantiations"), 762 cl::init(true), cl::cat(ViewCategory)); 763 764 cl::opt<std::string> ShowOutputDirectory( 765 "output-dir", cl::init(""), 766 cl::desc("Directory in which coverage information is written out")); 767 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"), 768 cl::aliasopt(ShowOutputDirectory)); 769 770 cl::opt<uint32_t> TabSize( 771 "tab-size", cl::init(2), 772 cl::desc( 773 "Set tab expansion size for html coverage reports (default = 2)")); 774 775 cl::opt<std::string> ProjectTitle( 776 "project-title", cl::Optional, 777 cl::desc("Set project title for the coverage report")); 778 779 cl::opt<unsigned> NumThreads( 780 "num-threads", cl::init(0), 781 cl::desc("Number of merge threads to use (default: autodetect)")); 782 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"), 783 cl::aliasopt(NumThreads)); 784 785 auto Err = commandLineParser(argc, argv); 786 if (Err) 787 return Err; 788 789 ViewOpts.ShowLineNumbers = true; 790 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 || 791 !ShowRegions || ShowBestLineRegionsCounts; 792 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts; 793 ViewOpts.ShowExpandedRegions = ShowExpansions; 794 ViewOpts.ShowFunctionInstantiations = ShowInstantiations; 795 ViewOpts.ShowOutputDirectory = ShowOutputDirectory; 796 ViewOpts.TabSize = TabSize; 797 ViewOpts.ProjectTitle = ProjectTitle; 798 799 if (ViewOpts.hasOutputDirectory()) { 800 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) { 801 error("Could not create output directory!", E.message()); 802 return 1; 803 } 804 } 805 806 sys::fs::file_status Status; 807 if (sys::fs::status(PGOFilename, Status)) { 808 error("profdata file error: can not get the file status. \n"); 809 return 1; 810 } 811 812 auto ModifiedTime = Status.getLastModificationTime(); 813 std::string ModifiedTimeStr = to_string(ModifiedTime); 814 size_t found = ModifiedTimeStr.rfind(':'); 815 ViewOpts.CreatedTimeStr = (found != std::string::npos) 816 ? "Created: " + ModifiedTimeStr.substr(0, found) 817 : "Created: " + ModifiedTimeStr; 818 819 auto Coverage = load(); 820 if (!Coverage) 821 return 1; 822 823 auto Printer = CoveragePrinter::create(ViewOpts); 824 825 if (!Filters.empty()) { 826 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true); 827 if (Error E = OSOrErr.takeError()) { 828 error("Could not create view file!", toString(std::move(E))); 829 return 1; 830 } 831 auto OS = std::move(OSOrErr.get()); 832 833 // Show functions. 834 for (const auto &Function : Coverage->getCoveredFunctions()) { 835 if (!Filters.matches(Function)) 836 continue; 837 838 auto mainView = createFunctionView(Function, *Coverage); 839 if (!mainView) { 840 warning("Could not read coverage for '" + Function.Name + "'."); 841 continue; 842 } 843 844 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true); 845 } 846 847 Printer->closeViewFile(std::move(OS)); 848 return 0; 849 } 850 851 // Show files 852 bool ShowFilenames = 853 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() || 854 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML); 855 856 if (SourceFiles.empty()) 857 // Get the source files from the function coverage mapping. 858 for (StringRef Filename : Coverage->getUniqueSourceFiles()) 859 SourceFiles.push_back(Filename); 860 861 // Create an index out of the source files. 862 if (ViewOpts.hasOutputDirectory()) { 863 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) { 864 error("Could not create index file!", toString(std::move(E))); 865 return 1; 866 } 867 } 868 869 // If NumThreads is not specified, auto-detect a good default. 870 if (NumThreads == 0) 871 NumThreads = 872 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(), 873 unsigned(SourceFiles.size()))); 874 875 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) { 876 for (const std::string &SourceFile : SourceFiles) 877 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(), 878 ShowFilenames); 879 } else { 880 // In -output-dir mode, it's safe to use multiple threads to print files. 881 ThreadPool Pool(NumThreads); 882 for (const std::string &SourceFile : SourceFiles) 883 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile, 884 Coverage.get(), Printer.get(), ShowFilenames); 885 Pool.wait(); 886 } 887 888 return 0; 889 } 890 891 int CodeCoverageTool::report(int argc, const char **argv, 892 CommandLineParserType commandLineParser) { 893 cl::opt<bool> ShowFunctionSummaries( 894 "show-functions", cl::Optional, cl::init(false), 895 cl::desc("Show coverage summaries for each function")); 896 897 auto Err = commandLineParser(argc, argv); 898 if (Err) 899 return Err; 900 901 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) { 902 error("HTML output for summary reports is not yet supported."); 903 return 1; 904 } 905 906 auto Coverage = load(); 907 if (!Coverage) 908 return 1; 909 910 CoverageReport Report(ViewOpts, *Coverage.get()); 911 if (!ShowFunctionSummaries) 912 Report.renderFileReports(llvm::outs()); 913 else 914 Report.renderFunctionReports(SourceFiles, DC, llvm::outs()); 915 return 0; 916 } 917 918 int CodeCoverageTool::export_(int argc, const char **argv, 919 CommandLineParserType commandLineParser) { 920 921 auto Err = commandLineParser(argc, argv); 922 if (Err) 923 return Err; 924 925 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) { 926 error("Coverage data can only be exported as textual JSON."); 927 return 1; 928 } 929 930 auto Coverage = load(); 931 if (!Coverage) { 932 error("Could not load coverage information"); 933 return 1; 934 } 935 936 exportCoverageDataToJson(*Coverage.get(), ViewOpts, outs()); 937 938 return 0; 939 } 940 941 int showMain(int argc, const char *argv[]) { 942 CodeCoverageTool Tool; 943 return Tool.run(CodeCoverageTool::Show, argc, argv); 944 } 945 946 int reportMain(int argc, const char *argv[]) { 947 CodeCoverageTool Tool; 948 return Tool.run(CodeCoverageTool::Report, argc, argv); 949 } 950 951 int exportMain(int argc, const char *argv[]) { 952 CodeCoverageTool Tool; 953 return Tool.run(CodeCoverageTool::Export, argc, argv); 954 } 955