blob: 781d1948ccd02211702b190ba403a83fa4931159 [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())
Igor Kudrin9e015da2017-02-19 14:26:52 +0000454 // On Windows, lines in the demangler's output file end with "\r\n".
455 // Splitting by '\n' keeps '\r's, so cut them now.
456 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000457}
458
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000459void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
460 CoverageMapping *Coverage,
461 CoveragePrinter *Printer,
462 bool ShowFilenames) {
463 auto View = createSourceFileView(SourceFile, *Coverage);
464 if (!View) {
465 warning("The file '" + SourceFile + "' isn't covered.");
466 return;
467 }
468
469 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
470 if (Error E = OSOrErr.takeError()) {
471 error("Could not create view file!", toString(std::move(E)));
472 return;
473 }
474 auto OS = std::move(OSOrErr.get());
475
476 View->print(*OS.get(), /*Wholefile=*/true,
477 /*ShowSourceName=*/ShowFilenames);
478 Printer->closeViewFile(std::move(OS));
479}
480
Alex Lorenze82d89c2014-08-22 22:56:03 +0000481int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000482 cl::opt<std::string> CovFilename(
483 cl::Positional, cl::desc("Covered executable or object file."));
484
485 cl::list<std::string> CovFilenames(
486 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
487 cl::CommaSeparated);
Justin Bognerf6c50552014-10-30 20:51:24 +0000488
Alex Lorenze82d89c2014-08-22 22:56:03 +0000489 cl::list<std::string> InputSourceFiles(
490 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
491
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000492 cl::opt<bool> DebugDumpCollectedPaths(
493 "dump-collected-paths", cl::Optional, cl::Hidden,
494 cl::desc("Show the collected paths to source files"));
495
Justin Bogner953e2402014-09-20 15:31:56 +0000496 cl::opt<std::string, true> PGOFilename(
497 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000498 cl::desc(
499 "File with the profile data obtained after an instrumented run"));
500
Justin Bogner43795352015-03-11 02:30:51 +0000501 cl::opt<std::string> Arch(
502 "arch", cl::desc("architecture of the coverage mapping binary"));
503
Alex Lorenze82d89c2014-08-22 22:56:03 +0000504 cl::opt<bool> DebugDump("dump", cl::Optional,
505 cl::desc("Show internal debug dump"));
506
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000507 cl::opt<CoverageViewOptions::OutputFormat> Format(
508 "format", cl::desc("Output format for line-based coverage reports"),
509 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
510 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000511 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000512 "HTML output")),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000513 cl::init(CoverageViewOptions::OutputFormat::Text));
514
Alex Lorenze82d89c2014-08-22 22:56:03 +0000515 cl::opt<bool> FilenameEquivalence(
516 "filename-equivalence", cl::Optional,
Justin Bogner116c1662014-09-19 08:13:12 +0000517 cl::desc("Treat source files as equivalent to paths in the coverage data "
518 "when the file names match, even if the full paths do not"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000519
520 cl::OptionCategory FilteringCategory("Function filtering options");
521
522 cl::list<std::string> NameFilters(
523 "name", cl::Optional,
524 cl::desc("Show code coverage only for functions with the given name"),
525 cl::ZeroOrMore, cl::cat(FilteringCategory));
526
527 cl::list<std::string> NameRegexFilters(
528 "name-regex", cl::Optional,
529 cl::desc("Show code coverage only for functions that match the given "
530 "regular expression"),
531 cl::ZeroOrMore, cl::cat(FilteringCategory));
532
533 cl::opt<double> RegionCoverageLtFilter(
534 "region-coverage-lt", cl::Optional,
535 cl::desc("Show code coverage only for functions with region coverage "
536 "less than the given threshold"),
537 cl::cat(FilteringCategory));
538
539 cl::opt<double> RegionCoverageGtFilter(
540 "region-coverage-gt", cl::Optional,
541 cl::desc("Show code coverage only for functions with region coverage "
542 "greater than the given threshold"),
543 cl::cat(FilteringCategory));
544
545 cl::opt<double> LineCoverageLtFilter(
546 "line-coverage-lt", cl::Optional,
547 cl::desc("Show code coverage only for functions with line coverage less "
548 "than the given threshold"),
549 cl::cat(FilteringCategory));
550
551 cl::opt<double> LineCoverageGtFilter(
552 "line-coverage-gt", cl::Optional,
553 cl::desc("Show code coverage only for functions with line coverage "
554 "greater than the given threshold"),
555 cl::cat(FilteringCategory));
556
Justin Bogner9deb1d42015-03-19 04:45:16 +0000557 cl::opt<cl::boolOrDefault> UseColor(
558 "use-color", cl::desc("Emit colored output (default=autodetect)"),
559 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000560
Vedant Kumar424f51b2016-07-15 22:44:57 +0000561 cl::list<std::string> DemanglerOpts(
562 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
563
Alex Lorenze82d89c2014-08-22 22:56:03 +0000564 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
565 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
566 ViewOpts.Debug = DebugDump;
567 CompareFilenamesOnly = FilenameEquivalence;
568
Vedant Kumara3661ef2016-10-25 17:40:55 +0000569 if (!CovFilename.empty())
570 ObjectFilenames.emplace_back(CovFilename);
571 for (const std::string &Filename : CovFilenames)
572 ObjectFilenames.emplace_back(Filename);
573 if (ObjectFilenames.empty()) {
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000574 errs() << "No filenames specified!\n";
Vedant Kumara3661ef2016-10-25 17:40:55 +0000575 ::exit(1);
576 }
577
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000578 ViewOpts.Format = Format;
579 switch (ViewOpts.Format) {
580 case CoverageViewOptions::OutputFormat::Text:
581 ViewOpts.Colors = UseColor == cl::BOU_UNSET
582 ? sys::Process::StandardOutHasColors()
583 : UseColor == cl::BOU_TRUE;
584 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000585 case CoverageViewOptions::OutputFormat::HTML:
586 if (UseColor == cl::BOU_FALSE)
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000587 errs() << "Color output cannot be disabled when generating html.\n";
Vedant Kumar4c010922016-07-06 21:44:05 +0000588 ViewOpts.Colors = true;
589 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000590 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000591
Vedant Kumar424f51b2016-07-15 22:44:57 +0000592 // If a demangler is supplied, check if it exists and register it.
593 if (DemanglerOpts.size()) {
594 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
595 if (!DemanglerPathOrErr) {
596 error("Could not find the demangler!",
597 DemanglerPathOrErr.getError().message());
598 return 1;
599 }
600 DemanglerOpts[0] = *DemanglerPathOrErr;
601 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
602 }
603
Alex Lorenze82d89c2014-08-22 22:56:03 +0000604 // Create the function filters
605 if (!NameFilters.empty() || !NameRegexFilters.empty()) {
606 auto NameFilterer = new CoverageFilters;
607 for (const auto &Name : NameFilters)
608 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
609 for (const auto &Regex : NameRegexFilters)
610 NameFilterer->push_back(
611 llvm::make_unique<NameRegexCoverageFilter>(Regex));
612 Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer));
613 }
614 if (RegionCoverageLtFilter.getNumOccurrences() ||
615 RegionCoverageGtFilter.getNumOccurrences() ||
616 LineCoverageLtFilter.getNumOccurrences() ||
617 LineCoverageGtFilter.getNumOccurrences()) {
618 auto StatFilterer = new CoverageFilters;
619 if (RegionCoverageLtFilter.getNumOccurrences())
620 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
621 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
622 if (RegionCoverageGtFilter.getNumOccurrences())
623 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
624 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
625 if (LineCoverageLtFilter.getNumOccurrences())
626 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
627 LineCoverageFilter::LessThan, LineCoverageLtFilter));
628 if (LineCoverageGtFilter.getNumOccurrences())
629 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
630 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
631 Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer));
632 }
633
Frederic Rissebc162a2015-06-22 21:33:24 +0000634 if (!Arch.empty() &&
635 Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000636 error("Unknown architecture: " + Arch);
Frederic Rissebc162a2015-06-22 21:33:24 +0000637 return 1;
Justin Bogner43795352015-03-11 02:30:51 +0000638 }
Frederic Rissebc162a2015-06-22 21:33:24 +0000639 CoverageArch = Arch;
Justin Bogner43795352015-03-11 02:30:51 +0000640
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000641 for (const std::string &File : InputSourceFiles)
642 collectPaths(File);
643
644 if (DebugDumpCollectedPaths) {
Vedant Kumarbc647982016-09-23 18:57:32 +0000645 for (const std::string &SF : SourceFiles)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000646 outs() << SF << '\n';
647 ::exit(0);
Justin Bogner116c1662014-09-19 08:13:12 +0000648 }
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000649
Alex Lorenze82d89c2014-08-22 22:56:03 +0000650 return 0;
651 };
652
Alex Lorenze82d89c2014-08-22 22:56:03 +0000653 switch (Cmd) {
654 case Show:
655 return show(argc, argv, commandLineParser);
656 case Report:
657 return report(argc, argv, commandLineParser);
Vedant Kumar7101d732016-07-26 22:50:58 +0000658 case Export:
659 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000660 }
661 return 0;
662}
663
664int CodeCoverageTool::show(int argc, const char **argv,
665 CommandLineParserType commandLineParser) {
666
667 cl::OptionCategory ViewCategory("Viewing options");
668
669 cl::opt<bool> ShowLineExecutionCounts(
670 "show-line-counts", cl::Optional,
671 cl::desc("Show the execution counts for each line"), cl::init(true),
672 cl::cat(ViewCategory));
673
674 cl::opt<bool> ShowRegions(
675 "show-regions", cl::Optional,
676 cl::desc("Show the execution counts for each region"),
677 cl::cat(ViewCategory));
678
679 cl::opt<bool> ShowBestLineRegionsCounts(
680 "show-line-counts-or-regions", cl::Optional,
681 cl::desc("Show the execution counts for each line, or the execution "
682 "counts for each region on lines that have multiple regions"),
683 cl::cat(ViewCategory));
684
685 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
686 cl::desc("Show expanded source regions"),
687 cl::cat(ViewCategory));
688
689 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
690 cl::desc("Show function instantiations"),
691 cl::cat(ViewCategory));
692
Vedant Kumar7937ef32016-06-28 02:09:39 +0000693 cl::opt<std::string> ShowOutputDirectory(
694 "output-dir", cl::init(""),
695 cl::desc("Directory in which coverage information is written out"));
696 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
697 cl::aliasopt(ShowOutputDirectory));
698
Ying Yi0ef31b72016-08-04 10:39:43 +0000699 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000700 "tab-size", cl::init(2),
701 cl::desc(
702 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000703
Ying Yi84dc9712016-08-24 14:27:23 +0000704 cl::opt<std::string> ProjectTitle(
705 "project-title", cl::Optional,
706 cl::desc("Set project title for the coverage report"));
707
Alex Lorenze82d89c2014-08-22 22:56:03 +0000708 auto Err = commandLineParser(argc, argv);
709 if (Err)
710 return Err;
711
Alex Lorenze82d89c2014-08-22 22:56:03 +0000712 ViewOpts.ShowLineNumbers = true;
713 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
714 !ShowRegions || ShowBestLineRegionsCounts;
715 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
716 ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts;
717 ViewOpts.ShowExpandedRegions = ShowExpansions;
718 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000719 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000720 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000721 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000722
Vedant Kumar64d8a022016-06-28 16:12:20 +0000723 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000724 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
725 error("Could not create output directory!", E.message());
726 return 1;
727 }
728 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000729
Ying Yi84dc9712016-08-24 14:27:23 +0000730 sys::fs::file_status Status;
731 if (sys::fs::status(PGOFilename, Status)) {
732 error("profdata file error: can not get the file status. \n");
733 return 1;
734 }
735
736 auto ModifiedTime = Status.getLastModificationTime();
Pavel Labath757ca882016-10-24 10:59:17 +0000737 std::string ModifiedTimeStr = to_string(ModifiedTime);
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000738 size_t found = ModifiedTimeStr.rfind(':');
Ying Yi84dc9712016-08-24 14:27:23 +0000739 ViewOpts.CreatedTimeStr = (found != std::string::npos)
740 ? "Created: " + ModifiedTimeStr.substr(0, found)
741 : "Created: " + ModifiedTimeStr;
742
Justin Bogner953e2402014-09-20 15:31:56 +0000743 auto Coverage = load();
744 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000745 return 1;
746
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000747 auto Printer = CoveragePrinter::create(ViewOpts);
748
Alex Lorenze82d89c2014-08-22 22:56:03 +0000749 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000750 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
751 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000752 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000753 return 1;
754 }
755 auto OS = std::move(OSOrErr.get());
756
757 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000758 for (const auto &Function : Coverage->getCoveredFunctions()) {
759 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000760 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000761
762 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000763 if (!mainView) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000764 warning("Could not read coverage for '" + Function.Name + "'.");
Justin Bogner5a6edad2014-09-19 19:07:17 +0000765 continue;
766 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000767
Vedant Kumar7937ef32016-06-28 02:09:39 +0000768 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000769 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000770
771 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000772 return 0;
773 }
774
775 // Show files
Ying Yi84dc9712016-08-24 14:27:23 +0000776 bool ShowFilenames =
Ying Yi24e91bd2016-09-06 21:41:38 +0000777 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
Ying Yi84dc9712016-08-24 14:27:23 +0000778 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000779
Justin Bogner116c1662014-09-19 08:13:12 +0000780 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000781 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000782 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000783 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000784
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000785 // Create an index out of the source files.
786 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumara59334d2016-09-09 01:32:55 +0000787 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000788 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000789 return 1;
790 }
791 }
792
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000793 // FIXME: Sink the hardware_concurrency() == 1 check into ThreadPool.
794 if (!ViewOpts.hasOutputDirectory() ||
795 std::thread::hardware_concurrency() == 1) {
796 for (const std::string &SourceFile : SourceFiles)
797 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
798 ShowFilenames);
799 } else {
800 // In -output-dir mode, it's safe to use multiple threads to print files.
801 ThreadPool Pool;
802 for (const std::string &SourceFile : SourceFiles)
803 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
804 Coverage.get(), Printer.get(), ShowFilenames);
805 Pool.wait();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000806 }
807
808 return 0;
809}
810
811int CodeCoverageTool::report(int argc, const char **argv,
812 CommandLineParserType commandLineParser) {
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000813 cl::opt<bool> ShowFunctionSummaries(
814 "show-functions", cl::Optional, cl::init(false),
815 cl::desc("Show coverage summaries for each function"));
816
Alex Lorenze82d89c2014-08-22 22:56:03 +0000817 auto Err = commandLineParser(argc, argv);
818 if (Err)
819 return Err;
820
Vedant Kumar4c010922016-07-06 21:44:05 +0000821 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)
822 error("HTML output for summary reports is not yet supported.");
823
Justin Bogner953e2402014-09-20 15:31:56 +0000824 auto Coverage = load();
825 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000826 return 1;
827
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000828 CoverageReport Report(ViewOpts, *Coverage.get());
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000829 if (!ShowFunctionSummaries)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000830 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000831 else
Vedant Kumarf2b067c2017-02-05 20:11:03 +0000832 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000833 return 0;
834}
835
Vedant Kumar7101d732016-07-26 22:50:58 +0000836int CodeCoverageTool::export_(int argc, const char **argv,
837 CommandLineParserType commandLineParser) {
838
839 auto Err = commandLineParser(argc, argv);
840 if (Err)
841 return Err;
842
843 auto Coverage = load();
844 if (!Coverage) {
845 error("Could not load coverage information");
846 return 1;
847 }
848
Vedant Kumar5c61c702016-10-25 00:08:33 +0000849 exportCoverageDataToJson(*Coverage.get(), outs());
Vedant Kumar7101d732016-07-26 22:50:58 +0000850
851 return 0;
852}
853
Justin Bognerd249a3b2014-10-30 20:57:49 +0000854int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000855 CodeCoverageTool Tool;
856 return Tool.run(CodeCoverageTool::Show, argc, argv);
857}
858
Justin Bognerd249a3b2014-10-30 20:57:49 +0000859int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000860 CodeCoverageTool Tool;
861 return Tool.run(CodeCoverageTool::Report, argc, argv);
862}
Vedant Kumar7101d732016-07-26 22:50:58 +0000863
864int exportMain(int argc, const char *argv[]) {
865 CodeCoverageTool Tool;
866 return Tool.run(CodeCoverageTool::Export, argc, argv);
867}