blob: 52169b6607cc4459cd56edca46e6d375369fee8d [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 Kumar86b2ac632016-07-13 21:38:36 +000035#include "llvm/Support/ThreadPool.h"
Vedant Kumar424f51b2016-07-15 22:44:57 +000036#include "llvm/Support/ToolOutputFile.h"
Alex Lorenze82d89c2014-08-22 22:56:03 +000037#include <functional>
Justin Bognere53be062014-09-09 05:32:18 +000038#include <system_error>
Alex Lorenze82d89c2014-08-22 22:56:03 +000039
40using namespace llvm;
41using namespace coverage;
42
Vedant Kumar5c61c702016-10-25 00:08:33 +000043void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
Vedant Kumar7101d732016-07-26 22:50:58 +000044 raw_ostream &OS);
45
Alex Lorenze82d89c2014-08-22 22:56:03 +000046namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000047/// \brief The implementation of the coverage tool.
48class CodeCoverageTool {
49public:
50 enum Command {
51 /// \brief The show command.
52 Show,
53 /// \brief The report command.
Vedant Kumar7101d732016-07-26 22:50:58 +000054 Report,
55 /// \brief The export command.
56 Export
Alex Lorenze82d89c2014-08-22 22:56:03 +000057 };
58
Vedant Kumar46103672016-09-22 21:49:47 +000059 int run(Command Cmd, int argc, const char **argv);
60
61private:
Alex Lorenze82d89c2014-08-22 22:56:03 +000062 /// \brief Print the error message to the error output stream.
63 void error(const Twine &Message, StringRef Whence = "");
64
Vedant Kumarb3020632016-07-18 17:53:12 +000065 /// \brief Print the warning message to the error output stream.
66 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar86b2ac632016-07-13 21:38:36 +000067
Vedant Kumarbc647982016-09-23 18:57:32 +000068 /// \brief Convert \p Path into an absolute path and append it to the list
69 /// of collected paths.
Vedant Kumarcef440f2016-06-28 16:12:18 +000070 void addCollectedPath(const std::string &Path);
71
Vedant Kumar1ce90d82016-09-22 21:49:43 +000072 /// \brief If \p Path is a regular file, collect the path. If it's a
73 /// directory, recursively collect all of the paths within the directory.
74 void collectPaths(const std::string &Path);
75
Alex Lorenze82d89c2014-08-22 22:56:03 +000076 /// \brief Return a memory buffer for the given source file.
77 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
78
Justin Bogner953e2402014-09-20 15:31:56 +000079 /// \brief Create source views for the expansions of the view.
80 void attachExpansionSubViews(SourceCoverageView &View,
81 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000082 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000083
Justin Bogner953e2402014-09-20 15:31:56 +000084 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000085 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000086 createFunctionView(const FunctionRecord &Function,
87 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000088
89 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000090 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000091 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000092
Simon Pilgrimdae11f72016-11-20 13:31:13 +000093 /// \brief Load the coverage mapping data. Return nullptr if an error occurred.
Justin Bogner953e2402014-09-20 15:31:56 +000094 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000095
Vedant Kumarcab52ad2016-09-23 20:13:41 +000096 /// \brief Remove input source files which aren't mapped by \p Coverage.
97 void removeUnmappedInputs(const CoverageMapping &Coverage);
98
Vedant Kumar424f51b2016-07-15 22:44:57 +000099 /// \brief If a demangler is available, demangle all symbol names.
100 void demangleSymbols(const CoverageMapping &Coverage);
101
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000102 /// \brief Write out a source file view to the filesystem.
103 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
104 CoveragePrinter *Printer, bool ShowFilenames);
105
Benjamin Kramerc321e532016-06-08 19:09:22 +0000106 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000107
108 int show(int argc, const char **argv,
109 CommandLineParserType commandLineParser);
110
111 int report(int argc, const char **argv,
112 CommandLineParserType commandLineParser);
113
Vedant Kumar7101d732016-07-26 22:50:58 +0000114 int export_(int argc, const char **argv,
115 CommandLineParserType commandLineParser);
116
Vedant Kumara3661ef2016-10-25 17:40:55 +0000117 std::vector<StringRef> ObjectFilenames;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000118 CoverageViewOptions ViewOpts;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000119 CoverageFiltersMatchAll Filters;
Vedant Kumar46103672016-09-22 21:49:47 +0000120
121 /// The path to the indexed profile.
122 std::string PGOFilename;
123
124 /// A list of input source files.
Vedant Kumarbc647982016-09-23 18:57:32 +0000125 std::vector<std::string> SourceFiles;
Vedant Kumar46103672016-09-22 21:49:47 +0000126
127 /// Whether or not we're in -filename-equivalence mode.
Alex Lorenze82d89c2014-08-22 22:56:03 +0000128 bool CompareFilenamesOnly;
Vedant Kumar46103672016-09-22 21:49:47 +0000129
130 /// In -filename-equivalence mode, this maps absolute paths from the
131 /// coverage mapping data to input source files.
Justin Bogner116c1662014-09-19 08:13:12 +0000132 StringMap<std::string> RemappedFilenames;
Vedant Kumar46103672016-09-22 21:49:47 +0000133
134 /// The architecture the coverage mapping data targets.
Frederic Rissebc162a2015-06-22 21:33:24 +0000135 std::string CoverageArch;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000136
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000137 /// A cache for demangled symbols.
138 DemangleCache DC;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000139
Vedant Kumarb6bfd472017-02-05 20:10:55 +0000140 /// A lock which guards printing to stderr.
Vedant Kumarb3020632016-07-18 17:53:12 +0000141 std::mutex ErrsLock;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000142
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000143 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000144 std::mutex LoadedSourceFilesLock;
145 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
146 LoadedSourceFiles;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000147};
148}
149
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000150static std::string getErrorString(const Twine &Message, StringRef Whence,
151 bool Warning) {
152 std::string Str = (Warning ? "warning" : "error");
153 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000154 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000155 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000156 Str += Message.str() + "\n";
157 return Str;
158}
159
160void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000161 std::unique_lock<std::mutex> Guard{ErrsLock};
162 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
163 << getErrorString(Message, Whence, false);
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000164}
165
Vedant Kumarb3020632016-07-18 17:53:12 +0000166void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
167 std::unique_lock<std::mutex> Guard{ErrsLock};
168 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
169 << getErrorString(Message, Whence, true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000170}
171
Vedant Kumarcef440f2016-06-28 16:12:18 +0000172void CodeCoverageTool::addCollectedPath(const std::string &Path) {
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000173 if (CompareFilenamesOnly) {
Vedant Kumarbc647982016-09-23 18:57:32 +0000174 SourceFiles.emplace_back(Path);
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000175 } else {
176 SmallString<128> EffectivePath(Path);
177 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
178 error(EC.message(), Path);
179 return;
180 }
181 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
Vedant Kumarbc647982016-09-23 18:57:32 +0000182 SourceFiles.emplace_back(EffectivePath.str());
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000183 }
Vedant Kumarcef440f2016-06-28 16:12:18 +0000184}
185
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000186void CodeCoverageTool::collectPaths(const std::string &Path) {
187 llvm::sys::fs::file_status Status;
188 llvm::sys::fs::status(Path, Status);
189 if (!llvm::sys::fs::exists(Status)) {
190 if (CompareFilenamesOnly)
191 addCollectedPath(Path);
192 else
193 error("Missing source file", Path);
194 return;
195 }
196
197 if (llvm::sys::fs::is_regular_file(Status)) {
198 addCollectedPath(Path);
199 return;
200 }
201
202 if (llvm::sys::fs::is_directory(Status)) {
203 std::error_code EC;
204 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
205 F != E && !EC; F.increment(EC)) {
206 if (llvm::sys::fs::is_regular_file(F->path()))
207 addCollectedPath(F->path());
208 }
209 if (EC)
210 warning(EC.message(), Path);
211 }
212}
213
Alex Lorenze82d89c2014-08-22 22:56:03 +0000214ErrorOr<const MemoryBuffer &>
215CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000216 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000217 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000218 if (!RemappedFilenames.empty()) {
219 auto Loc = RemappedFilenames.find(SourceFile);
220 if (Loc != RemappedFilenames.end())
221 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000222 }
Justin Bogner116c1662014-09-19 08:13:12 +0000223 for (const auto &Files : LoadedSourceFiles)
224 if (sys::fs::equivalent(SourceFile, Files.first))
225 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000226 auto Buffer = MemoryBuffer::getFile(SourceFile);
227 if (auto EC = Buffer.getError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000228 error(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000229 return EC;
230 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000231 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000232 return *LoadedSourceFiles.back().second;
233}
234
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000235void CodeCoverageTool::attachExpansionSubViews(
236 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
237 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000238 if (!ViewOpts.ShowExpandedRegions)
239 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000240 for (const auto &Expansion : Expansions) {
241 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
242 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000243 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000244 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
245 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000246 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000247
248 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000249 auto SubView =
250 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
251 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000252 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
253 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000254 }
255}
256
Justin Bogner5a6edad2014-09-19 19:07:17 +0000257std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000258CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000259 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000260 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
261 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000262 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000263 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000264 if (!SourceBuffer)
265 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000266
267 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000268 auto View = SourceCoverageView::create(DC.demangle(Function.Name),
Vedant Kumar0053c0b2016-09-08 00:56:48 +0000269 SourceBuffer.get(), ViewOpts,
270 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000271 attachExpansionSubViews(*View, Expansions, Coverage);
272
273 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000274}
275
Justin Bogner953e2402014-09-20 15:31:56 +0000276std::unique_ptr<SourceCoverageView>
277CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000278 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000279 auto SourceBuffer = getSourceFile(SourceFile);
280 if (!SourceBuffer)
281 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000282 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
283 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000284 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000285
286 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000287 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
288 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000289 attachExpansionSubViews(*View, Expansions, Coverage);
290
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000291 for (const auto *Function : Coverage.getInstantiations(SourceFile)) {
Vedant Kumara8c396d2016-09-15 06:44:51 +0000292 std::unique_ptr<SourceCoverageView> SubView{nullptr};
Justin Bogner953e2402014-09-20 15:31:56 +0000293
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000294 StringRef Funcname = DC.demangle(Function->Name);
Vedant Kumare9079772016-09-20 21:27:48 +0000295
Vedant Kumara8c396d2016-09-15 06:44:51 +0000296 if (Function->ExecutionCount > 0) {
297 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
298 auto SubViewExpansions = SubViewCoverage.getExpansions();
299 SubView = SourceCoverageView::create(
Vedant Kumare9079772016-09-20 21:27:48 +0000300 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
Vedant Kumara8c396d2016-09-15 06:44:51 +0000301 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000302 }
Vedant Kumara8c396d2016-09-15 06:44:51 +0000303
304 unsigned FileID = Function->CountedRegions.front().FileID;
305 unsigned Line = 0;
306 for (const auto &CR : Function->CountedRegions)
307 if (CR.FileID == FileID)
308 Line = std::max(CR.LineEnd, Line);
Vedant Kumare9079772016-09-20 21:27:48 +0000309 View->addInstantiation(Funcname, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000310 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000311 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000312}
313
Justin Bogner65337d12015-05-04 04:09:38 +0000314static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
315 sys::fs::file_status Status;
316 if (sys::fs::status(LHS, Status))
317 return false;
318 auto LHSTime = Status.getLastModificationTime();
319 if (sys::fs::status(RHS, Status))
320 return false;
321 auto RHSTime = Status.getLastModificationTime();
322 return LHSTime > RHSTime;
323}
324
Justin Bogner953e2402014-09-20 15:31:56 +0000325std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000326 for (StringRef ObjectFilename : ObjectFilenames)
327 if (modifiedTimeGT(ObjectFilename, PGOFilename))
328 warning("profile data may be out of date - object is newer",
329 ObjectFilename);
Vedant Kumarb3020632016-07-18 17:53:12 +0000330 auto CoverageOrErr =
Vedant Kumara3661ef2016-10-25 17:40:55 +0000331 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000332 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000333 error("Failed to load coverage: " + toString(std::move(E)),
334 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
Justin Bogner953e2402014-09-20 15:31:56 +0000335 return nullptr;
336 }
337 auto Coverage = std::move(CoverageOrErr.get());
338 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumarb3020632016-07-18 17:53:12 +0000339 if (Mismatched)
340 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000341
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000342 if (!SourceFiles.empty())
343 removeUnmappedInputs(*Coverage);
344
345 demangleSymbols(*Coverage);
346
347 return Coverage;
348}
349
350void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
351 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
Vedant Kumar458808802016-09-23 18:57:35 +0000352
353 auto UncoveredFilesIt = SourceFiles.end();
354 if (!CompareFilenamesOnly) {
355 // The user may have specified source files which aren't in the coverage
356 // mapping. Filter these files away.
357 UncoveredFilesIt = std::remove_if(
358 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
359 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
360 SF);
361 });
362 } else {
Justin Bogner116c1662014-09-19 08:13:12 +0000363 for (auto &SF : SourceFiles) {
364 StringRef SFBase = sys::path::filename(SF);
Vedant Kumar458808802016-09-23 18:57:35 +0000365 for (const auto &CF : CoveredFiles) {
Justin Bogner116c1662014-09-19 08:13:12 +0000366 if (SFBase == sys::path::filename(CF)) {
367 RemappedFilenames[CF] = SF;
368 SF = CF;
369 break;
370 }
Vedant Kumar458808802016-09-23 18:57:35 +0000371 }
Justin Bogner116c1662014-09-19 08:13:12 +0000372 }
Vedant Kumar458808802016-09-23 18:57:35 +0000373 UncoveredFilesIt = std::remove_if(
374 SourceFiles.begin(), SourceFiles.end(),
375 [&](const std::string &SF) { return !RemappedFilenames.count(SF); });
Justin Bogner116c1662014-09-19 08:13:12 +0000376 }
377
Vedant Kumar458808802016-09-23 18:57:35 +0000378 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000379}
380
Vedant Kumar424f51b2016-07-15 22:44:57 +0000381void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
382 if (!ViewOpts.hasDemangler())
383 return;
384
385 // Pass function names to the demangler in a temporary file.
386 int InputFD;
387 SmallString<256> InputPath;
388 std::error_code EC =
389 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
390 if (EC) {
391 error(InputPath, EC.message());
392 return;
393 }
394 tool_output_file InputTOF{InputPath, InputFD};
395
396 unsigned NumSymbols = 0;
397 for (const auto &Function : Coverage.getCoveredFunctions()) {
398 InputTOF.os() << Function.Name << '\n';
399 ++NumSymbols;
400 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000401 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000402
403 // Use another temporary file to store the demangler's output.
404 int OutputFD;
405 SmallString<256> OutputPath;
406 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
407 OutputPath);
408 if (EC) {
409 error(OutputPath, EC.message());
410 return;
411 }
412 tool_output_file OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000413 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000414
415 // Invoke the demangler.
416 std::vector<const char *> ArgsV;
417 for (const std::string &Arg : ViewOpts.DemanglerOpts)
418 ArgsV.push_back(Arg.c_str());
419 ArgsV.push_back(nullptr);
Vedant Kumar38202c02016-07-15 23:15:35 +0000420 StringRef InputPathRef = InputPath.str();
421 StringRef OutputPathRef = OutputPath.str();
422 StringRef StderrRef;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000423 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
424 std::string ErrMsg;
425 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
426 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
427 /*memoryLimit=*/0, &ErrMsg);
428 if (RC) {
429 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
430 return;
431 }
432
433 // Parse the demangler's output.
434 auto BufOrError = MemoryBuffer::getFile(OutputPath);
435 if (!BufOrError) {
436 error(OutputPath, BufOrError.getError().message());
437 return;
438 }
439
440 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
441
442 SmallVector<StringRef, 8> Symbols;
443 StringRef DemanglerData = DemanglerBuf->getBuffer();
444 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
445 /*KeepEmpty=*/false);
446 if (Symbols.size() != NumSymbols) {
447 error("Demangler did not provide expected number of symbols");
448 return;
449 }
450
451 // Cache the demangled names.
452 unsigned I = 0;
453 for (const auto &Function : Coverage.getCoveredFunctions())
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000454 DC.DemangledNames[Function.Name] = Symbols[I++];
Vedant Kumar424f51b2016-07-15 22:44:57 +0000455}
456
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000457void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
458 CoverageMapping *Coverage,
459 CoveragePrinter *Printer,
460 bool ShowFilenames) {
461 auto View = createSourceFileView(SourceFile, *Coverage);
462 if (!View) {
463 warning("The file '" + SourceFile + "' isn't covered.");
464 return;
465 }
466
467 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
468 if (Error E = OSOrErr.takeError()) {
469 error("Could not create view file!", toString(std::move(E)));
470 return;
471 }
472 auto OS = std::move(OSOrErr.get());
473
474 View->print(*OS.get(), /*Wholefile=*/true,
475 /*ShowSourceName=*/ShowFilenames);
476 Printer->closeViewFile(std::move(OS));
477}
478
Alex Lorenze82d89c2014-08-22 22:56:03 +0000479int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000480 cl::opt<std::string> CovFilename(
481 cl::Positional, cl::desc("Covered executable or object file."));
482
483 cl::list<std::string> CovFilenames(
484 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
485 cl::CommaSeparated);
Justin Bognerf6c50552014-10-30 20:51:24 +0000486
Alex Lorenze82d89c2014-08-22 22:56:03 +0000487 cl::list<std::string> InputSourceFiles(
488 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
489
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000490 cl::opt<bool> DebugDumpCollectedPaths(
491 "dump-collected-paths", cl::Optional, cl::Hidden,
492 cl::desc("Show the collected paths to source files"));
493
Justin Bogner953e2402014-09-20 15:31:56 +0000494 cl::opt<std::string, true> PGOFilename(
495 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000496 cl::desc(
497 "File with the profile data obtained after an instrumented run"));
498
Justin Bogner43795352015-03-11 02:30:51 +0000499 cl::opt<std::string> Arch(
500 "arch", cl::desc("architecture of the coverage mapping binary"));
501
Alex Lorenze82d89c2014-08-22 22:56:03 +0000502 cl::opt<bool> DebugDump("dump", cl::Optional,
503 cl::desc("Show internal debug dump"));
504
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000505 cl::opt<CoverageViewOptions::OutputFormat> Format(
506 "format", cl::desc("Output format for line-based coverage reports"),
507 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
508 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000509 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000510 "HTML output")),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000511 cl::init(CoverageViewOptions::OutputFormat::Text));
512
Alex Lorenze82d89c2014-08-22 22:56:03 +0000513 cl::opt<bool> FilenameEquivalence(
514 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000515 cl::desc("Treat source files as equivalent to paths in the coverage data "
516 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000517
518 cl::OptionCategory FilteringCategory("Function filtering options");
519
520 cl::list<std::string> NameFilters(
521 "name", cl::Optional,
522 cl::desc("Show code coverage only for functions with the given name"),
523 cl::ZeroOrMore, cl::cat(FilteringCategory));
524
525 cl::list<std::string> NameRegexFilters(
526 "name-regex", cl::Optional,
527 cl::desc("Show code coverage only for functions that match the given "
528 "regular expression"),
529 cl::ZeroOrMore, cl::cat(FilteringCategory));
530
531 cl::opt<double> RegionCoverageLtFilter(
532 "region-coverage-lt", cl::Optional,
533 cl::desc("Show code coverage only for functions with region coverage "
534 "less than the given threshold"),
535 cl::cat(FilteringCategory));
536
537 cl::opt<double> RegionCoverageGtFilter(
538 "region-coverage-gt", cl::Optional,
539 cl::desc("Show code coverage only for functions with region coverage "
540 "greater than the given threshold"),
541 cl::cat(FilteringCategory));
542
543 cl::opt<double> LineCoverageLtFilter(
544 "line-coverage-lt", cl::Optional,
545 cl::desc("Show code coverage only for functions with line coverage less "
546 "than the given threshold"),
547 cl::cat(FilteringCategory));
548
549 cl::opt<double> LineCoverageGtFilter(
550 "line-coverage-gt", cl::Optional,
551 cl::desc("Show code coverage only for functions with line coverage "
552 "greater than the given threshold"),
553 cl::cat(FilteringCategory));
554
Justin Bogner9deb1d42015-03-19 04:45:16 +0000555 cl::opt<cl::boolOrDefault> UseColor(
556 "use-color", cl::desc("Emit colored output (default=autodetect)"),
557 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000558
Vedant Kumar424f51b2016-07-15 22:44:57 +0000559 cl::list<std::string> DemanglerOpts(
560 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
561
Alex Lorenze82d89c2014-08-22 22:56:03 +0000562 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
563 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
564 ViewOpts.Debug = DebugDump;
565 CompareFilenamesOnly = FilenameEquivalence;
566
Vedant Kumara3661ef2016-10-25 17:40:55 +0000567 if (!CovFilename.empty())
568 ObjectFilenames.emplace_back(CovFilename);
569 for (const std::string &Filename : CovFilenames)
570 ObjectFilenames.emplace_back(Filename);
571 if (ObjectFilenames.empty()) {
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000572 errs() << "No filenames specified!\n";
Vedant Kumara3661ef2016-10-25 17:40:55 +0000573 ::exit(1);
574 }
575
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000576 ViewOpts.Format = Format;
577 switch (ViewOpts.Format) {
578 case CoverageViewOptions::OutputFormat::Text:
579 ViewOpts.Colors = UseColor == cl::BOU_UNSET
580 ? sys::Process::StandardOutHasColors()
581 : UseColor == cl::BOU_TRUE;
582 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000583 case CoverageViewOptions::OutputFormat::HTML:
584 if (UseColor == cl::BOU_FALSE)
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000585 errs() << "Color output cannot be disabled when generating html.\n";
Vedant Kumar4c010922016-07-06 21:44:05 +0000586 ViewOpts.Colors = true;
587 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000588 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000589
Vedant Kumar424f51b2016-07-15 22:44:57 +0000590 // If a demangler is supplied, check if it exists and register it.
591 if (DemanglerOpts.size()) {
592 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
593 if (!DemanglerPathOrErr) {
594 error("Could not find the demangler!",
595 DemanglerPathOrErr.getError().message());
596 return 1;
597 }
598 DemanglerOpts[0] = *DemanglerPathOrErr;
599 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
600 }
601
Alex Lorenze82d89c2014-08-22 22:56:03 +0000602 // Create the function filters
603 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
604 auto NameFilterer = new CoverageFilters;
605 for (const auto &Name : NameFilters)
606 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
607 for (const auto &Regex : NameRegexFilters)
608 NameFilterer->push_back(
609 llvm::make_unique<NameRegexCoverageFilter>(Regex));
610 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
611 }
612 if (RegionCoverageLtFilter.getNumOccurrences() ||
613 RegionCoverageGtFilter.getNumOccurrences() ||
614 LineCoverageLtFilter.getNumOccurrences() ||
615 LineCoverageGtFilter.getNumOccurrences()) {
616 auto StatFilterer = new CoverageFilters;
617 if (RegionCoverageLtFilter.getNumOccurrences())
618 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
619 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
620 if (RegionCoverageGtFilter.getNumOccurrences())
621 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
622 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
623 if (LineCoverageLtFilter.getNumOccurrences())
624 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
625 LineCoverageFilter::LessThan, LineCoverageLtFilter));
626 if (LineCoverageGtFilter.getNumOccurrences())
627 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
628 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
629 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
630 }
631
Frederic Rissebc162a2015-06-22 21:33:24 +0000632 if (!Arch.empty() &&
633 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000634 error("Unknown architecture: " + Arch);
Frederic Rissebc162a2015-06-22 21:33:24 +0000635 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000636 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000637 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000638
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000639 for (const std::string &File : InputSourceFiles)
640 collectPaths(File);
641
642 if (DebugDumpCollectedPaths) {
Vedant Kumarbc647982016-09-23 18:57:32 +0000643 for (const std::string &SF : SourceFiles)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000644 outs() << SF << '\n';
645 ::exit(0);
Justin Bogner116c1662014-09-19 08:13:12 +0000646 }
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000647
Alex Lorenze82d89c2014-08-22 22:56:03 +0000648 return 0;
649 };
650
Alex Lorenze82d89c2014-08-22 22:56:03 +0000651 switch (Cmd) {
652 case Show:
653 return show(argc, argv, commandLineParser);
654 case Report:
655 return report(argc, argv, commandLineParser);
Vedant Kumar7101d732016-07-26 22:50:58 +0000656 case Export:
657 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000658 }
659 return 0;
660}
661
662int CodeCoverageTool::show(int argc, const char **argv,
663 CommandLineParserType commandLineParser) {
664
665 cl::OptionCategory ViewCategory("Viewing options");
666
667 cl::opt<bool> ShowLineExecutionCounts(
668 "show-line-counts", cl::Optional,
669 cl::desc("Show the execution counts for each line"), cl::init(true),
670 cl::cat(ViewCategory));
671
672 cl::opt<bool> ShowRegions(
673 "show-regions", cl::Optional,
674 cl::desc("Show the execution counts for each region"),
675 cl::cat(ViewCategory));
676
677 cl::opt<bool> ShowBestLineRegionsCounts(
678 "show-line-counts-or-regions", cl::Optional,
679 cl::desc("Show the execution counts for each line, or the execution "
680 "counts for each region on lines that have multiple regions"),
681 cl::cat(ViewCategory));
682
683 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
684 cl::desc("Show expanded source regions"),
685 cl::cat(ViewCategory));
686
687 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
688 cl::desc("Show function instantiations"),
689 cl::cat(ViewCategory));
690
Vedant Kumar7937ef32016-06-28 02:09:39 +0000691 cl::opt<std::string> ShowOutputDirectory(
692 "output-dir", cl::init(""),
693 cl::desc("Directory in which coverage information is written out"));
694 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
695 cl::aliasopt(ShowOutputDirectory));
696
Ying Yi0ef31b72016-08-04 10:39:43 +0000697 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000698 "tab-size", cl::init(2),
699 cl::desc(
700 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000701
Ying Yi84dc9712016-08-24 14:27:23 +0000702 cl::opt<std::string> ProjectTitle(
703 "project-title", cl::Optional,
704 cl::desc("Set project title for the coverage report"));
705
Alex Lorenze82d89c2014-08-22 22:56:03 +0000706 auto Err = commandLineParser(argc, argv);
707 if (Err)
708 return Err;
709
Alex Lorenze82d89c2014-08-22 22:56:03 +0000710 ViewOpts.ShowLineNumbers = true;
711 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
712 !ShowRegions || ShowBestLineRegionsCounts;
713 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
714 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
715 ViewOpts.ShowExpandedRegions = ShowExpansions;
716 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000717 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000718 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000719 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000720
Vedant Kumar64d8a022016-06-28 16:12:20 +0000721 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000722 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
723 error("Could not create output directory!", E.message());
724 return 1;
725 }
726 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000727
Ying Yi84dc9712016-08-24 14:27:23 +0000728 sys::fs::file_status Status;
729 if (sys::fs::status(PGOFilename, Status)) {
730 error("profdata file error: can not get the file status. \n");
731 return 1;
732 }
733
734 auto ModifiedTime = Status.getLastModificationTime();
Pavel Labath757ca882016-10-24 10:59:17 +0000735 std::string ModifiedTimeStr = to_string(ModifiedTime);
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000736 size_t found = ModifiedTimeStr.rfind(':');
Ying Yi84dc9712016-08-24 14:27:23 +0000737 ViewOpts.CreatedTimeStr = (found != std::string::npos)
738 ? "Created: " + ModifiedTimeStr.substr(0, found)
739 : "Created: " + ModifiedTimeStr;
740
Justin Bogner953e2402014-09-20 15:31:56 +0000741 auto Coverage = load();
742 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000743 return 1;
744
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000745 auto Printer = CoveragePrinter::create(ViewOpts);
746
Alex Lorenze82d89c2014-08-22 22:56:03 +0000747 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000748 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
749 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000750 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000751 return 1;
752 }
753 auto OS = std::move(OSOrErr.get());
754
755 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000756 for (const auto &Function : Coverage->getCoveredFunctions()) {
757 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000758 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000759
760 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000761 if (!mainView) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000762 warning("Could not read coverage for '" + Function.Name + "'.");
Justin Bogner5a6edad2014-09-19 19:07:17 +0000763 continue;
764 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000765
Vedant Kumar7937ef32016-06-28 02:09:39 +0000766 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000767 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000768
769 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000770 return 0;
771 }
772
773 // Show files
Ying Yi84dc9712016-08-24 14:27:23 +0000774 bool ShowFilenames =
Ying Yi24e91bd2016-09-06 21:41:38 +0000775 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
Ying Yi84dc9712016-08-24 14:27:23 +0000776 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000777
Justin Bogner116c1662014-09-19 08:13:12 +0000778 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000779 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000780 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000781 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000782
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000783 // Create an index out of the source files.
784 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumara59334d2016-09-09 01:32:55 +0000785 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000786 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000787 return 1;
788 }
789 }
790
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000791 // FIXME: Sink the hardware_concurrency() == 1 check into ThreadPool.
792 if (!ViewOpts.hasOutputDirectory() ||
793 std::thread::hardware_concurrency() == 1) {
794 for (const std::string &SourceFile : SourceFiles)
795 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
796 ShowFilenames);
797 } else {
798 // In -output-dir mode, it's safe to use multiple threads to print files.
799 ThreadPool Pool;
800 for (const std::string &SourceFile : SourceFiles)
801 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
802 Coverage.get(), Printer.get(), ShowFilenames);
803 Pool.wait();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000804 }
805
806 return 0;
807}
808
809int CodeCoverageTool::report(int argc, const char **argv,
810 CommandLineParserType commandLineParser) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000811 auto Err = commandLineParser(argc, argv);
812 if (Err)
813 return Err;
814
Vedant Kumar4c010922016-07-06 21:44:05 +0000815 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
816 error("HTML output for summary reports is not yet supported.");
817
Justin Bogner953e2402014-09-20 15:31:56 +0000818 auto Coverage = load();
819 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000820 return 1;
821
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000822 CoverageReport Report(ViewOpts, *Coverage.get());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000823 if (SourceFiles.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000824 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000825 else
826 Report.renderFunctionReports(SourceFiles, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000827 return 0;
828}
829
Vedant Kumar7101d732016-07-26 22:50:58 +0000830int CodeCoverageTool::export_(int argc, const char **argv,
831 CommandLineParserType commandLineParser) {
832
833 auto Err = commandLineParser(argc, argv);
834 if (Err)
835 return Err;
836
837 auto Coverage = load();
838 if (!Coverage) {
839 error("Could not load coverage information");
840 return 1;
841 }
842
Vedant Kumar5c61c702016-10-25 00:08:33 +0000843 exportCoverageDataToJson(*Coverage.get(), outs());
Vedant Kumar7101d732016-07-26 22:50:58 +0000844
845 return 0;
846}
847
Justin Bognerd249a3b2014-10-30 20:57:49 +0000848int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000849 CodeCoverageTool Tool;
850 return Tool.run(CodeCoverageTool::Show, argc, argv);
851}
852
Justin Bognerd249a3b2014-10-30 20:57:49 +0000853int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000854 CodeCoverageTool Tool;
855 return Tool.run(CodeCoverageTool::Report, argc, argv);
856}
Vedant Kumar7101d732016-07-26 22:50:58 +0000857
858int exportMain(int argc, const char *argv[]) {
859 CodeCoverageTool Tool;
860 return Tool.run(CodeCoverageTool::Export, argc, argv);
861}