blob: 6edca9f6071e8c5736c80100911bf0b6d9d7dea5 [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
Vedant Kumar7101d732016-07-26 22:50:58 +000041void exportCoverageDataToJson(StringRef ObjectFilename,
42 const coverage::CoverageMapping &CoverageMapping,
43 raw_ostream &OS);
44
Alex Lorenze82d89c2014-08-22 22:56:03 +000045namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000046/// \brief The implementation of the coverage tool.
47class CodeCoverageTool {
48public:
49 enum Command {
50 /// \brief The show command.
51 Show,
52 /// \brief The report command.
Vedant Kumar7101d732016-07-26 22:50:58 +000053 Report,
54 /// \brief The export command.
55 Export
Alex Lorenze82d89c2014-08-22 22:56:03 +000056 };
57
58 /// \brief Print the error message to the error output stream.
59 void error(const Twine &Message, StringRef Whence = "");
60
Vedant Kumarb3020632016-07-18 17:53:12 +000061 /// \brief Print the warning message to the error output stream.
62 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar86b2ac632016-07-13 21:38:36 +000063
Vedant Kumar2ab08da2016-07-18 18:02:54 +000064 /// \brief Copy \p Path into the list of input source files.
Vedant Kumarcef440f2016-06-28 16:12:18 +000065 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
Vedant Kumar7101d732016-07-26 22:50:58 +0000103 int export_(int argc, const char **argv,
104 CommandLineParserType commandLineParser);
105
Justin Bognerf6c50552014-10-30 20:51:24 +0000106 std::string ObjectFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000107 CoverageViewOptions ViewOpts;
Justin Bogner953e2402014-09-20 15:31:56 +0000108 std::string PGOFilename;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000109 CoverageFiltersMatchAll Filters;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000110 std::vector<StringRef> SourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000111 bool CompareFilenamesOnly;
Justin Bogner116c1662014-09-19 08:13:12 +0000112 StringMap<std::string> RemappedFilenames;
Frederic Rissebc162a2015-06-22 21:33:24 +0000113 std::string CoverageArch;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000114
115private:
Vedant Kumar424f51b2016-07-15 22:44:57 +0000116 /// A cache for demangled symbol names.
117 StringMap<std::string> DemangledNames;
118
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000119 /// File paths (absolute, or otherwise) to input source files.
Vedant Kumarcef440f2016-06-28 16:12:18 +0000120 std::vector<std::string> CollectedPaths;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000121
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000122 /// Errors and warnings which have not been printed.
Vedant Kumarb3020632016-07-18 17:53:12 +0000123 std::mutex ErrsLock;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000124
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000125 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000126 std::mutex LoadedSourceFilesLock;
127 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
128 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000129};
130}
131
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000132static std::string getErrorString(const Twine &Message, StringRef Whence,
133 bool Warning) {
134 std::string Str = (Warning ? "warning" : "error");
135 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000136 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000137 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000138 Str += Message.str() + "\n";
139 return Str;
140}
141
142void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000143 std::unique_lock<std::mutex> Guard{ErrsLock};
144 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
145 << getErrorString(Message, Whence, false);
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000146}
147
Vedant Kumarb3020632016-07-18 17:53:12 +0000148void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
149 std::unique_lock<std::mutex> Guard{ErrsLock};
150 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
151 << getErrorString(Message, Whence, true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000152}
153
Vedant Kumarcef440f2016-06-28 16:12:18 +0000154void CodeCoverageTool::addCollectedPath(const std::string &Path) {
155 CollectedPaths.push_back(Path);
156 SourceFiles.emplace_back(CollectedPaths.back());
157}
158
Alex Lorenze82d89c2014-08-22 22:56:03 +0000159ErrorOr<const MemoryBuffer &>
160CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000161 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000162 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000163 if (!RemappedFilenames.empty()) {
164 auto Loc = RemappedFilenames.find(SourceFile);
165 if (Loc != RemappedFilenames.end())
166 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000167 }
Justin Bogner116c1662014-09-19 08:13:12 +0000168 for (const auto &Files : LoadedSourceFiles)
169 if (sys::fs::equivalent(SourceFile, Files.first))
170 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000171 auto Buffer = MemoryBuffer::getFile(SourceFile);
172 if (auto EC = Buffer.getError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000173 error(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000174 return EC;
175 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000176 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000177 return *LoadedSourceFiles.back().second;
178}
179
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000180void CodeCoverageTool::attachExpansionSubViews(
181 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
182 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000183 if (!ViewOpts.ShowExpandedRegions)
184 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000185 for (const auto &Expansion : Expansions) {
186 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
187 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000188 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000189 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
190 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000191 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000192
193 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000194 auto SubView =
195 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
196 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000197 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
198 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000199 }
200}
201
Justin Bogner5a6edad2014-09-19 19:07:17 +0000202std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000203CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000204 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000205 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
206 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000207 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000208 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000209 if (!SourceBuffer)
210 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000211
212 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar0053c0b2016-09-08 00:56:48 +0000213 auto View = SourceCoverageView::create(getSymbolForHumans(Function.Name),
214 SourceBuffer.get(), ViewOpts,
215 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000216 attachExpansionSubViews(*View, Expansions, Coverage);
217
218 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000219}
220
Justin Bogner953e2402014-09-20 15:31:56 +0000221std::unique_ptr<SourceCoverageView>
222CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000223 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000224 auto SourceBuffer = getSourceFile(SourceFile);
225 if (!SourceBuffer)
226 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000227 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
228 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000229 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000230
231 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000232 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
233 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000234 attachExpansionSubViews(*View, Expansions, Coverage);
235
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000236 for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000237 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
238 auto SubViewExpansions = SubViewCoverage.getExpansions();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000239 auto SubView = SourceCoverageView::create(
240 getSymbolForHumans(Function->Name), SourceBuffer.get(), ViewOpts,
Vedant Kumar0053c0b2016-09-08 00:56:48 +0000241 std::move(SubViewCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000242 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
243
244 if (SubView) {
Justin Bogner5e1400a2014-09-17 05:33:20 +0000245 unsigned FileID = Function->CountedRegions.front().FileID;
246 unsigned Line = 0;
247 for (const auto &CR : Function->CountedRegions)
248 if (CR.FileID == FileID)
249 Line = std::max(CR.LineEnd, Line);
Justin Bogner953e2402014-09-20 15:31:56 +0000250 View->addInstantiation(Function->Name, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000251 }
252 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000253 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000254}
255
Justin Bogner65337d12015-05-04 04:09:38 +0000256static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
257 sys::fs::file_status Status;
258 if (sys::fs::status(LHS, Status))
259 return false;
260 auto LHSTime = Status.getLastModificationTime();
261 if (sys::fs::status(RHS, Status))
262 return false;
263 auto RHSTime = Status.getLastModificationTime();
264 return LHSTime > RHSTime;
265}
266
Justin Bogner953e2402014-09-20 15:31:56 +0000267std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Justin Bogner65337d12015-05-04 04:09:38 +0000268 if (modifiedTimeGT(ObjectFilename, PGOFilename))
Vedant Kumarb3020632016-07-18 17:53:12 +0000269 warning("profile data may be out of date - object is newer",
270 ObjectFilename);
271 auto CoverageOrErr =
272 CoverageMapping::load(ObjectFilename, PGOFilename, CoverageArch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000273 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000274 error("Failed to load coverage: " + toString(std::move(E)), ObjectFilename);
Justin Bogner953e2402014-09-20 15:31:56 +0000275 return nullptr;
276 }
277 auto Coverage = std::move(CoverageOrErr.get());
278 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumarb3020632016-07-18 17:53:12 +0000279 if (Mismatched)
280 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000281
282 if (CompareFilenamesOnly) {
Justin Bogner953e2402014-09-20 15:31:56 +0000283 auto CoveredFiles = Coverage.get()->getUniqueSourceFiles();
Justin Bogner116c1662014-09-19 08:13:12 +0000284 for (auto &SF : SourceFiles) {
285 StringRef SFBase = sys::path::filename(SF);
286 for (const auto &CF : CoveredFiles)
287 if (SFBase == sys::path::filename(CF)) {
288 RemappedFilenames[CF] = SF;
289 SF = CF;
290 break;
291 }
292 }
293 }
294
Vedant Kumar424f51b2016-07-15 22:44:57 +0000295 demangleSymbols(*Coverage);
296
Justin Bogner953e2402014-09-20 15:31:56 +0000297 return Coverage;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000298}
299
Vedant Kumar424f51b2016-07-15 22:44:57 +0000300void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
301 if (!ViewOpts.hasDemangler())
302 return;
303
304 // Pass function names to the demangler in a temporary file.
305 int InputFD;
306 SmallString<256> InputPath;
307 std::error_code EC =
308 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
309 if (EC) {
310 error(InputPath, EC.message());
311 return;
312 }
313 tool_output_file InputTOF{InputPath, InputFD};
314
315 unsigned NumSymbols = 0;
316 for (const auto &Function : Coverage.getCoveredFunctions()) {
317 InputTOF.os() << Function.Name << '\n';
318 ++NumSymbols;
319 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000320 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000321
322 // Use another temporary file to store the demangler's output.
323 int OutputFD;
324 SmallString<256> OutputPath;
325 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
326 OutputPath);
327 if (EC) {
328 error(OutputPath, EC.message());
329 return;
330 }
331 tool_output_file OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000332 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000333
334 // Invoke the demangler.
335 std::vector<const char *> ArgsV;
336 for (const std::string &Arg : ViewOpts.DemanglerOpts)
337 ArgsV.push_back(Arg.c_str());
338 ArgsV.push_back(nullptr);
Vedant Kumar38202c02016-07-15 23:15:35 +0000339 StringRef InputPathRef = InputPath.str();
340 StringRef OutputPathRef = OutputPath.str();
341 StringRef StderrRef;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000342 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
343 std::string ErrMsg;
344 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
345 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
346 /*memoryLimit=*/0, &ErrMsg);
347 if (RC) {
348 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
349 return;
350 }
351
352 // Parse the demangler's output.
353 auto BufOrError = MemoryBuffer::getFile(OutputPath);
354 if (!BufOrError) {
355 error(OutputPath, BufOrError.getError().message());
356 return;
357 }
358
359 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
360
361 SmallVector<StringRef, 8> Symbols;
362 StringRef DemanglerData = DemanglerBuf->getBuffer();
363 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
364 /*KeepEmpty=*/false);
365 if (Symbols.size() != NumSymbols) {
366 error("Demangler did not provide expected number of symbols");
367 return;
368 }
369
370 // Cache the demangled names.
371 unsigned I = 0;
372 for (const auto &Function : Coverage.getCoveredFunctions())
373 DemangledNames[Function.Name] = Symbols[I++];
374}
375
376StringRef CodeCoverageTool::getSymbolForHumans(StringRef Sym) const {
377 const auto DemangledName = DemangledNames.find(Sym);
378 if (DemangledName == DemangledNames.end())
379 return Sym;
380 return DemangledName->getValue();
381}
382
Alex Lorenze82d89c2014-08-22 22:56:03 +0000383int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Justin Bognerf6c50552014-10-30 20:51:24 +0000384 cl::opt<std::string, true> ObjectFilename(
385 cl::Positional, cl::Required, cl::location(this->ObjectFilename),
386 cl::desc("Covered executable or object file."));
387
Alex Lorenze82d89c2014-08-22 22:56:03 +0000388 cl::list<std::string> InputSourceFiles(
389 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
390
Justin Bogner953e2402014-09-20 15:31:56 +0000391 cl::opt<std::string, true> PGOFilename(
392 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000393 cl::desc(
394 "File with the profile data obtained after an instrumented run"));
395
Justin Bogner43795352015-03-11 02:30:51 +0000396 cl::opt<std::string> Arch(
397 "arch", cl::desc("architecture of the coverage mapping binary"));
398
Alex Lorenze82d89c2014-08-22 22:56:03 +0000399 cl::opt<bool> DebugDump("dump", cl::Optional,
400 cl::desc("Show internal debug dump"));
401
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000402 cl::opt<CoverageViewOptions::OutputFormat> Format(
403 "format", cl::desc("Output format for line-based coverage reports"),
404 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
405 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000406 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
407 "HTML output"),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000408 clEnumValEnd),
409 cl::init(CoverageViewOptions::OutputFormat::Text));
410
Alex Lorenze82d89c2014-08-22 22:56:03 +0000411 cl::opt<bool> FilenameEquivalence(
412 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000413 cl::desc("Treat source files as equivalent to paths in the coverage data "
414 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000415
416 cl::OptionCategory FilteringCategory("Function filtering options");
417
418 cl::list<std::string> NameFilters(
419 "name", cl::Optional,
420 cl::desc("Show code coverage only for functions with the given name"),
421 cl::ZeroOrMore, cl::cat(FilteringCategory));
422
423 cl::list<std::string> NameRegexFilters(
424 "name-regex", cl::Optional,
425 cl::desc("Show code coverage only for functions that match the given "
426 "regular expression"),
427 cl::ZeroOrMore, cl::cat(FilteringCategory));
428
429 cl::opt<double> RegionCoverageLtFilter(
430 "region-coverage-lt", cl::Optional,
431 cl::desc("Show code coverage only for functions with region coverage "
432 "less than the given threshold"),
433 cl::cat(FilteringCategory));
434
435 cl::opt<double> RegionCoverageGtFilter(
436 "region-coverage-gt", cl::Optional,
437 cl::desc("Show code coverage only for functions with region coverage "
438 "greater than the given threshold"),
439 cl::cat(FilteringCategory));
440
441 cl::opt<double> LineCoverageLtFilter(
442 "line-coverage-lt", cl::Optional,
443 cl::desc("Show code coverage only for functions with line coverage less "
444 "than the given threshold"),
445 cl::cat(FilteringCategory));
446
447 cl::opt<double> LineCoverageGtFilter(
448 "line-coverage-gt", cl::Optional,
449 cl::desc("Show code coverage only for functions with line coverage "
450 "greater than the given threshold"),
451 cl::cat(FilteringCategory));
452
Justin Bogner9deb1d42015-03-19 04:45:16 +0000453 cl::opt<cl::boolOrDefault> UseColor(
454 "use-color", cl::desc("Emit colored output (default=autodetect)"),
455 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000456
Vedant Kumar424f51b2016-07-15 22:44:57 +0000457 cl::list<std::string> DemanglerOpts(
458 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
459
Alex Lorenze82d89c2014-08-22 22:56:03 +0000460 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
461 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
462 ViewOpts.Debug = DebugDump;
463 CompareFilenamesOnly = FilenameEquivalence;
464
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000465 ViewOpts.Format = Format;
Ying Yi84dc9712016-08-24 14:27:23 +0000466 SmallString<128> ObjectFilePath(this->ObjectFilename);
467 if (std::error_code EC = sys::fs::make_absolute(ObjectFilePath)) {
468 error(EC.message(), this->ObjectFilename);
469 return 1;
470 }
Ying Yi76eb2192016-08-30 07:01:37 +0000471 sys::path::native(ObjectFilePath);
Ying Yi84dc9712016-08-24 14:27:23 +0000472 ViewOpts.ObjectFilename = ObjectFilePath.c_str();
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000473 switch (ViewOpts.Format) {
474 case CoverageViewOptions::OutputFormat::Text:
475 ViewOpts.Colors = UseColor == cl::BOU_UNSET
476 ? sys::Process::StandardOutHasColors()
477 : UseColor == cl::BOU_TRUE;
478 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000479 case CoverageViewOptions::OutputFormat::HTML:
480 if (UseColor == cl::BOU_FALSE)
481 error("Color output cannot be disabled when generating html.");
482 ViewOpts.Colors = true;
483 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000484 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000485
Vedant Kumar424f51b2016-07-15 22:44:57 +0000486 // If a demangler is supplied, check if it exists and register it.
487 if (DemanglerOpts.size()) {
488 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
489 if (!DemanglerPathOrErr) {
490 error("Could not find the demangler!",
491 DemanglerPathOrErr.getError().message());
492 return 1;
493 }
494 DemanglerOpts[0] = *DemanglerPathOrErr;
495 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
496 }
497
Alex Lorenze82d89c2014-08-22 22:56:03 +0000498 // Create the function filters
499 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
500 auto NameFilterer = new CoverageFilters;
501 for (const auto &Name : NameFilters)
502 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
503 for (const auto &Regex : NameRegexFilters)
504 NameFilterer->push_back(
505 llvm::make_unique<NameRegexCoverageFilter>(Regex));
506 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
507 }
508 if (RegionCoverageLtFilter.getNumOccurrences() ||
509 RegionCoverageGtFilter.getNumOccurrences() ||
510 LineCoverageLtFilter.getNumOccurrences() ||
511 LineCoverageGtFilter.getNumOccurrences()) {
512 auto StatFilterer = new CoverageFilters;
513 if (RegionCoverageLtFilter.getNumOccurrences())
514 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
515 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
516 if (RegionCoverageGtFilter.getNumOccurrences())
517 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
518 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
519 if (LineCoverageLtFilter.getNumOccurrences())
520 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
521 LineCoverageFilter::LessThan, LineCoverageLtFilter));
522 if (LineCoverageGtFilter.getNumOccurrences())
523 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
524 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
525 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
526 }
527
Frederic Rissebc162a2015-06-22 21:33:24 +0000528 if (!Arch.empty() &&
529 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000530 error("Unknown architecture: " + Arch);
Frederic Rissebc162a2015-06-22 21:33:24 +0000531 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000532 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000533 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000534
Justin Bogner116c1662014-09-19 08:13:12 +0000535 for (const auto &File : InputSourceFiles) {
536 SmallString<128> Path(File);
Vedant Kumarb3020632016-07-18 17:53:12 +0000537 if (!CompareFilenamesOnly) {
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000538 if (std::error_code EC = sys::fs::make_absolute(Path)) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000539 error(EC.message(), File);
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000540 return 1;
541 }
Vedant Kumarb3020632016-07-18 17:53:12 +0000542 }
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);
Vedant Kumar7101d732016-07-26 22:50:58 +0000553 case Export:
554 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000555 }
556 return 0;
557}
558
559int CodeCoverageTool::show(int argc, const char **argv,
560 CommandLineParserType commandLineParser) {
561
562 cl::OptionCategory ViewCategory("Viewing options");
563
564 cl::opt<bool> ShowLineExecutionCounts(
565 "show-line-counts", cl::Optional,
566 cl::desc("Show the execution counts for each line"), cl::init(true),
567 cl::cat(ViewCategory));
568
569 cl::opt<bool> ShowRegions(
570 "show-regions", cl::Optional,
571 cl::desc("Show the execution counts for each region"),
572 cl::cat(ViewCategory));
573
574 cl::opt<bool> ShowBestLineRegionsCounts(
575 "show-line-counts-or-regions", cl::Optional,
576 cl::desc("Show the execution counts for each line, or the execution "
577 "counts for each region on lines that have multiple regions"),
578 cl::cat(ViewCategory));
579
580 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
581 cl::desc("Show expanded source regions"),
582 cl::cat(ViewCategory));
583
584 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
585 cl::desc("Show function instantiations"),
586 cl::cat(ViewCategory));
587
Vedant Kumar7937ef32016-06-28 02:09:39 +0000588 cl::opt<std::string> ShowOutputDirectory(
589 "output-dir", cl::init(""),
590 cl::desc("Directory in which coverage information is written out"));
591 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
592 cl::aliasopt(ShowOutputDirectory));
593
Ying Yi0ef31b72016-08-04 10:39:43 +0000594 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000595 "tab-size", cl::init(2),
596 cl::desc(
597 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000598
Ying Yi84dc9712016-08-24 14:27:23 +0000599 cl::opt<std::string> ProjectTitle(
600 "project-title", cl::Optional,
601 cl::desc("Set project title for the coverage report"));
602
Alex Lorenze82d89c2014-08-22 22:56:03 +0000603 auto Err = commandLineParser(argc, argv);
604 if (Err)
605 return Err;
606
Alex Lorenze82d89c2014-08-22 22:56:03 +0000607 ViewOpts.ShowLineNumbers = true;
608 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
609 !ShowRegions || ShowBestLineRegionsCounts;
610 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
611 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
612 ViewOpts.ShowExpandedRegions = ShowExpansions;
613 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000614 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000615 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000616 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000617
Vedant Kumar64d8a022016-06-28 16:12:20 +0000618 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000619 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
620 error("Could not create output directory!", E.message());
621 return 1;
622 }
623 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000624
Ying Yi84dc9712016-08-24 14:27:23 +0000625 sys::fs::file_status Status;
626 if (sys::fs::status(PGOFilename, Status)) {
627 error("profdata file error: can not get the file status. \n");
628 return 1;
629 }
630
631 auto ModifiedTime = Status.getLastModificationTime();
632 std::string ModifiedTimeStr = ModifiedTime.str();
633 size_t found = ModifiedTimeStr.rfind(":");
634 ViewOpts.CreatedTimeStr = (found != std::string::npos)
635 ? "Created: " + ModifiedTimeStr.substr(0, found)
636 : "Created: " + ModifiedTimeStr;
637
Justin Bogner953e2402014-09-20 15:31:56 +0000638 auto Coverage = load();
639 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000640 return 1;
641
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000642 auto Printer = CoveragePrinter::create(ViewOpts);
643
Alex Lorenze82d89c2014-08-22 22:56:03 +0000644 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000645 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
646 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000647 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000648 return 1;
649 }
650 auto OS = std::move(OSOrErr.get());
651
652 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000653 for (const auto &Function : Coverage->getCoveredFunctions()) {
654 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000655 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000656
657 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000658 if (!mainView) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000659 warning("Could not read coverage for '" + Function.Name + "'.");
Justin Bogner5a6edad2014-09-19 19:07:17 +0000660 continue;
661 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000662
Vedant Kumar7937ef32016-06-28 02:09:39 +0000663 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000664 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000665
666 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000667 return 0;
668 }
669
670 // Show files
Ying Yi84dc9712016-08-24 14:27:23 +0000671 bool ShowFilenames =
Ying Yi24e91bd2016-09-06 21:41:38 +0000672 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
Ying Yi84dc9712016-08-24 14:27:23 +0000673 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000674
Justin Bogner116c1662014-09-19 08:13:12 +0000675 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000676 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000677 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000678 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000679
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000680 // Create an index out of the source files.
681 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumara59334d2016-09-09 01:32:55 +0000682 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000683 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000684 return 1;
685 }
686 }
687
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000688 // In -output-dir mode, it's safe to use multiple threads to print files.
689 unsigned ThreadCount = 1;
690 if (ViewOpts.hasOutputDirectory())
691 ThreadCount = std::thread::hardware_concurrency();
692 ThreadPool Pool(ThreadCount);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000693
Vedant Kumar84c452d2016-07-15 01:19:35 +0000694 for (StringRef SourceFile : SourceFiles) {
695 Pool.async([this, SourceFile, &Coverage, &Printer, ShowFilenames] {
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000696 auto View = createSourceFileView(SourceFile, *Coverage);
697 if (!View) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000698 warning("The file '" + SourceFile.str() + "' isn't covered.");
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000699 return;
700 }
701
702 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
703 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000704 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000705 return;
706 }
707 auto OS = std::move(OSOrErr.get());
708
709 View->print(*OS.get(), /*Wholefile=*/true,
710 /*ShowSourceName=*/ShowFilenames);
711 Printer->closeViewFile(std::move(OS));
712 });
Alex Lorenze82d89c2014-08-22 22:56:03 +0000713 }
714
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000715 Pool.wait();
716
Alex Lorenze82d89c2014-08-22 22:56:03 +0000717 return 0;
718}
719
720int CodeCoverageTool::report(int argc, const char **argv,
721 CommandLineParserType commandLineParser) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000722 auto Err = commandLineParser(argc, argv);
723 if (Err)
724 return Err;
725
Vedant Kumar4c010922016-07-06 21:44:05 +0000726 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
727 error("HTML output for summary reports is not yet supported.");
728
Justin Bogner953e2402014-09-20 15:31:56 +0000729 auto Coverage = load();
730 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000731 return 1;
732
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000733 CoverageReport Report(ViewOpts, *Coverage.get());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000734 if (SourceFiles.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000735 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000736 else
737 Report.renderFunctionReports(SourceFiles, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000738 return 0;
739}
740
Vedant Kumar7101d732016-07-26 22:50:58 +0000741int CodeCoverageTool::export_(int argc, const char **argv,
742 CommandLineParserType commandLineParser) {
743
744 auto Err = commandLineParser(argc, argv);
745 if (Err)
746 return Err;
747
748 auto Coverage = load();
749 if (!Coverage) {
750 error("Could not load coverage information");
751 return 1;
752 }
753
754 exportCoverageDataToJson(ObjectFilename, *Coverage.get(), outs());
755
756 return 0;
757}
758
Justin Bognerd249a3b2014-10-30 20:57:49 +0000759int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000760 CodeCoverageTool Tool;
761 return Tool.run(CodeCoverageTool::Show, argc, argv);
762}
763
Justin Bognerd249a3b2014-10-30 20:57:49 +0000764int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000765 CodeCoverageTool Tool;
766 return Tool.run(CodeCoverageTool::Report, argc, argv);
767}
Vedant Kumar7101d732016-07-26 22:50:58 +0000768
769int exportMain(int argc, const char *argv[]) {
770 CodeCoverageTool Tool;
771 return Tool.run(CodeCoverageTool::Export, argc, argv);
772}