blob: 1ea54a8cffd48484489cd7e14f45da1b74067d01 [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 Kumar72c3a112017-09-08 18:44:49 +000045 const CoverageViewOptions &Options,
Vedant Kumar7101d732016-07-26 22:50:58 +000046 raw_ostream &OS);
47
Alex Lorenze82d89c2014-08-22 22:56:03 +000048namespace {
Alex Lorenze82d89c2014-08-22 22:56:03 +000049/// \brief The implementation of the coverage tool.
50class CodeCoverageTool {
51public:
52 enum Command {
53 /// \brief The show command.
54 Show,
55 /// \brief The report command.
Vedant Kumar7101d732016-07-26 22:50:58 +000056 Report,
57 /// \brief The export command.
58 Export
Alex Lorenze82d89c2014-08-22 22:56:03 +000059 };
60
Vedant Kumar46103672016-09-22 21:49:47 +000061 int run(Command Cmd, int argc, const char **argv);
62
63private:
Alex Lorenze82d89c2014-08-22 22:56:03 +000064 /// \brief Print the error message to the error output stream.
65 void error(const Twine &Message, StringRef Whence = "");
66
Vedant Kumarb3020632016-07-18 17:53:12 +000067 /// \brief Print the warning message to the error output stream.
68 void warning(const Twine &Message, StringRef Whence = "");
Vedant Kumar86b2ac632016-07-13 21:38:36 +000069
Vedant Kumarbc647982016-09-23 18:57:32 +000070 /// \brief Convert \p Path into an absolute path and append it to the list
71 /// of collected paths.
Vedant Kumarcef440f2016-06-28 16:12:18 +000072 void addCollectedPath(const std::string &Path);
73
Vedant Kumar1ce90d82016-09-22 21:49:43 +000074 /// \brief If \p Path is a regular file, collect the path. If it's a
75 /// directory, recursively collect all of the paths within the directory.
76 void collectPaths(const std::string &Path);
77
Alex Lorenze82d89c2014-08-22 22:56:03 +000078 /// \brief Return a memory buffer for the given source file.
79 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
80
Justin Bogner953e2402014-09-20 15:31:56 +000081 /// \brief Create source views for the expansions of the view.
82 void attachExpansionSubViews(SourceCoverageView &View,
83 ArrayRef<ExpansionRecord> Expansions,
Vedant Kumarf681e2e2016-07-15 01:19:33 +000084 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000085
Justin Bogner953e2402014-09-20 15:31:56 +000086 /// \brief Create the source view of a particular function.
Justin Bogner5a6edad2014-09-19 19:07:17 +000087 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000088 createFunctionView(const FunctionRecord &Function,
89 const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000090
91 /// \brief Create the main source view of a particular source file.
Justin Bogner5a6edad2014-09-19 19:07:17 +000092 std::unique_ptr<SourceCoverageView>
Vedant Kumarf681e2e2016-07-15 01:19:33 +000093 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
Alex Lorenze82d89c2014-08-22 22:56:03 +000094
Simon Pilgrimdae11f72016-11-20 13:31:13 +000095 /// \brief Load the coverage mapping data. Return nullptr if an error occurred.
Justin Bogner953e2402014-09-20 15:31:56 +000096 std::unique_ptr<CoverageMapping> load();
Alex Lorenze82d89c2014-08-22 22:56:03 +000097
Sean Eveson9edfeac2017-08-14 10:20:12 +000098 /// \brief Create a mapping from files in the Coverage data to local copies
99 /// (path-equivalence).
100 void remapPathNames(const CoverageMapping &Coverage);
101
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000102 /// \brief Remove input source files which aren't mapped by \p Coverage.
103 void removeUnmappedInputs(const CoverageMapping &Coverage);
104
Vedant Kumar424f51b2016-07-15 22:44:57 +0000105 /// \brief If a demangler is available, demangle all symbol names.
106 void demangleSymbols(const CoverageMapping &Coverage);
107
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000108 /// \brief Write out a source file view to the filesystem.
109 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
110 CoveragePrinter *Printer, bool ShowFilenames);
111
Benjamin Kramerc321e532016-06-08 19:09:22 +0000112 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000113
114 int show(int argc, const char **argv,
115 CommandLineParserType commandLineParser);
116
117 int report(int argc, const char **argv,
118 CommandLineParserType commandLineParser);
119
Vedant Kumar7101d732016-07-26 22:50:58 +0000120 int export_(int argc, const char **argv,
121 CommandLineParserType commandLineParser);
122
Vedant Kumara3661ef2016-10-25 17:40:55 +0000123 std::vector<StringRef> ObjectFilenames;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000124 CoverageViewOptions ViewOpts;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000125 CoverageFiltersMatchAll Filters;
Vedant Kumar46103672016-09-22 21:49:47 +0000126
127 /// The path to the indexed profile.
128 std::string PGOFilename;
129
130 /// A list of input source files.
Vedant Kumarbc647982016-09-23 18:57:32 +0000131 std::vector<std::string> SourceFiles;
Vedant Kumar46103672016-09-22 21:49:47 +0000132
Sean Eveson9edfeac2017-08-14 10:20:12 +0000133 /// In -path-equivalence mode, this maps the absolute paths from the coverage
134 /// mapping data to the input source files.
Justin Bogner116c1662014-09-19 08:13:12 +0000135 StringMap<std::string> RemappedFilenames;
Vedant Kumar46103672016-09-22 21:49:47 +0000136
Sean Eveson9edfeac2017-08-14 10:20:12 +0000137 /// The coverage data path to be remapped from, and the source path to be
138 /// remapped to, when using -path-equivalence.
139 Optional<std::pair<std::string, std::string>> PathRemapping;
140
Vedant Kumar46103672016-09-22 21:49:47 +0000141 /// The architecture the coverage mapping data targets.
Vedant Kumar4b102c32017-08-01 21:23:26 +0000142 std::vector<StringRef> CoverageArches;
Vedant Kumarcef440f2016-06-28 16:12:18 +0000143
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000144 /// A cache for demangled symbols.
145 DemangleCache DC;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000146
Vedant Kumarb6bfd472017-02-05 20:10:55 +0000147 /// A lock which guards printing to stderr.
Vedant Kumarb3020632016-07-18 17:53:12 +0000148 std::mutex ErrsLock;
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000149
Vedant Kumar6ab6b362016-07-15 22:44:54 +0000150 /// A container for input source file buffers.
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000151 std::mutex LoadedSourceFilesLock;
152 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
153 LoadedSourceFiles;
Sean Evesone15300e2017-08-31 09:11:31 +0000154
155 /// Whitelist from -name-whitelist to be used for filtering.
156 std::unique_ptr<SpecialCaseList> NameWhitelist;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000157};
158}
159
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000160static std::string getErrorString(const Twine &Message, StringRef Whence,
161 bool Warning) {
162 std::string Str = (Warning ? "warning" : "error");
163 Str += ": ";
Alex Lorenze82d89c2014-08-22 22:56:03 +0000164 if (!Whence.empty())
Vedant Kumarb95dc462016-07-15 01:53:39 +0000165 Str += Whence.str() + ": ";
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000166 Str += Message.str() + "\n";
167 return Str;
168}
169
170void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000171 std::unique_lock<std::mutex> Guard{ErrsLock};
172 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
173 << getErrorString(Message, Whence, false);
Vedant Kumar86b2ac632016-07-13 21:38:36 +0000174}
175
Vedant Kumarb3020632016-07-18 17:53:12 +0000176void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
177 std::unique_lock<std::mutex> Guard{ErrsLock};
178 ViewOpts.colored_ostream(errs(), raw_ostream::RED)
179 << getErrorString(Message, Whence, true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000180}
181
Vedant Kumarcef440f2016-06-28 16:12:18 +0000182void CodeCoverageTool::addCollectedPath(const std::string &Path) {
Sean Eveson9edfeac2017-08-14 10:20:12 +0000183 SmallString<128> EffectivePath(Path);
184 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
185 error(EC.message(), Path);
186 return;
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000187 }
Sean Eveson9edfeac2017-08-14 10:20:12 +0000188 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
189 SourceFiles.emplace_back(EffectivePath.str());
Vedant Kumarcef440f2016-06-28 16:12:18 +0000190}
191
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000192void CodeCoverageTool::collectPaths(const std::string &Path) {
193 llvm::sys::fs::file_status Status;
194 llvm::sys::fs::status(Path, Status);
195 if (!llvm::sys::fs::exists(Status)) {
Sean Eveson9edfeac2017-08-14 10:20:12 +0000196 if (PathRemapping)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000197 addCollectedPath(Path);
198 else
199 error("Missing source file", Path);
200 return;
201 }
202
203 if (llvm::sys::fs::is_regular_file(Status)) {
204 addCollectedPath(Path);
205 return;
206 }
207
208 if (llvm::sys::fs::is_directory(Status)) {
209 std::error_code EC;
210 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
211 F != E && !EC; F.increment(EC)) {
212 if (llvm::sys::fs::is_regular_file(F->path()))
213 addCollectedPath(F->path());
214 }
215 if (EC)
216 warning(EC.message(), Path);
217 }
218}
219
Alex Lorenze82d89c2014-08-22 22:56:03 +0000220ErrorOr<const MemoryBuffer &>
221CodeCoverageTool::getSourceFile(StringRef SourceFile) {
Justin Bogner116c1662014-09-19 08:13:12 +0000222 // If we've remapped filenames, look up the real location for this file.
Vedant Kumar615b85d2016-07-15 01:19:36 +0000223 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
Justin Bogner116c1662014-09-19 08:13:12 +0000224 if (!RemappedFilenames.empty()) {
225 auto Loc = RemappedFilenames.find(SourceFile);
226 if (Loc != RemappedFilenames.end())
227 SourceFile = Loc->second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000228 }
Justin Bogner116c1662014-09-19 08:13:12 +0000229 for (const auto &Files : LoadedSourceFiles)
230 if (sys::fs::equivalent(SourceFile, Files.first))
231 return *Files.second;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000232 auto Buffer = MemoryBuffer::getFile(SourceFile);
233 if (auto EC = Buffer.getError()) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000234 error(EC.message(), SourceFile);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000235 return EC;
236 }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000237 LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000238 return *LoadedSourceFiles.back().second;
239}
240
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000241void CodeCoverageTool::attachExpansionSubViews(
242 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
243 const CoverageMapping &Coverage) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000244 if (!ViewOpts.ShowExpandedRegions)
245 return;
Justin Bogner953e2402014-09-20 15:31:56 +0000246 for (const auto &Expansion : Expansions) {
247 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
248 if (ExpansionCoverage.empty())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000249 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000250 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
251 if (!SourceBuffer)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000252 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000253
254 auto SubViewExpansions = ExpansionCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000255 auto SubView =
256 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
257 ViewOpts, std::move(ExpansionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000258 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
259 View.addExpansion(Expansion.Region, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000260 }
261}
262
Justin Bogner5a6edad2014-09-19 19:07:17 +0000263std::unique_ptr<SourceCoverageView>
Justin Bogner953e2402014-09-20 15:31:56 +0000264CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000265 const CoverageMapping &Coverage) {
Justin Bogner953e2402014-09-20 15:31:56 +0000266 auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
267 if (FunctionCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000268 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000269 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
Justin Bogner5a6edad2014-09-19 19:07:17 +0000270 if (!SourceBuffer)
271 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000272
273 auto Expansions = FunctionCoverage.getExpansions();
Vedant Kumar6e28bcd2017-02-05 20:10:58 +0000274 auto View = SourceCoverageView::create(DC.demangle(Function.Name),
Vedant Kumar0053c0b2016-09-08 00:56:48 +0000275 SourceBuffer.get(), ViewOpts,
276 std::move(FunctionCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000277 attachExpansionSubViews(*View, Expansions, Coverage);
278
279 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000280}
281
Justin Bogner953e2402014-09-20 15:31:56 +0000282std::unique_ptr<SourceCoverageView>
283CodeCoverageTool::createSourceFileView(StringRef SourceFile,
Vedant Kumarf681e2e2016-07-15 01:19:33 +0000284 const CoverageMapping &Coverage) {
Justin Bogner5a6edad2014-09-19 19:07:17 +0000285 auto SourceBuffer = getSourceFile(SourceFile);
286 if (!SourceBuffer)
287 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000288 auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
289 if (FileCoverage.empty())
Justin Bogner5a6edad2014-09-19 19:07:17 +0000290 return nullptr;
Justin Bogner953e2402014-09-20 15:31:56 +0000291
292 auto Expansions = FileCoverage.getExpansions();
Vedant Kumarf9151b92016-06-25 02:58:30 +0000293 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
294 ViewOpts, std::move(FileCoverage));
Justin Bogner953e2402014-09-20 15:31:56 +0000295 attachExpansionSubViews(*View, Expansions, Coverage);
Vedant Kumar79554e42017-08-02 23:35:24 +0000296 if (!ViewOpts.ShowFunctionInstantiations)
297 return View;
Justin Bogner953e2402014-09-20 15:31:56 +0000298
Vedant Kumardde19c52017-08-02 23:35:25 +0000299 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) {
300 // Skip functions which have a single instantiation.
301 if (Group.size() < 2)
302 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000303
Vedant Kumardde19c52017-08-02 23:35:25 +0000304 for (const FunctionRecord *Function : Group.getInstantiations()) {
305 std::unique_ptr<SourceCoverageView> SubView{nullptr};
Vedant Kumare9079772016-09-20 21:27:48 +0000306
Vedant Kumardde19c52017-08-02 23:35:25 +0000307 StringRef Funcname = DC.demangle(Function->Name);
308
309 if (Function->ExecutionCount > 0) {
310 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
311 auto SubViewExpansions = SubViewCoverage.getExpansions();
312 SubView = SourceCoverageView::create(
313 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
314 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
315 }
316
317 unsigned FileID = Function->CountedRegions.front().FileID;
318 unsigned Line = 0;
319 for (const auto &CR : Function->CountedRegions)
320 if (CR.FileID == FileID)
321 Line = std::max(CR.LineEnd, Line);
322 View->addInstantiation(Funcname, Line, std::move(SubView));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000323 }
324 }
Justin Bogner5a6edad2014-09-19 19:07:17 +0000325 return View;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000326}
327
Justin Bogner65337d12015-05-04 04:09:38 +0000328static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
329 sys::fs::file_status Status;
330 if (sys::fs::status(LHS, Status))
331 return false;
332 auto LHSTime = Status.getLastModificationTime();
333 if (sys::fs::status(RHS, Status))
334 return false;
335 auto RHSTime = Status.getLastModificationTime();
336 return LHSTime > RHSTime;
337}
338
Justin Bogner953e2402014-09-20 15:31:56 +0000339std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000340 for (StringRef ObjectFilename : ObjectFilenames)
341 if (modifiedTimeGT(ObjectFilename, PGOFilename))
342 warning("profile data may be out of date - object is newer",
343 ObjectFilename);
Vedant Kumarb3020632016-07-18 17:53:12 +0000344 auto CoverageOrErr =
Vedant Kumar4b102c32017-08-01 21:23:26 +0000345 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000346 if (Error E = CoverageOrErr.takeError()) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000347 error("Failed to load coverage: " + toString(std::move(E)),
348 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
Justin Bogner953e2402014-09-20 15:31:56 +0000349 return nullptr;
350 }
351 auto Coverage = std::move(CoverageOrErr.get());
352 unsigned Mismatched = Coverage->getMismatchedCount();
Vedant Kumar18dd9e82017-09-21 01:11:30 +0000353 if (Mismatched) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000354 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000355
Vedant Kumar18dd9e82017-09-21 01:11:30 +0000356 if (ViewOpts.Debug) {
357 for (const auto &HashMismatch : Coverage->getHashMismatches())
358 errs() << "hash-mismatch: "
359 << "No profile record found for '" << HashMismatch.first << "'"
360 << " with hash = 0x" << utohexstr(HashMismatch.second) << "\n";
361
362 for (const auto &CounterMismatch : Coverage->getCounterMismatches())
363 errs() << "counter-mismatch: "
364 << "Coverage mapping for " << CounterMismatch.first
365 << " only has " << CounterMismatch.second
366 << " valid counter expressions\n";
367 }
368 }
369
Sean Eveson9edfeac2017-08-14 10:20:12 +0000370 remapPathNames(*Coverage);
371
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000372 if (!SourceFiles.empty())
373 removeUnmappedInputs(*Coverage);
374
375 demangleSymbols(*Coverage);
376
377 return Coverage;
378}
379
Sean Eveson9edfeac2017-08-14 10:20:12 +0000380void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
381 if (!PathRemapping)
382 return;
383
384 // Convert remapping paths to native paths with trailing seperators.
385 auto nativeWithTrailing = [](StringRef Path) -> std::string {
386 if (Path.empty())
387 return "";
388 SmallString<128> NativePath;
389 sys::path::native(Path, NativePath);
390 if (!sys::path::is_separator(NativePath.back()))
391 NativePath += sys::path::get_separator();
392 return NativePath.c_str();
393 };
394 std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
395 std::string RemapTo = nativeWithTrailing(PathRemapping->second);
396
397 // Create a mapping from coverage data file paths to local paths.
398 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
399 SmallString<128> NativeFilename;
400 sys::path::native(Filename, NativeFilename);
401 if (NativeFilename.startswith(RemapFrom)) {
402 RemappedFilenames[Filename] =
403 RemapTo + NativeFilename.substr(RemapFrom.size()).str();
404 }
405 }
406
407 // Convert input files from local paths to coverage data file paths.
408 StringMap<std::string> InvRemappedFilenames;
409 for (const auto &RemappedFilename : RemappedFilenames)
410 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
411
412 for (std::string &Filename : SourceFiles) {
413 SmallString<128> NativeFilename;
414 sys::path::native(Filename, NativeFilename);
415 auto CovFileName = InvRemappedFilenames.find(NativeFilename);
416 if (CovFileName != InvRemappedFilenames.end())
417 Filename = CovFileName->second;
418 }
419}
420
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000421void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
422 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
Vedant Kumar458808802016-09-23 18:57:35 +0000423
424 auto UncoveredFilesIt = SourceFiles.end();
Sean Eveson9edfeac2017-08-14 10:20:12 +0000425 // The user may have specified source files which aren't in the coverage
426 // mapping. Filter these files away.
427 UncoveredFilesIt = std::remove_if(
428 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
429 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
430 SF);
431 });
Justin Bogner116c1662014-09-19 08:13:12 +0000432
Vedant Kumar458808802016-09-23 18:57:35 +0000433 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000434}
435
Vedant Kumar424f51b2016-07-15 22:44:57 +0000436void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
437 if (!ViewOpts.hasDemangler())
438 return;
439
440 // Pass function names to the demangler in a temporary file.
441 int InputFD;
442 SmallString<256> InputPath;
443 std::error_code EC =
444 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
445 if (EC) {
446 error(InputPath, EC.message());
447 return;
448 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000449 ToolOutputFile InputTOF{InputPath, InputFD};
Vedant Kumar424f51b2016-07-15 22:44:57 +0000450
451 unsigned NumSymbols = 0;
452 for (const auto &Function : Coverage.getCoveredFunctions()) {
453 InputTOF.os() << Function.Name << '\n';
454 ++NumSymbols;
455 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000456 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000457
458 // Use another temporary file to store the demangler's output.
459 int OutputFD;
460 SmallString<256> OutputPath;
461 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
462 OutputPath);
463 if (EC) {
464 error(OutputPath, EC.message());
465 return;
466 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000467 ToolOutputFile OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000468 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000469
470 // Invoke the demangler.
471 std::vector<const char *> ArgsV;
472 for (const std::string &Arg : ViewOpts.DemanglerOpts)
473 ArgsV.push_back(Arg.c_str());
474 ArgsV.push_back(nullptr);
Alexander Kornienko208eecd2017-09-13 17:03:37 +0000475 Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
Vedant Kumar424f51b2016-07-15 22:44:57 +0000476 std::string ErrMsg;
477 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
478 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
479 /*memoryLimit=*/0, &ErrMsg);
480 if (RC) {
481 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
482 return;
483 }
484
485 // Parse the demangler's output.
486 auto BufOrError = MemoryBuffer::getFile(OutputPath);
487 if (!BufOrError) {
488 error(OutputPath, BufOrError.getError().message());
489 return;
490 }
491
492 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
493
494 SmallVector<StringRef, 8> Symbols;
495 StringRef DemanglerData = DemanglerBuf->getBuffer();
496 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
497 /*KeepEmpty=*/false);
498 if (Symbols.size() != NumSymbols) {
499 error("Demangler did not provide expected number of symbols");
500 return;
501 }
502
503 // Cache the demangled names.
504 unsigned I = 0;
505 for (const auto &Function : Coverage.getCoveredFunctions())
Igor Kudrin9e015da2017-02-19 14:26:52 +0000506 // On Windows, lines in the demangler's output file end with "\r\n".
507 // Splitting by '\n' keeps '\r's, so cut them now.
508 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000509}
510
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000511void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
512 CoverageMapping *Coverage,
513 CoveragePrinter *Printer,
514 bool ShowFilenames) {
515 auto View = createSourceFileView(SourceFile, *Coverage);
516 if (!View) {
517 warning("The file '" + SourceFile + "' isn't covered.");
518 return;
519 }
520
521 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
522 if (Error E = OSOrErr.takeError()) {
523 error("Could not create view file!", toString(std::move(E)));
524 return;
525 }
526 auto OS = std::move(OSOrErr.get());
527
528 View->print(*OS.get(), /*Wholefile=*/true,
Sean Eveson1439fa62017-09-27 16:20:07 +0000529 /*ShowSourceName=*/ShowFilenames);
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000530 Printer->closeViewFile(std::move(OS));
531}
532
Alex Lorenze82d89c2014-08-22 22:56:03 +0000533int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000534 cl::opt<std::string> CovFilename(
535 cl::Positional, cl::desc("Covered executable or object file."));
536
537 cl::list<std::string> CovFilenames(
538 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
539 cl::CommaSeparated);
Justin Bognerf6c50552014-10-30 20:51:24 +0000540
Alex Lorenze82d89c2014-08-22 22:56:03 +0000541 cl::list<std::string> InputSourceFiles(
542 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
543
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000544 cl::opt<bool> DebugDumpCollectedPaths(
545 "dump-collected-paths", cl::Optional, cl::Hidden,
546 cl::desc("Show the collected paths to source files"));
547
Justin Bogner953e2402014-09-20 15:31:56 +0000548 cl::opt<std::string, true> PGOFilename(
549 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000550 cl::desc(
551 "File with the profile data obtained after an instrumented run"));
552
Vedant Kumar4b102c32017-08-01 21:23:26 +0000553 cl::list<std::string> Arches(
554 "arch", cl::desc("architectures of the coverage mapping binaries"));
Justin Bogner43795352015-03-11 02:30:51 +0000555
Alex Lorenze82d89c2014-08-22 22:56:03 +0000556 cl::opt<bool> DebugDump("dump", cl::Optional,
557 cl::desc("Show internal debug dump"));
558
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000559 cl::opt<CoverageViewOptions::OutputFormat> Format(
560 "format", cl::desc("Output format for line-based coverage reports"),
561 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
562 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000563 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000564 "HTML output")),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000565 cl::init(CoverageViewOptions::OutputFormat::Text));
566
Sean Eveson9edfeac2017-08-14 10:20:12 +0000567 cl::opt<std::string> PathRemap(
568 "path-equivalence", cl::Optional,
569 cl::desc("<from>,<to> Map coverage data paths to local source file "
570 "paths"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000571
572 cl::OptionCategory FilteringCategory("Function filtering options");
573
574 cl::list<std::string> NameFilters(
575 "name", cl::Optional,
576 cl::desc("Show code coverage only for functions with the given name"),
577 cl::ZeroOrMore, cl::cat(FilteringCategory));
578
Sean Evesone15300e2017-08-31 09:11:31 +0000579 cl::list<std::string> NameFilterFiles(
580 "name-whitelist", cl::Optional,
581 cl::desc("Show code coverage only for functions listed in the given "
582 "file"),
583 cl::ZeroOrMore, cl::cat(FilteringCategory));
584
Alex Lorenze82d89c2014-08-22 22:56:03 +0000585 cl::list<std::string> NameRegexFilters(
586 "name-regex", cl::Optional,
587 cl::desc("Show code coverage only for functions that match the given "
588 "regular expression"),
589 cl::ZeroOrMore, cl::cat(FilteringCategory));
590
591 cl::opt<double> RegionCoverageLtFilter(
592 "region-coverage-lt", cl::Optional,
593 cl::desc("Show code coverage only for functions with region coverage "
594 "less than the given threshold"),
595 cl::cat(FilteringCategory));
596
597 cl::opt<double> RegionCoverageGtFilter(
598 "region-coverage-gt", cl::Optional,
599 cl::desc("Show code coverage only for functions with region coverage "
600 "greater than the given threshold"),
601 cl::cat(FilteringCategory));
602
603 cl::opt<double> LineCoverageLtFilter(
604 "line-coverage-lt", cl::Optional,
605 cl::desc("Show code coverage only for functions with line coverage less "
606 "than the given threshold"),
607 cl::cat(FilteringCategory));
608
609 cl::opt<double> LineCoverageGtFilter(
610 "line-coverage-gt", cl::Optional,
611 cl::desc("Show code coverage only for functions with line coverage "
612 "greater than the given threshold"),
613 cl::cat(FilteringCategory));
614
Justin Bogner9deb1d42015-03-19 04:45:16 +0000615 cl::opt<cl::boolOrDefault> UseColor(
616 "use-color", cl::desc("Emit colored output (default=autodetect)"),
617 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000618
Vedant Kumar424f51b2016-07-15 22:44:57 +0000619 cl::list<std::string> DemanglerOpts(
620 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
621
Eli Friedman50479f62017-09-11 22:56:20 +0000622 cl::opt<bool> RegionSummary(
623 "show-region-summary", cl::Optional,
624 cl::desc("Show region statistics in summary table"),
625 cl::init(true));
626
627 cl::opt<bool> InstantiationSummary(
628 "show-instantiation-summary", cl::Optional,
629 cl::desc("Show instantiation statistics in summary table"));
630
Alex Lorenze82d89c2014-08-22 22:56:03 +0000631 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
632 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
633 ViewOpts.Debug = DebugDump;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000634
Vedant Kumara3661ef2016-10-25 17:40:55 +0000635 if (!CovFilename.empty())
636 ObjectFilenames.emplace_back(CovFilename);
637 for (const std::string &Filename : CovFilenames)
638 ObjectFilenames.emplace_back(Filename);
639 if (ObjectFilenames.empty()) {
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000640 errs() << "No filenames specified!\n";
Vedant Kumara3661ef2016-10-25 17:40:55 +0000641 ::exit(1);
642 }
643
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000644 ViewOpts.Format = Format;
645 switch (ViewOpts.Format) {
646 case CoverageViewOptions::OutputFormat::Text:
647 ViewOpts.Colors = UseColor == cl::BOU_UNSET
648 ? sys::Process::StandardOutHasColors()
649 : UseColor == cl::BOU_TRUE;
650 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000651 case CoverageViewOptions::OutputFormat::HTML:
652 if (UseColor == cl::BOU_FALSE)
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000653 errs() << "Color output cannot be disabled when generating html.\n";
Vedant Kumar4c010922016-07-06 21:44:05 +0000654 ViewOpts.Colors = true;
655 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000656 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000657
Sean Eveson9edfeac2017-08-14 10:20:12 +0000658 // If path-equivalence was given and is a comma seperated pair then set
659 // PathRemapping.
660 auto EquivPair = StringRef(PathRemap).split(',');
661 if (!(EquivPair.first.empty() && EquivPair.second.empty()))
662 PathRemapping = EquivPair;
663
Vedant Kumar424f51b2016-07-15 22:44:57 +0000664 // If a demangler is supplied, check if it exists and register it.
665 if (DemanglerOpts.size()) {
666 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
667 if (!DemanglerPathOrErr) {
668 error("Could not find the demangler!",
669 DemanglerPathOrErr.getError().message());
670 return 1;
671 }
672 DemanglerOpts[0] = *DemanglerPathOrErr;
673 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
674 }
675
Sean Evesone15300e2017-08-31 09:11:31 +0000676 // Read in -name-whitelist files.
677 if (!NameFilterFiles.empty()) {
678 std::string SpecialCaseListErr;
679 NameWhitelist =
680 SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
681 if (!NameWhitelist)
682 error(SpecialCaseListErr);
683 }
684
Alex Lorenze82d89c2014-08-22 22:56:03 +0000685 // Create the function filters
Sean Evesone15300e2017-08-31 09:11:31 +0000686 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000687 auto NameFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000688 for (const auto &Name : NameFilters)
689 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
Sean Evesone15300e2017-08-31 09:11:31 +0000690 if (NameWhitelist)
691 NameFilterer->push_back(
692 llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000693 for (const auto &Regex : NameRegexFilters)
694 NameFilterer->push_back(
695 llvm::make_unique<NameRegexCoverageFilter>(Regex));
Vedant Kumar8a622382017-08-04 00:36:24 +0000696 Filters.push_back(std::move(NameFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000697 }
698 if (RegionCoverageLtFilter.getNumOccurrences() ||
699 RegionCoverageGtFilter.getNumOccurrences() ||
700 LineCoverageLtFilter.getNumOccurrences() ||
701 LineCoverageGtFilter.getNumOccurrences()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000702 auto StatFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000703 if (RegionCoverageLtFilter.getNumOccurrences())
704 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
705 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
706 if (RegionCoverageGtFilter.getNumOccurrences())
707 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
708 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
709 if (LineCoverageLtFilter.getNumOccurrences())
710 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
711 LineCoverageFilter::LessThan, LineCoverageLtFilter));
712 if (LineCoverageGtFilter.getNumOccurrences())
713 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
714 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
Vedant Kumar8a622382017-08-04 00:36:24 +0000715 Filters.push_back(std::move(StatFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000716 }
717
Vedant Kumar4b102c32017-08-01 21:23:26 +0000718 if (!Arches.empty()) {
719 for (const std::string &Arch : Arches) {
720 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
721 error("Unknown architecture: " + Arch);
722 return 1;
723 }
724 CoverageArches.emplace_back(Arch);
725 }
726 if (CoverageArches.size() != ObjectFilenames.size()) {
727 error("Number of architectures doesn't match the number of objects");
728 return 1;
729 }
Justin Bogner43795352015-03-11 02:30:51 +0000730 }
731
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000732 for (const std::string &File : InputSourceFiles)
733 collectPaths(File);
734
735 if (DebugDumpCollectedPaths) {
Vedant Kumarbc647982016-09-23 18:57:32 +0000736 for (const std::string &SF : SourceFiles)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000737 outs() << SF << '\n';
738 ::exit(0);
Justin Bogner116c1662014-09-19 08:13:12 +0000739 }
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000740
Eli Friedman50479f62017-09-11 22:56:20 +0000741 ViewOpts.ShowRegionSummary = RegionSummary;
742 ViewOpts.ShowInstantiationSummary = InstantiationSummary;
743
Alex Lorenze82d89c2014-08-22 22:56:03 +0000744 return 0;
745 };
746
Alex Lorenze82d89c2014-08-22 22:56:03 +0000747 switch (Cmd) {
748 case Show:
749 return show(argc, argv, commandLineParser);
750 case Report:
751 return report(argc, argv, commandLineParser);
Vedant Kumar7101d732016-07-26 22:50:58 +0000752 case Export:
753 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000754 }
755 return 0;
756}
757
758int CodeCoverageTool::show(int argc, const char **argv,
759 CommandLineParserType commandLineParser) {
760
761 cl::OptionCategory ViewCategory("Viewing options");
762
763 cl::opt<bool> ShowLineExecutionCounts(
764 "show-line-counts", cl::Optional,
765 cl::desc("Show the execution counts for each line"), cl::init(true),
766 cl::cat(ViewCategory));
767
768 cl::opt<bool> ShowRegions(
769 "show-regions", cl::Optional,
770 cl::desc("Show the execution counts for each region"),
771 cl::cat(ViewCategory));
772
773 cl::opt<bool> ShowBestLineRegionsCounts(
774 "show-line-counts-or-regions", cl::Optional,
775 cl::desc("Show the execution counts for each line, or the execution "
776 "counts for each region on lines that have multiple regions"),
777 cl::cat(ViewCategory));
778
779 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
780 cl::desc("Show expanded source regions"),
781 cl::cat(ViewCategory));
782
783 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
784 cl::desc("Show function instantiations"),
Vedant Kumar79554e42017-08-02 23:35:24 +0000785 cl::init(true), cl::cat(ViewCategory));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000786
Vedant Kumar7937ef32016-06-28 02:09:39 +0000787 cl::opt<std::string> ShowOutputDirectory(
788 "output-dir", cl::init(""),
789 cl::desc("Directory in which coverage information is written out"));
790 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
791 cl::aliasopt(ShowOutputDirectory));
792
Ying Yi0ef31b72016-08-04 10:39:43 +0000793 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000794 "tab-size", cl::init(2),
795 cl::desc(
796 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000797
Ying Yi84dc9712016-08-24 14:27:23 +0000798 cl::opt<std::string> ProjectTitle(
799 "project-title", cl::Optional,
800 cl::desc("Set project title for the coverage report"));
801
Vedant Kumar7fa75102017-07-11 01:23:29 +0000802 cl::opt<unsigned> NumThreads(
803 "num-threads", cl::init(0),
804 cl::desc("Number of merge threads to use (default: autodetect)"));
805 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
806 cl::aliasopt(NumThreads));
807
Alex Lorenze82d89c2014-08-22 22:56:03 +0000808 auto Err = commandLineParser(argc, argv);
809 if (Err)
810 return Err;
811
Alex Lorenze82d89c2014-08-22 22:56:03 +0000812 ViewOpts.ShowLineNumbers = true;
813 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
814 !ShowRegions || ShowBestLineRegionsCounts;
815 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000816 ViewOpts.ShowExpandedRegions = ShowExpansions;
817 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000818 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000819 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000820 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000821
Vedant Kumar64d8a022016-06-28 16:12:20 +0000822 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000823 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
824 error("Could not create output directory!", E.message());
825 return 1;
826 }
827 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000828
Ying Yi84dc9712016-08-24 14:27:23 +0000829 sys::fs::file_status Status;
830 if (sys::fs::status(PGOFilename, Status)) {
831 error("profdata file error: can not get the file status. \n");
832 return 1;
833 }
834
835 auto ModifiedTime = Status.getLastModificationTime();
Pavel Labath757ca882016-10-24 10:59:17 +0000836 std::string ModifiedTimeStr = to_string(ModifiedTime);
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000837 size_t found = ModifiedTimeStr.rfind(':');
Ying Yi84dc9712016-08-24 14:27:23 +0000838 ViewOpts.CreatedTimeStr = (found != std::string::npos)
839 ? "Created: " + ModifiedTimeStr.substr(0, found)
840 : "Created: " + ModifiedTimeStr;
841
Justin Bogner953e2402014-09-20 15:31:56 +0000842 auto Coverage = load();
843 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000844 return 1;
845
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000846 auto Printer = CoveragePrinter::create(ViewOpts);
847
Sean Eveson1439fa62017-09-27 16:20:07 +0000848 if (!Filters.empty()) {
849 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
850 if (Error E = OSOrErr.takeError()) {
851 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000852 return 1;
853 }
Sean Eveson1439fa62017-09-27 16:20:07 +0000854 auto OS = std::move(OSOrErr.get());
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000855
Sean Eveson1439fa62017-09-27 16:20:07 +0000856 // Show functions.
857 for (const auto &Function : Coverage->getCoveredFunctions()) {
858 if (!Filters.matches(*Coverage.get(), Function))
859 continue;
Sean Eveson51b81742017-09-27 15:37:40 +0000860
Sean Eveson1439fa62017-09-27 16:20:07 +0000861 auto mainView = createFunctionView(Function, *Coverage);
862 if (!mainView) {
863 warning("Could not read coverage for '" + Function.Name + "'.");
864 continue;
Sean Eveson51b81742017-09-27 15:37:40 +0000865 }
866
Sean Eveson1439fa62017-09-27 16:20:07 +0000867 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Sean Eveson51b81742017-09-27 15:37:40 +0000868 }
Sean Eveson1439fa62017-09-27 16:20:07 +0000869
870 Printer->closeViewFile(std::move(OS));
Sean Eveson51b81742017-09-27 15:37:40 +0000871 return 0;
872 }
873
874 // Show files
875 bool ShowFilenames =
876 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
877 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
878
Sean Eveson1439fa62017-09-27 16:20:07 +0000879 if (SourceFiles.empty())
880 // Get the source files from the function coverage mapping.
881 for (StringRef Filename : Coverage->getUniqueSourceFiles())
882 SourceFiles.push_back(Filename);
883
884 // Create an index out of the source files.
885 if (ViewOpts.hasOutputDirectory()) {
886 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
887 error("Could not create index file!", toString(std::move(E)));
888 return 1;
889 }
890 }
891
Vedant Kumar7fa75102017-07-11 01:23:29 +0000892 // If NumThreads is not specified, auto-detect a good default.
893 if (NumThreads == 0)
894 NumThreads =
895 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
896 unsigned(SourceFiles.size())));
897
898 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000899 for (const std::string &SourceFile : SourceFiles)
900 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
901 ShowFilenames);
902 } else {
903 // In -output-dir mode, it's safe to use multiple threads to print files.
Vedant Kumar7fa75102017-07-11 01:23:29 +0000904 ThreadPool Pool(NumThreads);
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000905 for (const std::string &SourceFile : SourceFiles)
906 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
907 Coverage.get(), Printer.get(), ShowFilenames);
908 Pool.wait();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000909 }
910
911 return 0;
912}
913
914int CodeCoverageTool::report(int argc, const char **argv,
915 CommandLineParserType commandLineParser) {
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000916 cl::opt<bool> ShowFunctionSummaries(
917 "show-functions", cl::Optional, cl::init(false),
918 cl::desc("Show coverage summaries for each function"));
919
Alex Lorenze82d89c2014-08-22 22:56:03 +0000920 auto Err = commandLineParser(argc, argv);
921 if (Err)
922 return Err;
923
Vedant Kumar431359a2017-02-28 16:57:28 +0000924 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
Vedant Kumar4c010922016-07-06 21:44:05 +0000925 error("HTML output for summary reports is not yet supported.");
Vedant Kumar431359a2017-02-28 16:57:28 +0000926 return 1;
927 }
Vedant Kumar4c010922016-07-06 21:44:05 +0000928
Justin Bogner953e2402014-09-20 15:31:56 +0000929 auto Coverage = load();
930 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000931 return 1;
932
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000933 CoverageReport Report(ViewOpts, *Coverage.get());
Vedant Kumarfeb3f522017-09-25 23:10:03 +0000934 if (!ShowFunctionSummaries) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000935 Report.renderFileReports(llvm::outs());
Vedant Kumarfeb3f522017-09-25 23:10:03 +0000936 } else {
937 if (SourceFiles.empty()) {
938 error("Source files must be specified when -show-functions=true is "
939 "specified");
940 return 1;
941 }
942
Vedant Kumarf2b067c2017-02-05 20:11:03 +0000943 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
Vedant Kumarfeb3f522017-09-25 23:10:03 +0000944 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000945 return 0;
946}
947
Vedant Kumar7101d732016-07-26 22:50:58 +0000948int CodeCoverageTool::export_(int argc, const char **argv,
949 CommandLineParserType commandLineParser) {
950
951 auto Err = commandLineParser(argc, argv);
952 if (Err)
953 return Err;
954
Vedant Kumar431359a2017-02-28 16:57:28 +0000955 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
956 error("Coverage data can only be exported as textual JSON.");
957 return 1;
958 }
959
Vedant Kumar7101d732016-07-26 22:50:58 +0000960 auto Coverage = load();
961 if (!Coverage) {
962 error("Could not load coverage information");
963 return 1;
964 }
965
Vedant Kumar72c3a112017-09-08 18:44:49 +0000966 exportCoverageDataToJson(*Coverage.get(), ViewOpts, outs());
Vedant Kumar7101d732016-07-26 22:50:58 +0000967
968 return 0;
969}
970
Justin Bognerd249a3b2014-10-30 20:57:49 +0000971int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000972 CodeCoverageTool Tool;
973 return Tool.run(CodeCoverageTool::Show, argc, argv);
974}
975
Justin Bognerd249a3b2014-10-30 20:57:49 +0000976int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000977 CodeCoverageTool Tool;
978 return Tool.run(CodeCoverageTool::Report, argc, argv);
979}
Vedant Kumar7101d732016-07-26 22:50:58 +0000980
981int exportMain(int argc, const char *argv[]) {
982 CodeCoverageTool Tool;
983 return Tool.run(CodeCoverageTool::Export, argc, argv);
984}