blob: c2989f43963e0244b0aa5d7bbc69370b3106e351 [file] [log] [blame]
Alex Lorenze82d89c2014-08-22 22:56:03 +00001//===- 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
Alex Lorenze82d89c2014-08-22 22:56:03 +000016#include "CoverageFilters.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000017#include "CoverageReport.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000018#include "CoverageViewOptions.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000019#include "RenderingSupport.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "SourceCoverageView.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000021#include "llvm/ADT/SmallString.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000022#include "llvm/ADT/StringRef.h"
Justin Bogner43795352015-03-11 02:30:51 +000023#include "llvm/ADT/Triple.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000024#include "llvm/ProfileData/Coverage/CoverageMapping.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000025#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileSystem.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000028#include "llvm/Support/Format.h"
29#include "llvm/Support/Path.h"
Justin Bognercfb53e42015-03-19 00:02:23 +000030#include "llvm/Support/Process.h"
Vedant Kumar86b2ac632016-07-13 21:38:36 +000031#include "llvm/Support/ThreadPool.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000032#include <functional>
Justin Bognere53be062014-09-09 05:32:18 +000033#include <system_error>
Alex Lorenze82d89c2014-08-22 22:56:03 +000034
35using namespace llvm;
36using namespace coverage;
37
38namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000039/// \brief The implementation of the coverage tool.
40class CodeCoverageTool {
41public:
42 enum Command {
43 /// \brief The show command.
44 Show,
45 /// \brief The report command.
46 Report
47 };
48
49 /// \brief Print the error message to the error output stream.
50 void error(const Twine &Message, StringRef Whence = "");
51
Vedant Kumar86b2ac632016-07-13 21:38:36 +000052 /// \brief Record (but do not print) an error message in a thread-safe way.
53 void deferError(const Twine &Message, StringRef Whence = "");
54
55 /// \brief Record (but do not print) a warning message in a thread-safe way.
56 void deferWarning(const Twine &Message, StringRef Whence = "");
57
58 /// \brief Print (and then clear) all deferred error and warning messages.
59 void consumeDeferredMessages();
60
Vedant Kumarcef440f2016-06-28 16:12:18 +000061 /// \brief Append a reference to a private copy of \p Path into SourceFiles.
62 void addCollectedPath(const std::string &Path);
63
Alex Lorenze82d89c2014-08-22 22:56:03 +000064 /// \brief Return a memory buffer for the given source file.
65 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
66
Justin Bogner953e2402014-09-20 15:31:56 +000067 /// \brief Create source views for the expansions of the view.
68 void attachExpansionSubViews(SourceCoverageView &View,
69 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000070 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000071
Justin Bogner953e2402014-09-20 15:31:56 +000072 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000073 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000074 createFunctionView(const FunctionRecord &Function,
75 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000076
77 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000078 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000079 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000080
Vedant Kumarf681e2e2016-07-15 01:19:33 +000081 /// \brief Load the coverage mapping data. Return nullptr if an error occured.
Justin Bogner953e2402014-09-20 15:31:56 +000082 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000083
84 int run(Command Cmd, int argc, const char **argv);
85
Benjamin Kramerc321e532016-06-08 19:09:22 +000086 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +000087
88 int show(int argc, const char **argv,
89 CommandLineParserType commandLineParser);
90
91 int report(int argc, const char **argv,
92 CommandLineParserType commandLineParser);
93
Justin Bognerf6c50552014-10-30 20:51:24 +000094 std::string ObjectFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +000095 CoverageViewOptions ViewOpts;
Justin Bogner953e2402014-09-20 15:31:56 +000096 std::string PGOFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +000097 CoverageFiltersMatchAll Filters;
Vedant Kumarcef440f2016-06-28 16:12:18 +000098 std::vector<StringRef> SourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +000099 bool CompareFilenamesOnly;
Justin Bogner116c1662014-09-19 08:13:12 +0000100 StringMap<std::string> RemappedFilenames;
Frederic Rissebc162a2015-06-22 21:33:24 +0000101 std::string CoverageArch;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000102
103private:
104 std::vector<std::string> CollectedPaths;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000105
106 std::mutex DeferredMessagesLock;
107 std::vector<std::string> DeferredMessages;
108
109 std::mutex LoadedSourceFilesLock;
110 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
111 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000112};
113}
114
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000115static std::string getErrorString(const Twine &Message, StringRef Whence,
116 bool Warning) {
117 std::string Str = (Warning ? "warning" : "error");
118 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000119 if (!Whence.empty())
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000120 Str += Whence;
121 Str += Message.str() + "\n";
122 return Str;
123}
124
125void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
126 errs() << getErrorString(Message, Whence, false);
127}
128
129void CodeCoverageTool::deferError(const Twine &Message, StringRef Whence) {
130 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
131 DeferredMessages.emplace_back(getErrorString(Message, Whence, false));
132}
133
134void CodeCoverageTool::deferWarning(const Twine &Message, StringRef Whence) {
135 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
136 DeferredMessages.emplace_back(getErrorString(Message, Whence, true));
137}
138
139void CodeCoverageTool::consumeDeferredMessages() {
140 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
141 for (const std::string &Message : DeferredMessages)
142 ViewOpts.colored_ostream(errs(), raw_ostream::RED) << Message;
143 DeferredMessages.clear();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000144}
145
Vedant Kumarcef440f2016-06-28 16:12:18 +0000146void CodeCoverageTool::addCollectedPath(const std::string &Path) {
147 CollectedPaths.push_back(Path);
148 SourceFiles.emplace_back(CollectedPaths.back());
149}
150
Alex Lorenze82d89c2014-08-22 22:56:03 +0000151ErrorOr<const MemoryBuffer &>
152CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000153 // If we've remapped filenames, look up the real location for this file.
154 if (!RemappedFilenames.empty()) {
155 auto Loc = RemappedFilenames.find(SourceFile);
156 if (Loc != RemappedFilenames.end())
157 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000158 }
Justin Bogner116c1662014-09-19 08:13:12 +0000159 for (const auto &Files : LoadedSourceFiles)
160 if (sys::fs::equivalent(SourceFile, Files.first))
161 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000162 auto Buffer = MemoryBuffer::getFile(SourceFile);
163 if (auto EC = Buffer.getError()) {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000164 deferError(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000165 return EC;
166 }
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000167 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000168 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000169 return *LoadedSourceFiles.back().second;
170}
171
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000172void CodeCoverageTool::attachExpansionSubViews(
173 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
174 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000175 if (!ViewOpts.ShowExpandedRegions)
176 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000177 for (const auto &Expansion : Expansions) {
178 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
179 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000180 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000181 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
182 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000183 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000184
185 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000186 auto SubView =
187 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
188 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000189 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
190 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000191 }
192}
193
Justin Bogner5a6edad2014-09-19 19:07:17 +0000194std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000195CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000196 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000197 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
198 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000199 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000200 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000201 if (!SourceBuffer)
202 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000203
204 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000205 auto View = SourceCoverageView::create(Function.Name, SourceBuffer.get(),
206 ViewOpts, std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000207 attachExpansionSubViews(*View, Expansions, Coverage);
208
209 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000210}
211
Justin Bogner953e2402014-09-20 15:31:56 +0000212std::unique_ptr<SourceCoverageView>
213CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000214 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000215 auto SourceBuffer = getSourceFile(SourceFile);
216 if (!SourceBuffer)
217 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000218 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
219 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000220 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000221
222 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000223 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
224 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000225 attachExpansionSubViews(*View, Expansions, Coverage);
226
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000227 for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000228 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
229 auto SubViewExpansions = SubViewCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000230 auto SubView =
231 SourceCoverageView::create(Function->Name, SourceBuffer.get(), ViewOpts,
232 std::move(SubViewCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000233 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
234
235 if (SubView) {
Justin Bogner5e1400a2014-09-17 05:33:20 +0000236 unsigned FileID = Function->CountedRegions.front().FileID;
237 unsigned Line = 0;
238 for (const auto &CR : Function->CountedRegions)
239 if (CR.FileID == FileID)
240 Line = std::max(CR.LineEnd, Line);
Justin Bogner953e2402014-09-20 15:31:56 +0000241 View->addInstantiation(Function->Name, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000242 }
243 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000244 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000245}
246
Justin Bogner65337d12015-05-04 04:09:38 +0000247static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
248 sys::fs::file_status Status;
249 if (sys::fs::status(LHS, Status))
250 return false;
251 auto LHSTime = Status.getLastModificationTime();
252 if (sys::fs::status(RHS, Status))
253 return false;
254 auto RHSTime = Status.getLastModificationTime();
255 return LHSTime > RHSTime;
256}
257
Justin Bogner953e2402014-09-20 15:31:56 +0000258std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Justin Bogner65337d12015-05-04 04:09:38 +0000259 if (modifiedTimeGT(ObjectFilename, PGOFilename))
260 errs() << "warning: profile data may be out of date - object is newer\n";
Justin Bogner43795352015-03-11 02:30:51 +0000261 auto CoverageOrErr = CoverageMapping::load(ObjectFilename, PGOFilename,
262 CoverageArch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000263 if (Error E = CoverageOrErr.takeError()) {
Justin Bogner953e2402014-09-20 15:31:56 +0000264 colored_ostream(errs(), raw_ostream::RED)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000265 << "error: Failed to load coverage: " << toString(std::move(E)) << "\n";
Justin Bogner953e2402014-09-20 15:31:56 +0000266 return nullptr;
267 }
268 auto Coverage = std::move(CoverageOrErr.get());
269 unsigned Mismatched = Coverage->getMismatchedCount();
270 if (Mismatched) {
271 colored_ostream(errs(), raw_ostream::RED)
272 << "warning: " << Mismatched << " functions have mismatched data. ";
273 errs() << "\n";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000274 }
Justin Bogner116c1662014-09-19 08:13:12 +0000275
276 if (CompareFilenamesOnly) {
Justin Bogner953e2402014-09-20 15:31:56 +0000277 auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
Justin Bogner116c1662014-09-19 08:13:12 +0000278 for (auto &SF : SourceFiles) {
279 StringRef SFBase = sys::path::filename(SF);
280 for (const auto &CF : CoveredFiles)
281 if (SFBase == sys::path::filename(CF)) {
282 RemappedFilenames[CF] = SF;
283 SF = CF;
284 break;
285 }
286 }
287 }
288
Justin Bogner953e2402014-09-20 15:31:56 +0000289 return Coverage;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000290}
291
292int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Justin Bognerf6c50552014-10-30 20:51:24 +0000293 cl::opt<std::string, true> ObjectFilename(
294 cl::Positional, cl::Required, cl::location(this->ObjectFilename),
295 cl::desc("Covered executable or object file."));
296
Alex Lorenze82d89c2014-08-22 22:56:03 +0000297 cl::list<std::string> InputSourceFiles(
298 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
299
Justin Bogner953e2402014-09-20 15:31:56 +0000300 cl::opt<std::string, true> PGOFilename(
301 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000302 cl::desc(
303 "File with the profile data obtained after an instrumented run"));
304
Justin Bogner43795352015-03-11 02:30:51 +0000305 cl::opt<std::string> Arch(
306 "arch", cl::desc("architecture of the coverage mapping binary"));
307
Alex Lorenze82d89c2014-08-22 22:56:03 +0000308 cl::opt<bool> DebugDump("dump", cl::Optional,
309 cl::desc("Show internal debug dump"));
310
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000311 cl::opt<CoverageViewOptions::OutputFormat> Format(
312 "format", cl::desc("Output format for line-based coverage reports"),
313 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
314 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000315 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
316 "HTML output"),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000317 clEnumValEnd),
318 cl::init(CoverageViewOptions::OutputFormat::Text));
319
Alex Lorenze82d89c2014-08-22 22:56:03 +0000320 cl::opt<bool> FilenameEquivalence(
321 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000322 cl::desc("Treat source files as equivalent to paths in the coverage data "
323 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000324
325 cl::OptionCategory FilteringCategory("Function filtering options");
326
327 cl::list<std::string> NameFilters(
328 "name", cl::Optional,
329 cl::desc("Show code coverage only for functions with the given name"),
330 cl::ZeroOrMore, cl::cat(FilteringCategory));
331
332 cl::list<std::string> NameRegexFilters(
333 "name-regex", cl::Optional,
334 cl::desc("Show code coverage only for functions that match the given "
335 "regular expression"),
336 cl::ZeroOrMore, cl::cat(FilteringCategory));
337
338 cl::opt<double> RegionCoverageLtFilter(
339 "region-coverage-lt", cl::Optional,
340 cl::desc("Show code coverage only for functions with region coverage "
341 "less than the given threshold"),
342 cl::cat(FilteringCategory));
343
344 cl::opt<double> RegionCoverageGtFilter(
345 "region-coverage-gt", cl::Optional,
346 cl::desc("Show code coverage only for functions with region coverage "
347 "greater than the given threshold"),
348 cl::cat(FilteringCategory));
349
350 cl::opt<double> LineCoverageLtFilter(
351 "line-coverage-lt", cl::Optional,
352 cl::desc("Show code coverage only for functions with line coverage less "
353 "than the given threshold"),
354 cl::cat(FilteringCategory));
355
356 cl::opt<double> LineCoverageGtFilter(
357 "line-coverage-gt", cl::Optional,
358 cl::desc("Show code coverage only for functions with line coverage "
359 "greater than the given threshold"),
360 cl::cat(FilteringCategory));
361
Justin Bogner9deb1d42015-03-19 04:45:16 +0000362 cl::opt<cl::boolOrDefault> UseColor(
363 "use-color", cl::desc("Emit colored output (default=autodetect)"),
364 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000365
Alex Lorenze82d89c2014-08-22 22:56:03 +0000366 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
367 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
368 ViewOpts.Debug = DebugDump;
369 CompareFilenamesOnly = FilenameEquivalence;
370
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000371 ViewOpts.Format = Format;
372 switch (ViewOpts.Format) {
373 case CoverageViewOptions::OutputFormat::Text:
374 ViewOpts.Colors = UseColor == cl::BOU_UNSET
375 ? sys::Process::StandardOutHasColors()
376 : UseColor == cl::BOU_TRUE;
377 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000378 case CoverageViewOptions::OutputFormat::HTML:
379 if (UseColor == cl::BOU_FALSE)
380 error("Color output cannot be disabled when generating html.");
381 ViewOpts.Colors = true;
382 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000383 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000384
Alex Lorenze82d89c2014-08-22 22:56:03 +0000385 // Create the function filters
386 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
387 auto NameFilterer = new CoverageFilters;
388 for (const auto &Name : NameFilters)
389 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
390 for (const auto &Regex : NameRegexFilters)
391 NameFilterer->push_back(
392 llvm::make_unique<NameRegexCoverageFilter>(Regex));
393 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
394 }
395 if (RegionCoverageLtFilter.getNumOccurrences() ||
396 RegionCoverageGtFilter.getNumOccurrences() ||
397 LineCoverageLtFilter.getNumOccurrences() ||
398 LineCoverageGtFilter.getNumOccurrences()) {
399 auto StatFilterer = new CoverageFilters;
400 if (RegionCoverageLtFilter.getNumOccurrences())
401 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
402 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
403 if (RegionCoverageGtFilter.getNumOccurrences())
404 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
405 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
406 if (LineCoverageLtFilter.getNumOccurrences())
407 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
408 LineCoverageFilter::LessThan, LineCoverageLtFilter));
409 if (LineCoverageGtFilter.getNumOccurrences())
410 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
411 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
412 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
413 }
414
Frederic Rissebc162a2015-06-22 21:33:24 +0000415 if (!Arch.empty() &&
416 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
417 errs() << "error: Unknown architecture: " << Arch << "\n";
418 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000419 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000420 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000421
Justin Bogner116c1662014-09-19 08:13:12 +0000422 for (const auto &File : InputSourceFiles) {
423 SmallString<128> Path(File);
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000424 if (!CompareFilenamesOnly)
425 if (std::error_code EC = sys::fs::make_absolute(Path)) {
426 errs() << "error: " << File << ": " << EC.message();
427 return 1;
428 }
Vedant Kumarcef440f2016-06-28 16:12:18 +0000429 addCollectedPath(Path.str());
Justin Bogner116c1662014-09-19 08:13:12 +0000430 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000431 return 0;
432 };
433
Alex Lorenze82d89c2014-08-22 22:56:03 +0000434 switch (Cmd) {
435 case Show:
436 return show(argc, argv, commandLineParser);
437 case Report:
438 return report(argc, argv, commandLineParser);
439 }
440 return 0;
441}
442
443int CodeCoverageTool::show(int argc, const char **argv,
444 CommandLineParserType commandLineParser) {
445
446 cl::OptionCategory ViewCategory("Viewing options");
447
448 cl::opt<bool> ShowLineExecutionCounts(
449 "show-line-counts", cl::Optional,
450 cl::desc("Show the execution counts for each line"), cl::init(true),
451 cl::cat(ViewCategory));
452
453 cl::opt<bool> ShowRegions(
454 "show-regions", cl::Optional,
455 cl::desc("Show the execution counts for each region"),
456 cl::cat(ViewCategory));
457
458 cl::opt<bool> ShowBestLineRegionsCounts(
459 "show-line-counts-or-regions", cl::Optional,
460 cl::desc("Show the execution counts for each line, or the execution "
461 "counts for each region on lines that have multiple regions"),
462 cl::cat(ViewCategory));
463
464 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
465 cl::desc("Show expanded source regions"),
466 cl::cat(ViewCategory));
467
468 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
469 cl::desc("Show function instantiations"),
470 cl::cat(ViewCategory));
471
Vedant Kumar7937ef32016-06-28 02:09:39 +0000472 cl::opt<std::string> ShowOutputDirectory(
473 "output-dir", cl::init(""),
474 cl::desc("Directory in which coverage information is written out"));
475 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
476 cl::aliasopt(ShowOutputDirectory));
477
Alex Lorenze82d89c2014-08-22 22:56:03 +0000478 auto Err = commandLineParser(argc, argv);
479 if (Err)
480 return Err;
481
Alex Lorenze82d89c2014-08-22 22:56:03 +0000482 ViewOpts.ShowLineNumbers = true;
483 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
484 !ShowRegions || ShowBestLineRegionsCounts;
485 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
486 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
487 ViewOpts.ShowExpandedRegions = ShowExpansions;
488 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000489 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
490
Vedant Kumar64d8a022016-06-28 16:12:20 +0000491 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000492 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
493 error("Could not create output directory!", E.message());
494 return 1;
495 }
496 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000497
Justin Bogner953e2402014-09-20 15:31:56 +0000498 auto Coverage = load();
499 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000500 return 1;
501
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000502 auto Printer = CoveragePrinter::create(ViewOpts);
503
Alex Lorenze82d89c2014-08-22 22:56:03 +0000504 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000505 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
506 if (Error E = OSOrErr.takeError()) {
507 error(toString(std::move(E)));
508 return 1;
509 }
510 auto OS = std::move(OSOrErr.get());
511
512 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000513 for (const auto &Function : Coverage->getCoveredFunctions()) {
514 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000515 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000516
517 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000518 if (!mainView) {
Vedant Kumar2c96e882016-06-24 02:33:01 +0000519 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
520 << "warning: Could not read coverage for '" << Function.Name << "'."
521 << "\n";
Justin Bogner5a6edad2014-09-19 19:07:17 +0000522 continue;
523 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000524
Vedant Kumar7937ef32016-06-28 02:09:39 +0000525 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000526 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000527
528 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000529 return 0;
530 }
531
532 // Show files
533 bool ShowFilenames = SourceFiles.size() != 1;
534
Justin Bogner116c1662014-09-19 08:13:12 +0000535 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000536 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000537 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000538 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000539
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000540 // Create an index out of the source files.
541 if (ViewOpts.hasOutputDirectory()) {
542 if (Error E = Printer->createIndexFile(SourceFiles)) {
543 error(toString(std::move(E)));
544 return 1;
545 }
546 }
547
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000548 // In -output-dir mode, it's safe to use multiple threads to print files.
549 unsigned ThreadCount = 1;
550 if (ViewOpts.hasOutputDirectory())
551 ThreadCount = std::thread::hardware_concurrency();
552 ThreadPool Pool(ThreadCount);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000553
Vedant Kumar84c452d2016-07-15 01:19:35 +0000554 for (StringRef SourceFile : SourceFiles) {
555 Pool.async([this, SourceFile, &Coverage, &Printer, ShowFilenames] {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000556 auto View = createSourceFileView(SourceFile, *Coverage);
557 if (!View) {
558 deferWarning("The file '" + SourceFile.str() + "' isn't covered.");
559 return;
560 }
561
562 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
563 if (Error E = OSOrErr.takeError()) {
564 deferError(toString(std::move(E)));
565 return;
566 }
567 auto OS = std::move(OSOrErr.get());
568
569 View->print(*OS.get(), /*Wholefile=*/true,
570 /*ShowSourceName=*/ShowFilenames);
571 Printer->closeViewFile(std::move(OS));
572 });
Alex Lorenze82d89c2014-08-22 22:56:03 +0000573 }
574
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000575 Pool.wait();
576
577 consumeDeferredMessages();
578
Alex Lorenze82d89c2014-08-22 22:56:03 +0000579 return 0;
580}
581
582int CodeCoverageTool::report(int argc, const char **argv,
583 CommandLineParserType commandLineParser) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000584 auto Err = commandLineParser(argc, argv);
585 if (Err)
586 return Err;
587
Vedant Kumar4c010922016-07-06 21:44:05 +0000588 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
589 error("HTML output for summary reports is not yet supported.");
590
Justin Bogner953e2402014-09-20 15:31:56 +0000591 auto Coverage = load();
592 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000593 return 1;
594
Justin Bognerf91bc6c2015-02-14 02:01:24 +0000595 CoverageReport Report(ViewOpts, std::move(Coverage));
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000596 if (SourceFiles.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000597 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000598 else
599 Report.renderFunctionReports(SourceFiles, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000600 return 0;
601}
602
Justin Bognerd249a3b2014-10-30 20:57:49 +0000603int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000604 CodeCoverageTool Tool;
605 return Tool.run(CodeCoverageTool::Show, argc, argv);
606}
607
Justin Bognerd249a3b2014-10-30 20:57:49 +0000608int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000609 CodeCoverageTool Tool;
610 return Tool.run(CodeCoverageTool::Report, argc, argv);
611}