blob: e9346cd4c5b6da904cae6d0e921ecdd5ba0e3b62 [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"
Vedant Kumar424f51b2016-07-15 22:44:57 +000029#include "llvm/Support/MemoryBuffer.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000030#include "llvm/Support/Path.h"
Justin Bognercfb53e42015-03-19 00:02:23 +000031#include "llvm/Support/Process.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000032#include "llvm/Support/Program.h"
Vedant Kumar86b2ac632016-07-13 21:38:36 +000033#include "llvm/Support/ThreadPool.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000034#include "llvm/Support/ToolOutputFile.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000035#include <functional>
Justin Bognere53be062014-09-09 05:32:18 +000036#include <system_error>
Alex Lorenze82d89c2014-08-22 22:56:03 +000037
38using namespace llvm;
39using namespace coverage;
40
41namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000042/// \brief The implementation of the coverage tool.
43class CodeCoverageTool {
44public:
45 enum Command {
46 /// \brief The show command.
47 Show,
48 /// \brief The report command.
49 Report
50 };
51
52 /// \brief Print the error message to the error output stream.
53 void error(const Twine &Message, StringRef Whence = "");
54
Vedant Kumar86b2ac632016-07-13 21:38:36 +000055 /// \brief Record (but do not print) an error message in a thread-safe way.
56 void deferError(const Twine &Message, StringRef Whence = "");
57
58 /// \brief Record (but do not print) a warning message in a thread-safe way.
59 void deferWarning(const Twine &Message, StringRef Whence = "");
60
61 /// \brief Print (and then clear) all deferred error and warning messages.
62 void consumeDeferredMessages();
63
Vedant Kumarcef440f2016-06-28 16:12:18 +000064 /// \brief Append a reference to a private copy of \p Path into SourceFiles.
65 void addCollectedPath(const std::string &Path);
66
Alex Lorenze82d89c2014-08-22 22:56:03 +000067 /// \brief Return a memory buffer for the given source file.
68 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
69
Justin Bogner953e2402014-09-20 15:31:56 +000070 /// \brief Create source views for the expansions of the view.
71 void attachExpansionSubViews(SourceCoverageView &View,
72 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000073 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000074
Justin Bogner953e2402014-09-20 15:31:56 +000075 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000076 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000077 createFunctionView(const FunctionRecord &Function,
78 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000079
80 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000081 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000082 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000083
Vedant Kumarf681e2e2016-07-15 01:19:33 +000084 /// \brief Load the coverage mapping data. Return nullptr if an error occured.
Justin Bogner953e2402014-09-20 15:31:56 +000085 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000086
Vedant Kumar424f51b2016-07-15 22:44:57 +000087 /// \brief If a demangler is available, demangle all symbol names.
88 void demangleSymbols(const CoverageMapping &Coverage);
89
90 /// \brief Demangle \p Sym if possible. Otherwise, just return \p Sym.
91 StringRef getSymbolForHumans(StringRef Sym) const;
92
Alex Lorenze82d89c2014-08-22 22:56:03 +000093 int run(Command Cmd, int argc, const char **argv);
94
Benjamin Kramerc321e532016-06-08 19:09:22 +000095 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +000096
97 int show(int argc, const char **argv,
98 CommandLineParserType commandLineParser);
99
100 int report(int argc, const char **argv,
101 CommandLineParserType commandLineParser);
102
Justin Bognerf6c50552014-10-30 20:51:24 +0000103 std::string ObjectFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000104 CoverageViewOptions ViewOpts;
Justin Bogner953e2402014-09-20 15:31:56 +0000105 std::string PGOFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000106 CoverageFiltersMatchAll Filters;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000107 std::vector<StringRef> SourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000108 bool CompareFilenamesOnly;
Justin Bogner116c1662014-09-19 08:13:12 +0000109 StringMap<std::string> RemappedFilenames;
Frederic Rissebc162a2015-06-22 21:33:24 +0000110 std::string CoverageArch;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000111
112private:
Vedant Kumar424f51b2016-07-15 22:44:57 +0000113 /// A cache for demangled symbol names.
114 StringMap<std::string> DemangledNames;
115
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000116 /// File paths (absolute, or otherwise) to input source files.
Vedant Kumarcef440f2016-06-28 16:12:18 +0000117 std::vector<std::string> CollectedPaths;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000118
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000119 /// Errors and warnings which have not been printed.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000120 std::mutex DeferredMessagesLock;
121 std::vector<std::string> DeferredMessages;
122
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000123 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000124 std::mutex LoadedSourceFilesLock;
125 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
126 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000127};
128}
129
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000130static std::string getErrorString(const Twine &Message, StringRef Whence,
131 bool Warning) {
132 std::string Str = (Warning ? "warning" : "error");
133 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000134 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000135 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000136 Str += Message.str() + "\n";
137 return Str;
138}
139
140void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
141 errs() << getErrorString(Message, Whence, false);
142}
143
144void CodeCoverageTool::deferError(const Twine &Message, StringRef Whence) {
145 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
146 DeferredMessages.emplace_back(getErrorString(Message, Whence, false));
147}
148
149void CodeCoverageTool::deferWarning(const Twine &Message, StringRef Whence) {
150 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
151 DeferredMessages.emplace_back(getErrorString(Message, Whence, true));
152}
153
154void CodeCoverageTool::consumeDeferredMessages() {
155 std::unique_lock<std::mutex> Guard{DeferredMessagesLock};
156 for (const std::string &Message : DeferredMessages)
157 ViewOpts.colored_ostream(errs(), raw_ostream::RED) << Message;
158 DeferredMessages.clear();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000159}
160
Vedant Kumarcef440f2016-06-28 16:12:18 +0000161void CodeCoverageTool::addCollectedPath(const std::string &Path) {
162 CollectedPaths.push_back(Path);
163 SourceFiles.emplace_back(CollectedPaths.back());
164}
165
Alex Lorenze82d89c2014-08-22 22:56:03 +0000166ErrorOr<const MemoryBuffer &>
167CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000168 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000169 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000170 if (!RemappedFilenames.empty()) {
171 auto Loc = RemappedFilenames.find(SourceFile);
172 if (Loc != RemappedFilenames.end())
173 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000174 }
Justin Bogner116c1662014-09-19 08:13:12 +0000175 for (const auto &Files : LoadedSourceFiles)
176 if (sys::fs::equivalent(SourceFile, Files.first))
177 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000178 auto Buffer = MemoryBuffer::getFile(SourceFile);
179 if (auto EC = Buffer.getError()) {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000180 deferError(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000181 return EC;
182 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000183 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000184 return *LoadedSourceFiles.back().second;
185}
186
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000187void CodeCoverageTool::attachExpansionSubViews(
188 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
189 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000190 if (!ViewOpts.ShowExpandedRegions)
191 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000192 for (const auto &Expansion : Expansions) {
193 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
194 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000195 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000196 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
197 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000198 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000199
200 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000201 auto SubView =
202 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
203 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000204 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
205 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000206 }
207}
208
Justin Bogner5a6edad2014-09-19 19:07:17 +0000209std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000210CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000211 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000212 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
213 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000214 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000215 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000216 if (!SourceBuffer)
217 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000218
219 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000220 auto View = SourceCoverageView::create(getSymbolForHumans(Function.Name),
221 SourceBuffer.get(), ViewOpts,
222 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000223 attachExpansionSubViews(*View, Expansions, Coverage);
224
225 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000226}
227
Justin Bogner953e2402014-09-20 15:31:56 +0000228std::unique_ptr<SourceCoverageView>
229CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000230 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000231 auto SourceBuffer = getSourceFile(SourceFile);
232 if (!SourceBuffer)
233 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000234 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
235 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000236 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000237
238 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000239 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
240 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000241 attachExpansionSubViews(*View, Expansions, Coverage);
242
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000243 for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000244 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
245 auto SubViewExpansions = SubViewCoverage.getExpansions();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000246 auto SubView = SourceCoverageView::create(
247 getSymbolForHumans(Function->Name), SourceBuffer.get(), ViewOpts,
248 std::move(SubViewCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000249 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
250
251 if (SubView) {
Justin Bogner5e1400a2014-09-17 05:33:20 +0000252 unsigned FileID = Function->CountedRegions.front().FileID;
253 unsigned Line = 0;
254 for (const auto &CR : Function->CountedRegions)
255 if (CR.FileID == FileID)
256 Line = std::max(CR.LineEnd, Line);
Justin Bogner953e2402014-09-20 15:31:56 +0000257 View->addInstantiation(Function->Name, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000258 }
259 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000260 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000261}
262
Justin Bogner65337d12015-05-04 04:09:38 +0000263static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
264 sys::fs::file_status Status;
265 if (sys::fs::status(LHS, Status))
266 return false;
267 auto LHSTime = Status.getLastModificationTime();
268 if (sys::fs::status(RHS, Status))
269 return false;
270 auto RHSTime = Status.getLastModificationTime();
271 return LHSTime > RHSTime;
272}
273
Justin Bogner953e2402014-09-20 15:31:56 +0000274std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Justin Bogner65337d12015-05-04 04:09:38 +0000275 if (modifiedTimeGT(ObjectFilename, PGOFilename))
276 errs() << "warning: profile data may be out of date - object is newer\n";
Justin Bogner43795352015-03-11 02:30:51 +0000277 auto CoverageOrErr = CoverageMapping::load(ObjectFilename, PGOFilename,
278 CoverageArch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000279 if (Error E = CoverageOrErr.takeError()) {
Justin Bogner953e2402014-09-20 15:31:56 +0000280 colored_ostream(errs(), raw_ostream::RED)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000281 << "error: Failed to load coverage: " << toString(std::move(E)) << "\n";
Justin Bogner953e2402014-09-20 15:31:56 +0000282 return nullptr;
283 }
284 auto Coverage = std::move(CoverageOrErr.get());
285 unsigned Mismatched = Coverage->getMismatchedCount();
286 if (Mismatched) {
287 colored_ostream(errs(), raw_ostream::RED)
288 << "warning: " << Mismatched << " functions have mismatched data. ";
289 errs() << "\n";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000290 }
Justin Bogner116c1662014-09-19 08:13:12 +0000291
292 if (CompareFilenamesOnly) {
Justin Bogner953e2402014-09-20 15:31:56 +0000293 auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
Justin Bogner116c1662014-09-19 08:13:12 +0000294 for (auto &SF : SourceFiles) {
295 StringRef SFBase = sys::path::filename(SF);
296 for (const auto &CF : CoveredFiles)
297 if (SFBase == sys::path::filename(CF)) {
298 RemappedFilenames[CF] = SF;
299 SF = CF;
300 break;
301 }
302 }
303 }
304
Vedant Kumar424f51b2016-07-15 22:44:57 +0000305 demangleSymbols(*Coverage);
306
Justin Bogner953e2402014-09-20 15:31:56 +0000307 return Coverage;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000308}
309
Vedant Kumar424f51b2016-07-15 22:44:57 +0000310void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
311 if (!ViewOpts.hasDemangler())
312 return;
313
314 // Pass function names to the demangler in a temporary file.
315 int InputFD;
316 SmallString<256> InputPath;
317 std::error_code EC =
318 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
319 if (EC) {
320 error(InputPath, EC.message());
321 return;
322 }
323 tool_output_file InputTOF{InputPath, InputFD};
324
325 unsigned NumSymbols = 0;
326 for (const auto &Function : Coverage.getCoveredFunctions()) {
327 InputTOF.os() << Function.Name << '\n';
328 ++NumSymbols;
329 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000330 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000331
332 // Use another temporary file to store the demangler's output.
333 int OutputFD;
334 SmallString<256> OutputPath;
335 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
336 OutputPath);
337 if (EC) {
338 error(OutputPath, EC.message());
339 return;
340 }
341 tool_output_file OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000342 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000343
344 // Invoke the demangler.
345 std::vector<const char *> ArgsV;
346 for (const std::string &Arg : ViewOpts.DemanglerOpts)
347 ArgsV.push_back(Arg.c_str());
348 ArgsV.push_back(nullptr);
349 StringRef InputPathRef{InputPath}, OutputPathRef{OutputPath}, StderrRef;
350 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
351 std::string ErrMsg;
352 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
353 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
354 /*memoryLimit=*/0, &ErrMsg);
355 if (RC) {
356 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
357 return;
358 }
359
360 // Parse the demangler's output.
361 auto BufOrError = MemoryBuffer::getFile(OutputPath);
362 if (!BufOrError) {
363 error(OutputPath, BufOrError.getError().message());
364 return;
365 }
366
367 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
368
369 SmallVector<StringRef, 8> Symbols;
370 StringRef DemanglerData = DemanglerBuf->getBuffer();
371 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
372 /*KeepEmpty=*/false);
373 if (Symbols.size() != NumSymbols) {
374 error("Demangler did not provide expected number of symbols");
375 return;
376 }
377
378 // Cache the demangled names.
379 unsigned I = 0;
380 for (const auto &Function : Coverage.getCoveredFunctions())
381 DemangledNames[Function.Name] = Symbols[I++];
382}
383
384StringRef CodeCoverageTool::getSymbolForHumans(StringRef Sym) const {
385 const auto DemangledName = DemangledNames.find(Sym);
386 if (DemangledName == DemangledNames.end())
387 return Sym;
388 return DemangledName->getValue();
389}
390
Alex Lorenze82d89c2014-08-22 22:56:03 +0000391int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Justin Bognerf6c50552014-10-30 20:51:24 +0000392 cl::opt<std::string, true> ObjectFilename(
393 cl::Positional, cl::Required, cl::location(this->ObjectFilename),
394 cl::desc("Covered executable or object file."));
395
Alex Lorenze82d89c2014-08-22 22:56:03 +0000396 cl::list<std::string> InputSourceFiles(
397 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
398
Justin Bogner953e2402014-09-20 15:31:56 +0000399 cl::opt<std::string, true> PGOFilename(
400 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000401 cl::desc(
402 "File with the profile data obtained after an instrumented run"));
403
Justin Bogner43795352015-03-11 02:30:51 +0000404 cl::opt<std::string> Arch(
405 "arch", cl::desc("architecture of the coverage mapping binary"));
406
Alex Lorenze82d89c2014-08-22 22:56:03 +0000407 cl::opt<bool> DebugDump("dump", cl::Optional,
408 cl::desc("Show internal debug dump"));
409
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000410 cl::opt<CoverageViewOptions::OutputFormat> Format(
411 "format", cl::desc("Output format for line-based coverage reports"),
412 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
413 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000414 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
415 "HTML output"),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000416 clEnumValEnd),
417 cl::init(CoverageViewOptions::OutputFormat::Text));
418
Alex Lorenze82d89c2014-08-22 22:56:03 +0000419 cl::opt<bool> FilenameEquivalence(
420 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000421 cl::desc("Treat source files as equivalent to paths in the coverage data "
422 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000423
424 cl::OptionCategory FilteringCategory("Function filtering options");
425
426 cl::list<std::string> NameFilters(
427 "name", cl::Optional,
428 cl::desc("Show code coverage only for functions with the given name"),
429 cl::ZeroOrMore, cl::cat(FilteringCategory));
430
431 cl::list<std::string> NameRegexFilters(
432 "name-regex", cl::Optional,
433 cl::desc("Show code coverage only for functions that match the given "
434 "regular expression"),
435 cl::ZeroOrMore, cl::cat(FilteringCategory));
436
437 cl::opt<double> RegionCoverageLtFilter(
438 "region-coverage-lt", cl::Optional,
439 cl::desc("Show code coverage only for functions with region coverage "
440 "less than the given threshold"),
441 cl::cat(FilteringCategory));
442
443 cl::opt<double> RegionCoverageGtFilter(
444 "region-coverage-gt", cl::Optional,
445 cl::desc("Show code coverage only for functions with region coverage "
446 "greater than the given threshold"),
447 cl::cat(FilteringCategory));
448
449 cl::opt<double> LineCoverageLtFilter(
450 "line-coverage-lt", cl::Optional,
451 cl::desc("Show code coverage only for functions with line coverage less "
452 "than the given threshold"),
453 cl::cat(FilteringCategory));
454
455 cl::opt<double> LineCoverageGtFilter(
456 "line-coverage-gt", cl::Optional,
457 cl::desc("Show code coverage only for functions with line coverage "
458 "greater than the given threshold"),
459 cl::cat(FilteringCategory));
460
Justin Bogner9deb1d42015-03-19 04:45:16 +0000461 cl::opt<cl::boolOrDefault> UseColor(
462 "use-color", cl::desc("Emit colored output (default=autodetect)"),
463 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000464
Vedant Kumar424f51b2016-07-15 22:44:57 +0000465 cl::list<std::string> DemanglerOpts(
466 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
467
Alex Lorenze82d89c2014-08-22 22:56:03 +0000468 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
469 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
470 ViewOpts.Debug = DebugDump;
471 CompareFilenamesOnly = FilenameEquivalence;
472
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000473 ViewOpts.Format = Format;
474 switch (ViewOpts.Format) {
475 case CoverageViewOptions::OutputFormat::Text:
476 ViewOpts.Colors = UseColor == cl::BOU_UNSET
477 ? sys::Process::StandardOutHasColors()
478 : UseColor == cl::BOU_TRUE;
479 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000480 case CoverageViewOptions::OutputFormat::HTML:
481 if (UseColor == cl::BOU_FALSE)
482 error("Color output cannot be disabled when generating html.");
483 ViewOpts.Colors = true;
484 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000485 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000486
Vedant Kumar424f51b2016-07-15 22:44:57 +0000487 // If a demangler is supplied, check if it exists and register it.
488 if (DemanglerOpts.size()) {
489 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
490 if (!DemanglerPathOrErr) {
491 error("Could not find the demangler!",
492 DemanglerPathOrErr.getError().message());
493 return 1;
494 }
495 DemanglerOpts[0] = *DemanglerPathOrErr;
496 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
497 }
498
Alex Lorenze82d89c2014-08-22 22:56:03 +0000499 // Create the function filters
500 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
501 auto NameFilterer = new CoverageFilters;
502 for (const auto &Name : NameFilters)
503 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
504 for (const auto &Regex : NameRegexFilters)
505 NameFilterer->push_back(
506 llvm::make_unique<NameRegexCoverageFilter>(Regex));
507 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
508 }
509 if (RegionCoverageLtFilter.getNumOccurrences() ||
510 RegionCoverageGtFilter.getNumOccurrences() ||
511 LineCoverageLtFilter.getNumOccurrences() ||
512 LineCoverageGtFilter.getNumOccurrences()) {
513 auto StatFilterer = new CoverageFilters;
514 if (RegionCoverageLtFilter.getNumOccurrences())
515 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
516 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
517 if (RegionCoverageGtFilter.getNumOccurrences())
518 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
519 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
520 if (LineCoverageLtFilter.getNumOccurrences())
521 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
522 LineCoverageFilter::LessThan, LineCoverageLtFilter));
523 if (LineCoverageGtFilter.getNumOccurrences())
524 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
525 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
526 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
527 }
528
Frederic Rissebc162a2015-06-22 21:33:24 +0000529 if (!Arch.empty() &&
530 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
531 errs() << "error: Unknown architecture: " << Arch << "\n";
532 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000533 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000534 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000535
Justin Bogner116c1662014-09-19 08:13:12 +0000536 for (const auto &File : InputSourceFiles) {
537 SmallString<128> Path(File);
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000538 if (!CompareFilenamesOnly)
539 if (std::error_code EC = sys::fs::make_absolute(Path)) {
540 errs() << "error: " << File << ": " << EC.message();
541 return 1;
542 }
Vedant Kumarcef440f2016-06-28 16:12:18 +0000543 addCollectedPath(Path.str());
Justin Bogner116c1662014-09-19 08:13:12 +0000544 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000545 return 0;
546 };
547
Alex Lorenze82d89c2014-08-22 22:56:03 +0000548 switch (Cmd) {
549 case Show:
550 return show(argc, argv, commandLineParser);
551 case Report:
552 return report(argc, argv, commandLineParser);
553 }
554 return 0;
555}
556
557int CodeCoverageTool::show(int argc, const char **argv,
558 CommandLineParserType commandLineParser) {
559
560 cl::OptionCategory ViewCategory("Viewing options");
561
562 cl::opt<bool> ShowLineExecutionCounts(
563 "show-line-counts", cl::Optional,
564 cl::desc("Show the execution counts for each line"), cl::init(true),
565 cl::cat(ViewCategory));
566
567 cl::opt<bool> ShowRegions(
568 "show-regions", cl::Optional,
569 cl::desc("Show the execution counts for each region"),
570 cl::cat(ViewCategory));
571
572 cl::opt<bool> ShowBestLineRegionsCounts(
573 "show-line-counts-or-regions", cl::Optional,
574 cl::desc("Show the execution counts for each line, or the execution "
575 "counts for each region on lines that have multiple regions"),
576 cl::cat(ViewCategory));
577
578 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
579 cl::desc("Show expanded source regions"),
580 cl::cat(ViewCategory));
581
582 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
583 cl::desc("Show function instantiations"),
584 cl::cat(ViewCategory));
585
Vedant Kumar7937ef32016-06-28 02:09:39 +0000586 cl::opt<std::string> ShowOutputDirectory(
587 "output-dir", cl::init(""),
588 cl::desc("Directory in which coverage information is written out"));
589 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
590 cl::aliasopt(ShowOutputDirectory));
591
Alex Lorenze82d89c2014-08-22 22:56:03 +0000592 auto Err = commandLineParser(argc, argv);
593 if (Err)
594 return Err;
595
Alex Lorenze82d89c2014-08-22 22:56:03 +0000596 ViewOpts.ShowLineNumbers = true;
597 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
598 !ShowRegions || ShowBestLineRegionsCounts;
599 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
600 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
601 ViewOpts.ShowExpandedRegions = ShowExpansions;
602 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000603 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
604
Vedant Kumar64d8a022016-06-28 16:12:20 +0000605 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000606 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
607 error("Could not create output directory!", E.message());
608 return 1;
609 }
610 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000611
Justin Bogner953e2402014-09-20 15:31:56 +0000612 auto Coverage = load();
613 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000614 return 1;
615
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000616 auto Printer = CoveragePrinter::create(ViewOpts);
617
Alex Lorenze82d89c2014-08-22 22:56:03 +0000618 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000619 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
620 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000621 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000622 return 1;
623 }
624 auto OS = std::move(OSOrErr.get());
625
626 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000627 for (const auto &Function : Coverage->getCoveredFunctions()) {
628 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000629 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000630
631 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000632 if (!mainView) {
Vedant Kumar2c96e882016-06-24 02:33:01 +0000633 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
634 << "warning: Could not read coverage for '" << Function.Name << "'."
635 << "\n";
Justin Bogner5a6edad2014-09-19 19:07:17 +0000636 continue;
637 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000638
Vedant Kumar7937ef32016-06-28 02:09:39 +0000639 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000640 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000641
642 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000643 return 0;
644 }
645
646 // Show files
647 bool ShowFilenames = SourceFiles.size() != 1;
648
Justin Bogner116c1662014-09-19 08:13:12 +0000649 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000650 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000651 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000652 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000653
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000654 // Create an index out of the source files.
655 if (ViewOpts.hasOutputDirectory()) {
656 if (Error E = Printer->createIndexFile(SourceFiles)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000657 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000658 return 1;
659 }
660 }
661
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000662 // In -output-dir mode, it's safe to use multiple threads to print files.
663 unsigned ThreadCount = 1;
664 if (ViewOpts.hasOutputDirectory())
665 ThreadCount = std::thread::hardware_concurrency();
666 ThreadPool Pool(ThreadCount);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000667
Vedant Kumar84c452d2016-07-15 01:19:35 +0000668 for (StringRef SourceFile : SourceFiles) {
669 Pool.async([this, SourceFile, &Coverage, &Printer, ShowFilenames] {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000670 auto View = createSourceFileView(SourceFile, *Coverage);
671 if (!View) {
672 deferWarning("The file '" + SourceFile.str() + "' isn't covered.");
673 return;
674 }
675
676 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
677 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000678 deferError("Could not create view file!", toString(std::move(E)));
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000679 return;
680 }
681 auto OS = std::move(OSOrErr.get());
682
683 View->print(*OS.get(), /*Wholefile=*/true,
684 /*ShowSourceName=*/ShowFilenames);
685 Printer->closeViewFile(std::move(OS));
686 });
Alex Lorenze82d89c2014-08-22 22:56:03 +0000687 }
688
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000689 Pool.wait();
690
691 consumeDeferredMessages();
692
Alex Lorenze82d89c2014-08-22 22:56:03 +0000693 return 0;
694}
695
696int CodeCoverageTool::report(int argc, const char **argv,
697 CommandLineParserType commandLineParser) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000698 auto Err = commandLineParser(argc, argv);
699 if (Err)
700 return Err;
701
Vedant Kumar4c010922016-07-06 21:44:05 +0000702 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
703 error("HTML output for summary reports is not yet supported.");
704
Justin Bogner953e2402014-09-20 15:31:56 +0000705 auto Coverage = load();
706 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000707 return 1;
708
Justin Bognerf91bc6c2015-02-14 02:01:24 +0000709 CoverageReport Report(ViewOpts, std::move(Coverage));
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000710 if (SourceFiles.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000711 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000712 else
713 Report.renderFunctionReports(SourceFiles, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000714 return 0;
715}
716
Justin Bognerd249a3b2014-10-30 20:57:49 +0000717int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000718 CodeCoverageTool Tool;
719 return Tool.run(CodeCoverageTool::Show, argc, argv);
720}
721
Justin Bognerd249a3b2014-10-30 20:57:49 +0000722int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000723 CodeCoverageTool Tool;
724 return Tool.run(CodeCoverageTool::Report, argc, argv);
725}