1 //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The 'CodeCoverageTool' class implements a command line tool to analyze and
11 // report coverage information using the profiling instrumentation and code
14 //===----------------------------------------------------------------------===//
16 #include "RenderingSupport.h"
17 #include "CoverageFilters.h"
18 #include "CoverageReport.h"
19 #include "CoverageViewOptions.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/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/ManagedStatic.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/Signals.h"
35 #include <system_error>
38 using namespace coverage;
41 /// \brief The implementation of the coverage tool.
42 class CodeCoverageTool {
45 /// \brief The show command.
47 /// \brief The report command.
51 /// \brief Print the error message to the error output stream.
52 void error(const Twine &Message, StringRef Whence = "");
54 /// \brief Return a memory buffer for the given source file.
55 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
57 /// \brief Create source views for the expansions of the view.
58 void attachExpansionSubViews(SourceCoverageView &View,
59 ArrayRef<ExpansionRecord> Expansions,
60 CoverageMapping &Coverage);
62 /// \brief Create the source view of a particular function.
63 std::unique_ptr<SourceCoverageView>
64 createFunctionView(const FunctionRecord &Function, CoverageMapping &Coverage);
66 /// \brief Create the main source view of a particular source file.
67 std::unique_ptr<SourceCoverageView>
68 createSourceFileView(StringRef SourceFile, CoverageMapping &Coverage);
70 /// \brief Load the coverage mapping data. Return true if an error occured.
71 std::unique_ptr<CoverageMapping> load();
73 int run(Command Cmd, int argc, const char **argv);
75 typedef std::function<int(int, const char **)> CommandLineParserType;
77 int show(int argc, const char **argv,
78 CommandLineParserType commandLineParser);
80 int report(int argc, const char **argv,
81 CommandLineParserType commandLineParser);
83 std::string ObjectFilename;
84 CoverageViewOptions ViewOpts;
85 std::string PGOFilename;
86 CoverageFiltersMatchAll Filters;
87 std::vector<std::string> SourceFiles;
88 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
90 bool CompareFilenamesOnly;
91 StringMap<std::string> RemappedFilenames;
92 llvm::Triple::ArchType CoverageArch;
96 void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
99 errs() << Whence << ": ";
100 errs() << Message << "\n";
103 ErrorOr<const MemoryBuffer &>
104 CodeCoverageTool::getSourceFile(StringRef SourceFile) {
105 // If we've remapped filenames, look up the real location for this file.
106 if (!RemappedFilenames.empty()) {
107 auto Loc = RemappedFilenames.find(SourceFile);
108 if (Loc != RemappedFilenames.end())
109 SourceFile = Loc->second;
111 for (const auto &Files : LoadedSourceFiles)
112 if (sys::fs::equivalent(SourceFile, Files.first))
113 return *Files.second;
114 auto Buffer = MemoryBuffer::getFile(SourceFile);
115 if (auto EC = Buffer.getError()) {
116 error(EC.message(), SourceFile);
119 LoadedSourceFiles.push_back(
120 std::make_pair(SourceFile, std::move(Buffer.get())));
121 return *LoadedSourceFiles.back().second;
125 CodeCoverageTool::attachExpansionSubViews(SourceCoverageView &View,
126 ArrayRef<ExpansionRecord> Expansions,
127 CoverageMapping &Coverage) {
128 if (!ViewOpts.ShowExpandedRegions)
130 for (const auto &Expansion : Expansions) {
131 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
132 if (ExpansionCoverage.empty())
134 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
138 auto SubViewExpansions = ExpansionCoverage.getExpansions();
139 auto SubView = llvm::make_unique<SourceCoverageView>(
140 SourceBuffer.get(), ViewOpts, std::move(ExpansionCoverage));
141 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
142 View.addExpansion(Expansion.Region, std::move(SubView));
146 std::unique_ptr<SourceCoverageView>
147 CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
148 CoverageMapping &Coverage) {
149 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
150 if (FunctionCoverage.empty())
152 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
156 auto Expansions = FunctionCoverage.getExpansions();
157 auto View = llvm::make_unique<SourceCoverageView>(
158 SourceBuffer.get(), ViewOpts, std::move(FunctionCoverage));
159 attachExpansionSubViews(*View, Expansions, Coverage);
164 std::unique_ptr<SourceCoverageView>
165 CodeCoverageTool::createSourceFileView(StringRef SourceFile,
166 CoverageMapping &Coverage) {
167 auto SourceBuffer = getSourceFile(SourceFile);
170 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
171 if (FileCoverage.empty())
174 auto Expansions = FileCoverage.getExpansions();
175 auto View = llvm::make_unique<SourceCoverageView>(
176 SourceBuffer.get(), ViewOpts, std::move(FileCoverage));
177 attachExpansionSubViews(*View, Expansions, Coverage);
179 for (auto Function : Coverage.getInstantiations(SourceFile)) {
180 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
181 auto SubViewExpansions = SubViewCoverage.getExpansions();
182 auto SubView = llvm::make_unique<SourceCoverageView>(
183 SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
184 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
187 unsigned FileID = Function->CountedRegions.front().FileID;
189 for (const auto &CR : Function->CountedRegions)
190 if (CR.FileID == FileID)
191 Line = std::max(CR.LineEnd, Line);
192 View->addInstantiation(Function->Name, Line, std::move(SubView));
198 std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
199 auto CoverageOrErr = CoverageMapping::load(ObjectFilename, PGOFilename,
201 if (std::error_code EC = CoverageOrErr.getError()) {
202 colored_ostream(errs(), raw_ostream::RED)
203 << "error: Failed to load coverage: " << EC.message();
207 auto Coverage = std::move(CoverageOrErr.get());
208 unsigned Mismatched = Coverage->getMismatchedCount();
210 colored_ostream(errs(), raw_ostream::RED)
211 << "warning: " << Mismatched << " functions have mismatched data. ";
215 if (CompareFilenamesOnly) {
216 auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
217 for (auto &SF : SourceFiles) {
218 StringRef SFBase = sys::path::filename(SF);
219 for (const auto &CF : CoveredFiles)
220 if (SFBase == sys::path::filename(CF)) {
221 RemappedFilenames[CF] = SF;
232 enum Colors { Auto, Always, Never };
235 int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
236 // Print a stack trace if we signal out.
237 sys::PrintStackTraceOnErrorSignal();
238 PrettyStackTraceProgram X(argc, argv);
239 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
241 cl::opt<std::string, true> ObjectFilename(
242 cl::Positional, cl::Required, cl::location(this->ObjectFilename),
243 cl::desc("Covered executable or object file."));
245 cl::list<std::string> InputSourceFiles(
246 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
248 cl::opt<std::string, true> PGOFilename(
249 "instr-profile", cl::Required, cl::location(this->PGOFilename),
251 "File with the profile data obtained after an instrumented run"));
253 cl::opt<std::string> Arch(
254 "arch", cl::desc("architecture of the coverage mapping binary"));
256 cl::opt<bool> DebugDump("dump", cl::Optional,
257 cl::desc("Show internal debug dump"));
259 cl::opt<bool> FilenameEquivalence(
260 "filename-equivalence", cl::Optional,
261 cl::desc("Treat source files as equivalent to paths in the coverage data "
262 "when the file names match, even if the full paths do not"));
264 cl::OptionCategory FilteringCategory("Function filtering options");
266 cl::list<std::string> NameFilters(
267 "name", cl::Optional,
268 cl::desc("Show code coverage only for functions with the given name"),
269 cl::ZeroOrMore, cl::cat(FilteringCategory));
271 cl::list<std::string> NameRegexFilters(
272 "name-regex", cl::Optional,
273 cl::desc("Show code coverage only for functions that match the given "
274 "regular expression"),
275 cl::ZeroOrMore, cl::cat(FilteringCategory));
277 cl::opt<double> RegionCoverageLtFilter(
278 "region-coverage-lt", cl::Optional,
279 cl::desc("Show code coverage only for functions with region coverage "
280 "less than the given threshold"),
281 cl::cat(FilteringCategory));
283 cl::opt<double> RegionCoverageGtFilter(
284 "region-coverage-gt", cl::Optional,
285 cl::desc("Show code coverage only for functions with region coverage "
286 "greater than the given threshold"),
287 cl::cat(FilteringCategory));
289 cl::opt<double> LineCoverageLtFilter(
290 "line-coverage-lt", cl::Optional,
291 cl::desc("Show code coverage only for functions with line coverage less "
292 "than the given threshold"),
293 cl::cat(FilteringCategory));
295 cl::opt<double> LineCoverageGtFilter(
296 "line-coverage-gt", cl::Optional,
297 cl::desc("Show code coverage only for functions with line coverage "
298 "greater than the given threshold"),
299 cl::cat(FilteringCategory));
301 cl::opt<Colors> Color(
302 "color", cl::desc("Configure color output:"), cl::init(Colors::Auto),
303 cl::values(clEnumValN(Colors::Auto, "auto",
304 "Enable color if stdout seems to support it"),
305 clEnumValN(Colors::Always, "always", "Enable color"),
306 clEnumValN(Colors::Never, "never", "Disable color"),
309 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
310 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
311 ViewOpts.Debug = DebugDump;
312 CompareFilenamesOnly = FilenameEquivalence;
315 Color == Colors::Always ||
316 (Color == Colors::Auto && sys::Process::StandardOutHasColors());
318 // Create the function filters
319 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
320 auto NameFilterer = new CoverageFilters;
321 for (const auto &Name : NameFilters)
322 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
323 for (const auto &Regex : NameRegexFilters)
324 NameFilterer->push_back(
325 llvm::make_unique<NameRegexCoverageFilter>(Regex));
326 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
328 if (RegionCoverageLtFilter.getNumOccurrences() ||
329 RegionCoverageGtFilter.getNumOccurrences() ||
330 LineCoverageLtFilter.getNumOccurrences() ||
331 LineCoverageGtFilter.getNumOccurrences()) {
332 auto StatFilterer = new CoverageFilters;
333 if (RegionCoverageLtFilter.getNumOccurrences())
334 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
335 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
336 if (RegionCoverageGtFilter.getNumOccurrences())
337 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
338 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
339 if (LineCoverageLtFilter.getNumOccurrences())
340 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
341 LineCoverageFilter::LessThan, LineCoverageLtFilter));
342 if (LineCoverageGtFilter.getNumOccurrences())
343 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
344 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
345 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
349 CoverageArch = llvm::Triple::ArchType::UnknownArch;
351 CoverageArch = Triple(Arch).getArch();
352 if (CoverageArch == llvm::Triple::ArchType::UnknownArch) {
353 errs() << "error: Unknown architecture: " << Arch << "\n";
358 for (const auto &File : InputSourceFiles) {
359 SmallString<128> Path(File);
360 if (!CompareFilenamesOnly)
361 if (std::error_code EC = sys::fs::make_absolute(Path)) {
362 errs() << "error: " << File << ": " << EC.message();
365 SourceFiles.push_back(Path.str());
372 return show(argc, argv, commandLineParser);
374 return report(argc, argv, commandLineParser);
379 int CodeCoverageTool::show(int argc, const char **argv,
380 CommandLineParserType commandLineParser) {
382 cl::OptionCategory ViewCategory("Viewing options");
384 cl::opt<bool> ShowLineExecutionCounts(
385 "show-line-counts", cl::Optional,
386 cl::desc("Show the execution counts for each line"), cl::init(true),
387 cl::cat(ViewCategory));
389 cl::opt<bool> ShowRegions(
390 "show-regions", cl::Optional,
391 cl::desc("Show the execution counts for each region"),
392 cl::cat(ViewCategory));
394 cl::opt<bool> ShowBestLineRegionsCounts(
395 "show-line-counts-or-regions", cl::Optional,
396 cl::desc("Show the execution counts for each line, or the execution "
397 "counts for each region on lines that have multiple regions"),
398 cl::cat(ViewCategory));
400 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
401 cl::desc("Show expanded source regions"),
402 cl::cat(ViewCategory));
404 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
405 cl::desc("Show function instantiations"),
406 cl::cat(ViewCategory));
408 auto Err = commandLineParser(argc, argv);
412 ViewOpts.ShowLineNumbers = true;
413 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
414 !ShowRegions || ShowBestLineRegionsCounts;
415 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
416 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
417 ViewOpts.ShowExpandedRegions = ShowExpansions;
418 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
420 auto Coverage = load();
424 if (!Filters.empty()) {
426 for (const auto &Function : Coverage->getCoveredFunctions()) {
427 if (!Filters.matches(Function))
430 auto mainView = createFunctionView(Function, *Coverage);
432 ViewOpts.colored_ostream(outs(), raw_ostream::RED)
433 << "warning: Could not read coverage for '" << Function.Name;
437 ViewOpts.colored_ostream(outs(), raw_ostream::CYAN) << Function.Name
440 mainView->render(outs(), /*WholeFile=*/false);
447 bool ShowFilenames = SourceFiles.size() != 1;
449 if (SourceFiles.empty())
450 // Get the source files from the function coverage mapping
451 for (StringRef Filename : Coverage->getUniqueSourceFiles())
452 SourceFiles.push_back(Filename);
454 for (const auto &SourceFile : SourceFiles) {
455 auto mainView = createSourceFileView(SourceFile, *Coverage);
457 ViewOpts.colored_ostream(outs(), raw_ostream::RED)
458 << "warning: The file '" << SourceFile << "' isn't covered.";
464 ViewOpts.colored_ostream(outs(), raw_ostream::CYAN) << SourceFile << ":";
467 mainView->render(outs(), /*Wholefile=*/true);
468 if (SourceFiles.size() > 1)
475 int CodeCoverageTool::report(int argc, const char **argv,
476 CommandLineParserType commandLineParser) {
477 auto Err = commandLineParser(argc, argv);
481 auto Coverage = load();
485 CoverageReport Report(ViewOpts, std::move(Coverage));
486 if (SourceFiles.empty())
487 Report.renderFileReports(llvm::outs());
489 Report.renderFunctionReports(SourceFiles, llvm::outs());
493 int showMain(int argc, const char *argv[]) {
494 CodeCoverageTool Tool;
495 return Tool.run(CodeCoverageTool::Show, argc, argv);
498 int reportMain(int argc, const char *argv[]) {
499 CodeCoverageTool Tool;
500 return Tool.run(CodeCoverageTool::Report, argc, argv);