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