blob: e5878df6c154fc88ce66b57ed77ed6fa40d16a6d [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"
Vedant Kumar6e28bcd2017-02-05 20:10:58 +000018#include "CoverageSummaryInfo.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000019#include "CoverageViewOptions.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000020#include "RenderingSupport.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000021#include "SourceCoverageView.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000022#include "llvm/ADT/SmallString.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000023#include "llvm/ADT/StringRef.h"
Justin Bogner43795352015-03-11 02:30:51 +000024#include "llvm/ADT/Triple.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000025#include "llvm/ProfileData/Coverage/CoverageMapping.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000026#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FileSystem.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000029#include "llvm/Support/Format.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000030#include "llvm/Support/MemoryBuffer.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000031#include "llvm/Support/Path.h"
Justin Bognercfb53e42015-03-19 00:02:23 +000032#include "llvm/Support/Process.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000033#include "llvm/Support/Program.h"
Pavel Labath757ca882016-10-24 10:59:17 +000034#include "llvm/Support/ScopedPrinter.h"
Vedant Kumar7fa75102017-07-11 01:23:29 +000035#include "llvm/Support/Threading.h"
Vedant Kumar86b2ac632016-07-13 21:38:36 +000036#include "llvm/Support/ThreadPool.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000037#include "llvm/Support/ToolOutputFile.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000038#include <functional>
Justin Bognere53be062014-09-09 05:32:18 +000039#include <system_error>
Alex Lorenze82d89c2014-08-22 22:56:03 +000040
41using namespace llvm;
42using namespace coverage;
43
Vedant Kumar5c61c702016-10-25 00:08:33 +000044void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
Vedant Kumar7101d732016-07-26 22:50:58 +000045 raw_ostream &OS);
46
Alex Lorenze82d89c2014-08-22 22:56:03 +000047namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000048/// \brief The implementation of the coverage tool.
49class CodeCoverageTool {
50public:
51 enum Command {
52 /// \brief The show command.
53 Show,
54 /// \brief The report command.
Vedant Kumar7101d732016-07-26 22:50:58 +000055 Report,
56 /// \brief The export command.
57 Export
Alex Lorenze82d89c2014-08-22 22:56:03 +000058 };
59
Vedant Kumar46103672016-09-22 21:49:47 +000060 int run(Command Cmd, int argc, const char **argv);
61
62private:
Alex Lorenze82d89c2014-08-22 22:56:03 +000063 /// \brief Print the error message to the error output stream.
64 void error(const Twine &Message, StringRef Whence = "");
65
Vedant Kumarb3020632016-07-18 17:53:12 +000066 /// \brief Print the warning message to the error output stream.
67 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar86b2ac632016-07-13 21:38:36 +000068
Vedant Kumarbc647982016-09-23 18:57:32 +000069 /// \brief Convert \p Path into an absolute path and append it to the list
70 /// of collected paths.
Vedant Kumarcef440f2016-06-28 16:12:18 +000071 void addCollectedPath(const std::string &Path);
72
Vedant Kumar1ce90d82016-09-22 21:49:43 +000073 /// \brief If \p Path is a regular file, collect the path. If it's a
74 /// directory, recursively collect all of the paths within the directory.
75 void collectPaths(const std::string &Path);
76
Alex Lorenze82d89c2014-08-22 22:56:03 +000077 /// \brief Return a memory buffer for the given source file.
78 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
79
Justin Bogner953e2402014-09-20 15:31:56 +000080 /// \brief Create source views for the expansions of the view.
81 void attachExpansionSubViews(SourceCoverageView &View,
82 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000083 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000084
Justin Bogner953e2402014-09-20 15:31:56 +000085 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000086 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000087 createFunctionView(const FunctionRecord &Function,
88 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000089
90 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000091 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000092 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000093
Simon Pilgrimdae11f72016-11-20 13:31:13 +000094 /// \brief Load the coverage mapping data. Return nullptr if an error occurred.
Justin Bogner953e2402014-09-20 15:31:56 +000095 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000096
Sean Eveson9edfeac2017-08-14 10:20:12 +000097 /// \brief Create a mapping from files in the Coverage data to local copies
98 /// (path-equivalence).
99 void remapPathNames(const CoverageMapping &Coverage);
100
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000101 /// \brief Remove input source files which aren't mapped by \p Coverage.
102 void removeUnmappedInputs(const CoverageMapping &Coverage);
103
Vedant Kumar424f51b2016-07-15 22:44:57 +0000104 /// \brief If a demangler is available, demangle all symbol names.
105 void demangleSymbols(const CoverageMapping &Coverage);
106
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000107 /// \brief Write out a source file view to the filesystem.
108 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
109 CoveragePrinter *Printer, bool ShowFilenames);
110
Benjamin Kramerc321e532016-06-08 19:09:22 +0000111 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000112
113 int show(int argc, const char **argv,
114 CommandLineParserType commandLineParser);
115
116 int report(int argc, const char **argv,
117 CommandLineParserType commandLineParser);
118
Vedant Kumar7101d732016-07-26 22:50:58 +0000119 int export_(int argc, const char **argv,
120 CommandLineParserType commandLineParser);
121
Vedant Kumara3661ef2016-10-25 17:40:55 +0000122 std::vector<StringRef> ObjectFilenames;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000123 CoverageViewOptions ViewOpts;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000124 CoverageFiltersMatchAll Filters;
Vedant Kumar46103672016-09-22 21:49:47 +0000125
126 /// The path to the indexed profile.
127 std::string PGOFilename;
128
129 /// A list of input source files.
Vedant Kumarbc647982016-09-23 18:57:32 +0000130 std::vector<std::string> SourceFiles;
Vedant Kumar46103672016-09-22 21:49:47 +0000131
Sean Eveson9edfeac2017-08-14 10:20:12 +0000132 /// In -path-equivalence mode, this maps the absolute paths from the coverage
133 /// mapping data to the input source files.
Justin Bogner116c1662014-09-19 08:13:12 +0000134 StringMap<std::string> RemappedFilenames;
Vedant Kumar46103672016-09-22 21:49:47 +0000135
Sean Eveson9edfeac2017-08-14 10:20:12 +0000136 /// The coverage data path to be remapped from, and the source path to be
137 /// remapped to, when using -path-equivalence.
138 Optional<std::pair<std::string, std::string>> PathRemapping;
139
Vedant Kumar46103672016-09-22 21:49:47 +0000140 /// The architecture the coverage mapping data targets.
Vedant Kumar4b102c32017-08-01 21:23:26 +0000141 std::vector<StringRef> CoverageArches;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000142
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000143 /// A cache for demangled symbols.
144 DemangleCache DC;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000145
Vedant Kumarb6bfd472017-02-05 20:10:55 +0000146 /// A lock which guards printing to stderr.
Vedant Kumarb3020632016-07-18 17:53:12 +0000147 std::mutex ErrsLock;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000148
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000149 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000150 std::mutex LoadedSourceFilesLock;
151 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
152 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000153};
154}
155
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000156static std::string getErrorString(const Twine &Message, StringRef Whence,
157 bool Warning) {
158 std::string Str = (Warning ? "warning" : "error");
159 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000160 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000161 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000162 Str += Message.str() + "\n";
163 return Str;
164}
165
166void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000167 std::unique_lock<std::mutex> Guard{ErrsLock};
168 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
169 << getErrorString(Message, Whence, false);
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000170}
171
Vedant Kumarb3020632016-07-18 17:53:12 +0000172void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
173 std::unique_lock<std::mutex> Guard{ErrsLock};
174 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
175 << getErrorString(Message, Whence, true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000176}
177
Vedant Kumarcef440f2016-06-28 16:12:18 +0000178void CodeCoverageTool::addCollectedPath(const std::string &Path) {
Sean Eveson9edfeac2017-08-14 10:20:12 +0000179 SmallString<128> EffectivePath(Path);
180 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
181 error(EC.message(), Path);
182 return;
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000183 }
Sean Eveson9edfeac2017-08-14 10:20:12 +0000184 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
185 SourceFiles.emplace_back(EffectivePath.str());
Vedant Kumarcef440f2016-06-28 16:12:18 +0000186}
187
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000188void CodeCoverageTool::collectPaths(const std::string &Path) {
189 llvm::sys::fs::file_status Status;
190 llvm::sys::fs::status(Path, Status);
191 if (!llvm::sys::fs::exists(Status)) {
Sean Eveson9edfeac2017-08-14 10:20:12 +0000192 if (PathRemapping)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000193 addCollectedPath(Path);
194 else
195 error("Missing source file", Path);
196 return;
197 }
198
199 if (llvm::sys::fs::is_regular_file(Status)) {
200 addCollectedPath(Path);
201 return;
202 }
203
204 if (llvm::sys::fs::is_directory(Status)) {
205 std::error_code EC;
206 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
207 F != E && !EC; F.increment(EC)) {
208 if (llvm::sys::fs::is_regular_file(F->path()))
209 addCollectedPath(F->path());
210 }
211 if (EC)
212 warning(EC.message(), Path);
213 }
214}
215
Alex Lorenze82d89c2014-08-22 22:56:03 +0000216ErrorOr<const MemoryBuffer &>
217CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000218 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000219 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000220 if (!RemappedFilenames.empty()) {
221 auto Loc = RemappedFilenames.find(SourceFile);
222 if (Loc != RemappedFilenames.end())
223 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000224 }
Justin Bogner116c1662014-09-19 08:13:12 +0000225 for (const auto &Files : LoadedSourceFiles)
226 if (sys::fs::equivalent(SourceFile, Files.first))
227 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000228 auto Buffer = MemoryBuffer::getFile(SourceFile);
229 if (auto EC = Buffer.getError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000230 error(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000231 return EC;
232 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000233 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000234 return *LoadedSourceFiles.back().second;
235}
236
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000237void CodeCoverageTool::attachExpansionSubViews(
238 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
239 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000240 if (!ViewOpts.ShowExpandedRegions)
241 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000242 for (const auto &Expansion : Expansions) {
243 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
244 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000245 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000246 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
247 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000248 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000249
250 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000251 auto SubView =
252 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
253 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000254 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
255 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000256 }
257}
258
Justin Bogner5a6edad2014-09-19 19:07:17 +0000259std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000260CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000261 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000262 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
263 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000264 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000265 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000266 if (!SourceBuffer)
267 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000268
269 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000270 auto View = SourceCoverageView::create(DC.demangle(Function.Name),
Vedant Kumar0053c0b2016-09-08 00:56:48 +0000271 SourceBuffer.get(), ViewOpts,
272 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000273 attachExpansionSubViews(*View, Expansions, Coverage);
274
275 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000276}
277
Justin Bogner953e2402014-09-20 15:31:56 +0000278std::unique_ptr<SourceCoverageView>
279CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000280 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000281 auto SourceBuffer = getSourceFile(SourceFile);
282 if (!SourceBuffer)
283 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000284 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
285 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000286 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000287
288 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000289 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
290 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000291 attachExpansionSubViews(*View, Expansions, Coverage);
Vedant Kumar79554e42017-08-02 23:35:24 +0000292 if (!ViewOpts.ShowFunctionInstantiations)
293 return View;
Justin Bogner953e2402014-09-20 15:31:56 +0000294
Vedant Kumardde19c52017-08-02 23:35:25 +0000295 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
296 // Skip functions which have a single instantiation.
297 if (Group.size() < 2)
298 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000299
Vedant Kumardde19c52017-08-02 23:35:25 +0000300 for (const FunctionRecord *Function : Group.getInstantiations()) {
301 std::unique_ptr<SourceCoverageView> SubView{nullptr};
Vedant Kumare9079772016-09-20 21:27:48 +0000302
Vedant Kumardde19c52017-08-02 23:35:25 +0000303 StringRef Funcname = DC.demangle(Function->Name);
304
305 if (Function->ExecutionCount > 0) {
306 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
307 auto SubViewExpansions = SubViewCoverage.getExpansions();
308 SubView = SourceCoverageView::create(
309 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
310 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
311 }
312
313 unsigned FileID = Function->CountedRegions.front().FileID;
314 unsigned Line = 0;
315 for (const auto &CR : Function->CountedRegions)
316 if (CR.FileID == FileID)
317 Line = std::max(CR.LineEnd, Line);
318 View->addInstantiation(Funcname, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000319 }
320 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000321 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000322}
323
Justin Bogner65337d12015-05-04 04:09:38 +0000324static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
325 sys::fs::file_status Status;
326 if (sys::fs::status(LHS, Status))
327 return false;
328 auto LHSTime = Status.getLastModificationTime();
329 if (sys::fs::status(RHS, Status))
330 return false;
331 auto RHSTime = Status.getLastModificationTime();
332 return LHSTime > RHSTime;
333}
334
Justin Bogner953e2402014-09-20 15:31:56 +0000335std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000336 for (StringRef ObjectFilename : ObjectFilenames)
337 if (modifiedTimeGT(ObjectFilename, PGOFilename))
338 warning("profile data may be out of date - object is newer",
339 ObjectFilename);
Vedant Kumarb3020632016-07-18 17:53:12 +0000340 auto CoverageOrErr =
Vedant Kumar4b102c32017-08-01 21:23:26 +0000341 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000342 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000343 error("Failed to load coverage: " + toString(std::move(E)),
344 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
Justin Bogner953e2402014-09-20 15:31:56 +0000345 return nullptr;
346 }
347 auto Coverage = std::move(CoverageOrErr.get());
348 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumarb3020632016-07-18 17:53:12 +0000349 if (Mismatched)
350 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000351
Sean Eveson9edfeac2017-08-14 10:20:12 +0000352 remapPathNames(*Coverage);
353
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000354 if (!SourceFiles.empty())
355 removeUnmappedInputs(*Coverage);
356
357 demangleSymbols(*Coverage);
358
359 return Coverage;
360}
361
Sean Eveson9edfeac2017-08-14 10:20:12 +0000362void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
363 if (!PathRemapping)
364 return;
365
366 // Convert remapping paths to native paths with trailing seperators.
367 auto nativeWithTrailing = [](StringRef Path) -> std::string {
368 if (Path.empty())
369 return "";
370 SmallString<128> NativePath;
371 sys::path::native(Path, NativePath);
372 if (!sys::path::is_separator(NativePath.back()))
373 NativePath += sys::path::get_separator();
374 return NativePath.c_str();
375 };
376 std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
377 std::string RemapTo = nativeWithTrailing(PathRemapping->second);
378
379 // Create a mapping from coverage data file paths to local paths.
380 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
381 SmallString<128> NativeFilename;
382 sys::path::native(Filename, NativeFilename);
383 if (NativeFilename.startswith(RemapFrom)) {
384 RemappedFilenames[Filename] =
385 RemapTo + NativeFilename.substr(RemapFrom.size()).str();
386 }
387 }
388
389 // Convert input files from local paths to coverage data file paths.
390 StringMap<std::string> InvRemappedFilenames;
391 for (const auto &RemappedFilename : RemappedFilenames)
392 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
393
394 for (std::string &Filename : SourceFiles) {
395 SmallString<128> NativeFilename;
396 sys::path::native(Filename, NativeFilename);
397 auto CovFileName = InvRemappedFilenames.find(NativeFilename);
398 if (CovFileName != InvRemappedFilenames.end())
399 Filename = CovFileName->second;
400 }
401}
402
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000403void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
404 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
Vedant Kumar458808802016-09-23 18:57:35 +0000405
406 auto UncoveredFilesIt = SourceFiles.end();
Sean Eveson9edfeac2017-08-14 10:20:12 +0000407 // The user may have specified source files which aren't in the coverage
408 // mapping. Filter these files away.
409 UncoveredFilesIt = std::remove_if(
410 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
411 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
412 SF);
413 });
Justin Bogner116c1662014-09-19 08:13:12 +0000414
Vedant Kumar458808802016-09-23 18:57:35 +0000415 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000416}
417
Vedant Kumar424f51b2016-07-15 22:44:57 +0000418void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
419 if (!ViewOpts.hasDemangler())
420 return;
421
422 // Pass function names to the demangler in a temporary file.
423 int InputFD;
424 SmallString<256> InputPath;
425 std::error_code EC =
426 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
427 if (EC) {
428 error(InputPath, EC.message());
429 return;
430 }
431 tool_output_file InputTOF{InputPath, InputFD};
432
433 unsigned NumSymbols = 0;
434 for (const auto &Function : Coverage.getCoveredFunctions()) {
435 InputTOF.os() << Function.Name << '\n';
436 ++NumSymbols;
437 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000438 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000439
440 // Use another temporary file to store the demangler's output.
441 int OutputFD;
442 SmallString<256> OutputPath;
443 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
444 OutputPath);
445 if (EC) {
446 error(OutputPath, EC.message());
447 return;
448 }
449 tool_output_file OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000450 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000451
452 // Invoke the demangler.
453 std::vector<const char *> ArgsV;
454 for (const std::string &Arg : ViewOpts.DemanglerOpts)
455 ArgsV.push_back(Arg.c_str());
456 ArgsV.push_back(nullptr);
Vedant Kumar38202c02016-07-15 23:15:35 +0000457 StringRef InputPathRef = InputPath.str();
458 StringRef OutputPathRef = OutputPath.str();
459 StringRef StderrRef;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000460 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
461 std::string ErrMsg;
462 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
463 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
464 /*memoryLimit=*/0, &ErrMsg);
465 if (RC) {
466 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
467 return;
468 }
469
470 // Parse the demangler's output.
471 auto BufOrError = MemoryBuffer::getFile(OutputPath);
472 if (!BufOrError) {
473 error(OutputPath, BufOrError.getError().message());
474 return;
475 }
476
477 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
478
479 SmallVector<StringRef, 8> Symbols;
480 StringRef DemanglerData = DemanglerBuf->getBuffer();
481 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
482 /*KeepEmpty=*/false);
483 if (Symbols.size() != NumSymbols) {
484 error("Demangler did not provide expected number of symbols");
485 return;
486 }
487
488 // Cache the demangled names.
489 unsigned I = 0;
490 for (const auto &Function : Coverage.getCoveredFunctions())
Igor Kudrin9e015da2017-02-19 14:26:52 +0000491 // On Windows, lines in the demangler's output file end with "\r\n".
492 // Splitting by '\n' keeps '\r's, so cut them now.
493 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000494}
495
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000496void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
497 CoverageMapping *Coverage,
498 CoveragePrinter *Printer,
499 bool ShowFilenames) {
500 auto View = createSourceFileView(SourceFile, *Coverage);
501 if (!View) {
502 warning("The file '" + SourceFile + "' isn't covered.");
503 return;
504 }
505
506 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
507 if (Error E = OSOrErr.takeError()) {
508 error("Could not create view file!", toString(std::move(E)));
509 return;
510 }
511 auto OS = std::move(OSOrErr.get());
512
513 View->print(*OS.get(), /*Wholefile=*/true,
514 /*ShowSourceName=*/ShowFilenames);
515 Printer->closeViewFile(std::move(OS));
516}
517
Alex Lorenze82d89c2014-08-22 22:56:03 +0000518int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000519 cl::opt<std::string> CovFilename(
520 cl::Positional, cl::desc("Covered executable or object file."));
521
522 cl::list<std::string> CovFilenames(
523 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
524 cl::CommaSeparated);
Justin Bognerf6c50552014-10-30 20:51:24 +0000525
Alex Lorenze82d89c2014-08-22 22:56:03 +0000526 cl::list<std::string> InputSourceFiles(
527 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
528
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000529 cl::opt<bool> DebugDumpCollectedPaths(
530 "dump-collected-paths", cl::Optional, cl::Hidden,
531 cl::desc("Show the collected paths to source files"));
532
Justin Bogner953e2402014-09-20 15:31:56 +0000533 cl::opt<std::string, true> PGOFilename(
534 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000535 cl::desc(
536 "File with the profile data obtained after an instrumented run"));
537
Vedant Kumar4b102c32017-08-01 21:23:26 +0000538 cl::list<std::string> Arches(
539 "arch", cl::desc("architectures of the coverage mapping binaries"));
Justin Bogner43795352015-03-11 02:30:51 +0000540
Alex Lorenze82d89c2014-08-22 22:56:03 +0000541 cl::opt<bool> DebugDump("dump", cl::Optional,
542 cl::desc("Show internal debug dump"));
543
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000544 cl::opt<CoverageViewOptions::OutputFormat> Format(
545 "format", cl::desc("Output format for line-based coverage reports"),
546 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
547 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000548 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000549 "HTML output")),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000550 cl::init(CoverageViewOptions::OutputFormat::Text));
551
Sean Eveson9edfeac2017-08-14 10:20:12 +0000552 cl::opt<std::string> PathRemap(
553 "path-equivalence", cl::Optional,
554 cl::desc("<from>,<to> Map coverage data paths to local source file "
555 "paths"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000556
557 cl::OptionCategory FilteringCategory("Function filtering options");
558
559 cl::list<std::string> NameFilters(
560 "name", cl::Optional,
561 cl::desc("Show code coverage only for functions with the given name"),
562 cl::ZeroOrMore, cl::cat(FilteringCategory));
563
564 cl::list<std::string> NameRegexFilters(
565 "name-regex", cl::Optional,
566 cl::desc("Show code coverage only for functions that match the given "
567 "regular expression"),
568 cl::ZeroOrMore, cl::cat(FilteringCategory));
569
570 cl::opt<double> RegionCoverageLtFilter(
571 "region-coverage-lt", cl::Optional,
572 cl::desc("Show code coverage only for functions with region coverage "
573 "less than the given threshold"),
574 cl::cat(FilteringCategory));
575
576 cl::opt<double> RegionCoverageGtFilter(
577 "region-coverage-gt", cl::Optional,
578 cl::desc("Show code coverage only for functions with region coverage "
579 "greater than the given threshold"),
580 cl::cat(FilteringCategory));
581
582 cl::opt<double> LineCoverageLtFilter(
583 "line-coverage-lt", cl::Optional,
584 cl::desc("Show code coverage only for functions with line coverage less "
585 "than the given threshold"),
586 cl::cat(FilteringCategory));
587
588 cl::opt<double> LineCoverageGtFilter(
589 "line-coverage-gt", cl::Optional,
590 cl::desc("Show code coverage only for functions with line coverage "
591 "greater than the given threshold"),
592 cl::cat(FilteringCategory));
593
Justin Bogner9deb1d42015-03-19 04:45:16 +0000594 cl::opt<cl::boolOrDefault> UseColor(
595 "use-color", cl::desc("Emit colored output (default=autodetect)"),
596 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000597
Vedant Kumar424f51b2016-07-15 22:44:57 +0000598 cl::list<std::string> DemanglerOpts(
599 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
600
Alex Lorenze82d89c2014-08-22 22:56:03 +0000601 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
602 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
603 ViewOpts.Debug = DebugDump;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000604
Vedant Kumara3661ef2016-10-25 17:40:55 +0000605 if (!CovFilename.empty())
606 ObjectFilenames.emplace_back(CovFilename);
607 for (const std::string &Filename : CovFilenames)
608 ObjectFilenames.emplace_back(Filename);
609 if (ObjectFilenames.empty()) {
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000610 errs() << "No filenames specified!\n";
Vedant Kumara3661ef2016-10-25 17:40:55 +0000611 ::exit(1);
612 }
613
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000614 ViewOpts.Format = Format;
615 switch (ViewOpts.Format) {
616 case CoverageViewOptions::OutputFormat::Text:
617 ViewOpts.Colors = UseColor == cl::BOU_UNSET
618 ? sys::Process::StandardOutHasColors()
619 : UseColor == cl::BOU_TRUE;
620 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000621 case CoverageViewOptions::OutputFormat::HTML:
622 if (UseColor == cl::BOU_FALSE)
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000623 errs() << "Color output cannot be disabled when generating html.\n";
Vedant Kumar4c010922016-07-06 21:44:05 +0000624 ViewOpts.Colors = true;
625 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000626 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000627
Sean Eveson9edfeac2017-08-14 10:20:12 +0000628 // If path-equivalence was given and is a comma seperated pair then set
629 // PathRemapping.
630 auto EquivPair = StringRef(PathRemap).split(',');
631 if (!(EquivPair.first.empty() && EquivPair.second.empty()))
632 PathRemapping = EquivPair;
633
Vedant Kumar424f51b2016-07-15 22:44:57 +0000634 // If a demangler is supplied, check if it exists and register it.
635 if (DemanglerOpts.size()) {
636 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
637 if (!DemanglerPathOrErr) {
638 error("Could not find the demangler!",
639 DemanglerPathOrErr.getError().message());
640 return 1;
641 }
642 DemanglerOpts[0] = *DemanglerPathOrErr;
643 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
644 }
645
Alex Lorenze82d89c2014-08-22 22:56:03 +0000646 // Create the function filters
647 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000648 auto NameFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000649 for (const auto &Name : NameFilters)
650 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
651 for (const auto &Regex : NameRegexFilters)
652 NameFilterer->push_back(
653 llvm::make_unique<NameRegexCoverageFilter>(Regex));
Vedant Kumar8a622382017-08-04 00:36:24 +0000654 Filters.push_back(std::move(NameFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000655 }
656 if (RegionCoverageLtFilter.getNumOccurrences() ||
657 RegionCoverageGtFilter.getNumOccurrences() ||
658 LineCoverageLtFilter.getNumOccurrences() ||
659 LineCoverageGtFilter.getNumOccurrences()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000660 auto StatFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000661 if (RegionCoverageLtFilter.getNumOccurrences())
662 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
663 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
664 if (RegionCoverageGtFilter.getNumOccurrences())
665 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
666 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
667 if (LineCoverageLtFilter.getNumOccurrences())
668 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
669 LineCoverageFilter::LessThan, LineCoverageLtFilter));
670 if (LineCoverageGtFilter.getNumOccurrences())
671 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
672 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
Vedant Kumar8a622382017-08-04 00:36:24 +0000673 Filters.push_back(std::move(StatFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000674 }
675
Vedant Kumar4b102c32017-08-01 21:23:26 +0000676 if (!Arches.empty()) {
677 for (const std::string &Arch : Arches) {
678 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
679 error("Unknown architecture: " + Arch);
680 return 1;
681 }
682 CoverageArches.emplace_back(Arch);
683 }
684 if (CoverageArches.size() != ObjectFilenames.size()) {
685 error("Number of architectures doesn't match the number of objects");
686 return 1;
687 }
Justin Bogner43795352015-03-11 02:30:51 +0000688 }
689
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000690 for (const std::string &File : InputSourceFiles)
691 collectPaths(File);
692
693 if (DebugDumpCollectedPaths) {
Vedant Kumarbc647982016-09-23 18:57:32 +0000694 for (const std::string &SF : SourceFiles)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000695 outs() << SF << '\n';
696 ::exit(0);
Justin Bogner116c1662014-09-19 08:13:12 +0000697 }
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000698
Alex Lorenze82d89c2014-08-22 22:56:03 +0000699 return 0;
700 };
701
Alex Lorenze82d89c2014-08-22 22:56:03 +0000702 switch (Cmd) {
703 case Show:
704 return show(argc, argv, commandLineParser);
705 case Report:
706 return report(argc, argv, commandLineParser);
Vedant Kumar7101d732016-07-26 22:50:58 +0000707 case Export:
708 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000709 }
710 return 0;
711}
712
713int CodeCoverageTool::show(int argc, const char **argv,
714 CommandLineParserType commandLineParser) {
715
716 cl::OptionCategory ViewCategory("Viewing options");
717
718 cl::opt<bool> ShowLineExecutionCounts(
719 "show-line-counts", cl::Optional,
720 cl::desc("Show the execution counts for each line"), cl::init(true),
721 cl::cat(ViewCategory));
722
723 cl::opt<bool> ShowRegions(
724 "show-regions", cl::Optional,
725 cl::desc("Show the execution counts for each region"),
726 cl::cat(ViewCategory));
727
728 cl::opt<bool> ShowBestLineRegionsCounts(
729 "show-line-counts-or-regions", cl::Optional,
730 cl::desc("Show the execution counts for each line, or the execution "
731 "counts for each region on lines that have multiple regions"),
732 cl::cat(ViewCategory));
733
734 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
735 cl::desc("Show expanded source regions"),
736 cl::cat(ViewCategory));
737
738 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
739 cl::desc("Show function instantiations"),
Vedant Kumar79554e42017-08-02 23:35:24 +0000740 cl::init(true), cl::cat(ViewCategory));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000741
Vedant Kumar7937ef32016-06-28 02:09:39 +0000742 cl::opt<std::string> ShowOutputDirectory(
743 "output-dir", cl::init(""),
744 cl::desc("Directory in which coverage information is written out"));
745 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
746 cl::aliasopt(ShowOutputDirectory));
747
Ying Yi0ef31b72016-08-04 10:39:43 +0000748 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000749 "tab-size", cl::init(2),
750 cl::desc(
751 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000752
Ying Yi84dc9712016-08-24 14:27:23 +0000753 cl::opt<std::string> ProjectTitle(
754 "project-title", cl::Optional,
755 cl::desc("Set project title for the coverage report"));
756
Vedant Kumar7fa75102017-07-11 01:23:29 +0000757 cl::opt<unsigned> NumThreads(
758 "num-threads", cl::init(0),
759 cl::desc("Number of merge threads to use (default: autodetect)"));
760 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
761 cl::aliasopt(NumThreads));
762
Alex Lorenze82d89c2014-08-22 22:56:03 +0000763 auto Err = commandLineParser(argc, argv);
764 if (Err)
765 return Err;
766
Alex Lorenze82d89c2014-08-22 22:56:03 +0000767 ViewOpts.ShowLineNumbers = true;
768 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
769 !ShowRegions || ShowBestLineRegionsCounts;
770 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
771 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
772 ViewOpts.ShowExpandedRegions = ShowExpansions;
773 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000774 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000775 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000776 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000777
Vedant Kumar64d8a022016-06-28 16:12:20 +0000778 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000779 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
780 error("Could not create output directory!", E.message());
781 return 1;
782 }
783 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000784
Ying Yi84dc9712016-08-24 14:27:23 +0000785 sys::fs::file_status Status;
786 if (sys::fs::status(PGOFilename, Status)) {
787 error("profdata file error: can not get the file status. \n");
788 return 1;
789 }
790
791 auto ModifiedTime = Status.getLastModificationTime();
Pavel Labath757ca882016-10-24 10:59:17 +0000792 std::string ModifiedTimeStr = to_string(ModifiedTime);
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000793 size_t found = ModifiedTimeStr.rfind(':');
Ying Yi84dc9712016-08-24 14:27:23 +0000794 ViewOpts.CreatedTimeStr = (found != std::string::npos)
795 ? "Created: " + ModifiedTimeStr.substr(0, found)
796 : "Created: " + ModifiedTimeStr;
797
Justin Bogner953e2402014-09-20 15:31:56 +0000798 auto Coverage = load();
799 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000800 return 1;
801
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000802 auto Printer = CoveragePrinter::create(ViewOpts);
803
Alex Lorenze82d89c2014-08-22 22:56:03 +0000804 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000805 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
806 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000807 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000808 return 1;
809 }
810 auto OS = std::move(OSOrErr.get());
811
812 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000813 for (const auto &Function : Coverage->getCoveredFunctions()) {
814 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000815 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000816
817 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000818 if (!mainView) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000819 warning("Could not read coverage for '" + Function.Name + "'.");
Justin Bogner5a6edad2014-09-19 19:07:17 +0000820 continue;
821 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000822
Vedant Kumar7937ef32016-06-28 02:09:39 +0000823 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000824 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000825
826 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000827 return 0;
828 }
829
830 // Show files
Ying Yi84dc9712016-08-24 14:27:23 +0000831 bool ShowFilenames =
Ying Yi24e91bd2016-09-06 21:41:38 +0000832 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
Ying Yi84dc9712016-08-24 14:27:23 +0000833 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000834
Justin Bogner116c1662014-09-19 08:13:12 +0000835 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000836 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000837 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000838 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000839
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000840 // Create an index out of the source files.
841 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumara59334d2016-09-09 01:32:55 +0000842 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000843 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000844 return 1;
845 }
846 }
847
Vedant Kumar7fa75102017-07-11 01:23:29 +0000848 // If NumThreads is not specified, auto-detect a good default.
849 if (NumThreads == 0)
850 NumThreads =
851 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
852 unsigned(SourceFiles.size())));
853
854 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000855 for (const std::string &SourceFile : SourceFiles)
856 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
857 ShowFilenames);
858 } else {
859 // In -output-dir mode, it's safe to use multiple threads to print files.
Vedant Kumar7fa75102017-07-11 01:23:29 +0000860 ThreadPool Pool(NumThreads);
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000861 for (const std::string &SourceFile : SourceFiles)
862 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
863 Coverage.get(), Printer.get(), ShowFilenames);
864 Pool.wait();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000865 }
866
867 return 0;
868}
869
870int CodeCoverageTool::report(int argc, const char **argv,
871 CommandLineParserType commandLineParser) {
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000872 cl::opt<bool> ShowFunctionSummaries(
873 "show-functions", cl::Optional, cl::init(false),
874 cl::desc("Show coverage summaries for each function"));
875
Alex Lorenze82d89c2014-08-22 22:56:03 +0000876 auto Err = commandLineParser(argc, argv);
877 if (Err)
878 return Err;
879
Vedant Kumar431359a2017-02-28 16:57:28 +0000880 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
Vedant Kumar4c010922016-07-06 21:44:05 +0000881 error("HTML output for summary reports is not yet supported.");
Vedant Kumar431359a2017-02-28 16:57:28 +0000882 return 1;
883 }
Vedant Kumar4c010922016-07-06 21:44:05 +0000884
Justin Bogner953e2402014-09-20 15:31:56 +0000885 auto Coverage = load();
886 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000887 return 1;
888
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000889 CoverageReport Report(ViewOpts, *Coverage.get());
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000890 if (!ShowFunctionSummaries)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000891 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000892 else
Vedant Kumarf2b067c2017-02-05 20:11:03 +0000893 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000894 return 0;
895}
896
Vedant Kumar7101d732016-07-26 22:50:58 +0000897int CodeCoverageTool::export_(int argc, const char **argv,
898 CommandLineParserType commandLineParser) {
899
900 auto Err = commandLineParser(argc, argv);
901 if (Err)
902 return Err;
903
Vedant Kumar431359a2017-02-28 16:57:28 +0000904 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
905 error("Coverage data can only be exported as textual JSON.");
906 return 1;
907 }
908
Vedant Kumar7101d732016-07-26 22:50:58 +0000909 auto Coverage = load();
910 if (!Coverage) {
911 error("Could not load coverage information");
912 return 1;
913 }
914
Vedant Kumar5c61c702016-10-25 00:08:33 +0000915 exportCoverageDataToJson(*Coverage.get(), outs());
Vedant Kumar7101d732016-07-26 22:50:58 +0000916
917 return 0;
918}
919
Justin Bognerd249a3b2014-10-30 20:57:49 +0000920int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000921 CodeCoverageTool Tool;
922 return Tool.run(CodeCoverageTool::Show, argc, argv);
923}
924
Justin Bognerd249a3b2014-10-30 20:57:49 +0000925int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000926 CodeCoverageTool Tool;
927 return Tool.run(CodeCoverageTool::Report, argc, argv);
928}
Vedant Kumar7101d732016-07-26 22:50:58 +0000929
930int exportMain(int argc, const char *argv[]) {
931 CodeCoverageTool Tool;
932 return Tool.run(CodeCoverageTool::Export, argc, argv);
933}