blob: 0e3d67e5691f8b89b8e5ba3654688a2b9938b0bc [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 Kumarb3020632016-07-18 17:53:12 +0000353 if (Mismatched)
354 warning(utostr(Mismatched) + " functions have mismatched data");
Justin Bogner116c1662014-09-19 08:13:12 +0000355
Sean Eveson9edfeac2017-08-14 10:20:12 +0000356 remapPathNames(*Coverage);
357
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000358 if (!SourceFiles.empty())
359 removeUnmappedInputs(*Coverage);
360
361 demangleSymbols(*Coverage);
362
363 return Coverage;
364}
365
Sean Eveson9edfeac2017-08-14 10:20:12 +0000366void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
367 if (!PathRemapping)
368 return;
369
370 // Convert remapping paths to native paths with trailing seperators.
371 auto nativeWithTrailing = [](StringRef Path) -> std::string {
372 if (Path.empty())
373 return "";
374 SmallString<128> NativePath;
375 sys::path::native(Path, NativePath);
376 if (!sys::path::is_separator(NativePath.back()))
377 NativePath += sys::path::get_separator();
378 return NativePath.c_str();
379 };
380 std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
381 std::string RemapTo = nativeWithTrailing(PathRemapping->second);
382
383 // Create a mapping from coverage data file paths to local paths.
384 for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
385 SmallString<128> NativeFilename;
386 sys::path::native(Filename, NativeFilename);
387 if (NativeFilename.startswith(RemapFrom)) {
388 RemappedFilenames[Filename] =
389 RemapTo + NativeFilename.substr(RemapFrom.size()).str();
390 }
391 }
392
393 // Convert input files from local paths to coverage data file paths.
394 StringMap<std::string> InvRemappedFilenames;
395 for (const auto &RemappedFilename : RemappedFilenames)
396 InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
397
398 for (std::string &Filename : SourceFiles) {
399 SmallString<128> NativeFilename;
400 sys::path::native(Filename, NativeFilename);
401 auto CovFileName = InvRemappedFilenames.find(NativeFilename);
402 if (CovFileName != InvRemappedFilenames.end())
403 Filename = CovFileName->second;
404 }
405}
406
Vedant Kumarcab52ad2016-09-23 20:13:41 +0000407void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
408 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
Vedant Kumar458808802016-09-23 18:57:35 +0000409
410 auto UncoveredFilesIt = SourceFiles.end();
Sean Eveson9edfeac2017-08-14 10:20:12 +0000411 // The user may have specified source files which aren't in the coverage
412 // mapping. Filter these files away.
413 UncoveredFilesIt = std::remove_if(
414 SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
415 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
416 SF);
417 });
Justin Bogner116c1662014-09-19 08:13:12 +0000418
Vedant Kumar458808802016-09-23 18:57:35 +0000419 SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000420}
421
Vedant Kumar424f51b2016-07-15 22:44:57 +0000422void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
423 if (!ViewOpts.hasDemangler())
424 return;
425
426 // Pass function names to the demangler in a temporary file.
427 int InputFD;
428 SmallString<256> InputPath;
429 std::error_code EC =
430 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
431 if (EC) {
432 error(InputPath, EC.message());
433 return;
434 }
435 tool_output_file InputTOF{InputPath, InputFD};
436
437 unsigned NumSymbols = 0;
438 for (const auto &Function : Coverage.getCoveredFunctions()) {
439 InputTOF.os() << Function.Name << '\n';
440 ++NumSymbols;
441 }
Vedant Kumar554357b2016-07-15 23:08:22 +0000442 InputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000443
444 // Use another temporary file to store the demangler's output.
445 int OutputFD;
446 SmallString<256> OutputPath;
447 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
448 OutputPath);
449 if (EC) {
450 error(OutputPath, EC.message());
451 return;
452 }
453 tool_output_file OutputTOF{OutputPath, OutputFD};
Vedant Kumar554357b2016-07-15 23:08:22 +0000454 OutputTOF.os().close();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000455
456 // Invoke the demangler.
457 std::vector<const char *> ArgsV;
458 for (const std::string &Arg : ViewOpts.DemanglerOpts)
459 ArgsV.push_back(Arg.c_str());
460 ArgsV.push_back(nullptr);
Vedant Kumar38202c02016-07-15 23:15:35 +0000461 StringRef InputPathRef = InputPath.str();
462 StringRef OutputPathRef = OutputPath.str();
463 StringRef StderrRef;
Vedant Kumar424f51b2016-07-15 22:44:57 +0000464 const StringRef *Redirects[] = {&InputPathRef, &OutputPathRef, &StderrRef};
465 std::string ErrMsg;
466 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV.data(),
467 /*env=*/nullptr, Redirects, /*secondsToWait=*/0,
468 /*memoryLimit=*/0, &ErrMsg);
469 if (RC) {
470 error(ErrMsg, ViewOpts.DemanglerOpts[0]);
471 return;
472 }
473
474 // Parse the demangler's output.
475 auto BufOrError = MemoryBuffer::getFile(OutputPath);
476 if (!BufOrError) {
477 error(OutputPath, BufOrError.getError().message());
478 return;
479 }
480
481 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
482
483 SmallVector<StringRef, 8> Symbols;
484 StringRef DemanglerData = DemanglerBuf->getBuffer();
485 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
486 /*KeepEmpty=*/false);
487 if (Symbols.size() != NumSymbols) {
488 error("Demangler did not provide expected number of symbols");
489 return;
490 }
491
492 // Cache the demangled names.
493 unsigned I = 0;
494 for (const auto &Function : Coverage.getCoveredFunctions())
Igor Kudrin9e015da2017-02-19 14:26:52 +0000495 // On Windows, lines in the demangler's output file end with "\r\n".
496 // Splitting by '\n' keeps '\r's, so cut them now.
497 DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
Vedant Kumar424f51b2016-07-15 22:44:57 +0000498}
499
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000500void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
501 CoverageMapping *Coverage,
502 CoveragePrinter *Printer,
503 bool ShowFilenames) {
504 auto View = createSourceFileView(SourceFile, *Coverage);
505 if (!View) {
506 warning("The file '" + SourceFile + "' isn't covered.");
507 return;
508 }
509
510 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
511 if (Error E = OSOrErr.takeError()) {
512 error("Could not create view file!", toString(std::move(E)));
513 return;
514 }
515 auto OS = std::move(OSOrErr.get());
516
517 View->print(*OS.get(), /*Wholefile=*/true,
518 /*ShowSourceName=*/ShowFilenames);
519 Printer->closeViewFile(std::move(OS));
520}
521
Alex Lorenze82d89c2014-08-22 22:56:03 +0000522int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
Vedant Kumara3661ef2016-10-25 17:40:55 +0000523 cl::opt<std::string> CovFilename(
524 cl::Positional, cl::desc("Covered executable or object file."));
525
526 cl::list<std::string> CovFilenames(
527 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
528 cl::CommaSeparated);
Justin Bognerf6c50552014-10-30 20:51:24 +0000529
Alex Lorenze82d89c2014-08-22 22:56:03 +0000530 cl::list<std::string> InputSourceFiles(
531 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
532
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000533 cl::opt<bool> DebugDumpCollectedPaths(
534 "dump-collected-paths", cl::Optional, cl::Hidden,
535 cl::desc("Show the collected paths to source files"));
536
Justin Bogner953e2402014-09-20 15:31:56 +0000537 cl::opt<std::string, true> PGOFilename(
538 "instr-profile", cl::Required, cl::location(this->PGOFilename),
Alex Lorenze82d89c2014-08-22 22:56:03 +0000539 cl::desc(
540 "File with the profile data obtained after an instrumented run"));
541
Vedant Kumar4b102c32017-08-01 21:23:26 +0000542 cl::list<std::string> Arches(
543 "arch", cl::desc("architectures of the coverage mapping binaries"));
Justin Bogner43795352015-03-11 02:30:51 +0000544
Alex Lorenze82d89c2014-08-22 22:56:03 +0000545 cl::opt<bool> DebugDump("dump", cl::Optional,
546 cl::desc("Show internal debug dump"));
547
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000548 cl::opt<CoverageViewOptions::OutputFormat> Format(
549 "format", cl::desc("Output format for line-based coverage reports"),
550 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
551 "Text output"),
Vedant Kumar4c010922016-07-06 21:44:05 +0000552 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000553 "HTML output")),
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000554 cl::init(CoverageViewOptions::OutputFormat::Text));
555
Sean Eveson9edfeac2017-08-14 10:20:12 +0000556 cl::opt<std::string> PathRemap(
557 "path-equivalence", cl::Optional,
558 cl::desc("<from>,<to> Map coverage data paths to local source file "
559 "paths"));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000560
561 cl::OptionCategory FilteringCategory("Function filtering options");
562
563 cl::list<std::string> NameFilters(
564 "name", cl::Optional,
565 cl::desc("Show code coverage only for functions with the given name"),
566 cl::ZeroOrMore, cl::cat(FilteringCategory));
567
Sean Evesone15300e2017-08-31 09:11:31 +0000568 cl::list<std::string> NameFilterFiles(
569 "name-whitelist", cl::Optional,
570 cl::desc("Show code coverage only for functions listed in the given "
571 "file"),
572 cl::ZeroOrMore, cl::cat(FilteringCategory));
573
Alex Lorenze82d89c2014-08-22 22:56:03 +0000574 cl::list<std::string> NameRegexFilters(
575 "name-regex", cl::Optional,
576 cl::desc("Show code coverage only for functions that match the given "
577 "regular expression"),
578 cl::ZeroOrMore, cl::cat(FilteringCategory));
579
580 cl::opt<double> RegionCoverageLtFilter(
581 "region-coverage-lt", cl::Optional,
582 cl::desc("Show code coverage only for functions with region coverage "
583 "less than the given threshold"),
584 cl::cat(FilteringCategory));
585
586 cl::opt<double> RegionCoverageGtFilter(
587 "region-coverage-gt", cl::Optional,
588 cl::desc("Show code coverage only for functions with region coverage "
589 "greater than the given threshold"),
590 cl::cat(FilteringCategory));
591
592 cl::opt<double> LineCoverageLtFilter(
593 "line-coverage-lt", cl::Optional,
594 cl::desc("Show code coverage only for functions with line coverage less "
595 "than the given threshold"),
596 cl::cat(FilteringCategory));
597
598 cl::opt<double> LineCoverageGtFilter(
599 "line-coverage-gt", cl::Optional,
600 cl::desc("Show code coverage only for functions with line coverage "
601 "greater than the given threshold"),
602 cl::cat(FilteringCategory));
603
Justin Bogner9deb1d42015-03-19 04:45:16 +0000604 cl::opt<cl::boolOrDefault> UseColor(
605 "use-color", cl::desc("Emit colored output (default=autodetect)"),
606 cl::init(cl::BOU_UNSET));
Justin Bognercfb53e42015-03-19 00:02:23 +0000607
Vedant Kumar424f51b2016-07-15 22:44:57 +0000608 cl::list<std::string> DemanglerOpts(
609 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
610
Alex Lorenze82d89c2014-08-22 22:56:03 +0000611 auto commandLineParser = [&, this](int argc, const char **argv) -> int {
612 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
613 ViewOpts.Debug = DebugDump;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000614
Vedant Kumara3661ef2016-10-25 17:40:55 +0000615 if (!CovFilename.empty())
616 ObjectFilenames.emplace_back(CovFilename);
617 for (const std::string &Filename : CovFilenames)
618 ObjectFilenames.emplace_back(Filename);
619 if (ObjectFilenames.empty()) {
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000620 errs() << "No filenames specified!\n";
Vedant Kumara3661ef2016-10-25 17:40:55 +0000621 ::exit(1);
622 }
623
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000624 ViewOpts.Format = Format;
625 switch (ViewOpts.Format) {
626 case CoverageViewOptions::OutputFormat::Text:
627 ViewOpts.Colors = UseColor == cl::BOU_UNSET
628 ? sys::Process::StandardOutHasColors()
629 : UseColor == cl::BOU_TRUE;
630 break;
Vedant Kumar4c010922016-07-06 21:44:05 +0000631 case CoverageViewOptions::OutputFormat::HTML:
632 if (UseColor == cl::BOU_FALSE)
Vedant Kumar22c1b7c2016-10-25 19:52:57 +0000633 errs() << "Color output cannot be disabled when generating html.\n";
Vedant Kumar4c010922016-07-06 21:44:05 +0000634 ViewOpts.Colors = true;
635 break;
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000636 }
Justin Bognercfb53e42015-03-19 00:02:23 +0000637
Sean Eveson9edfeac2017-08-14 10:20:12 +0000638 // If path-equivalence was given and is a comma seperated pair then set
639 // PathRemapping.
640 auto EquivPair = StringRef(PathRemap).split(',');
641 if (!(EquivPair.first.empty() && EquivPair.second.empty()))
642 PathRemapping = EquivPair;
643
Vedant Kumar424f51b2016-07-15 22:44:57 +0000644 // If a demangler is supplied, check if it exists and register it.
645 if (DemanglerOpts.size()) {
646 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
647 if (!DemanglerPathOrErr) {
648 error("Could not find the demangler!",
649 DemanglerPathOrErr.getError().message());
650 return 1;
651 }
652 DemanglerOpts[0] = *DemanglerPathOrErr;
653 ViewOpts.DemanglerOpts.swap(DemanglerOpts);
654 }
655
Sean Evesone15300e2017-08-31 09:11:31 +0000656 // Read in -name-whitelist files.
657 if (!NameFilterFiles.empty()) {
658 std::string SpecialCaseListErr;
659 NameWhitelist =
660 SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
661 if (!NameWhitelist)
662 error(SpecialCaseListErr);
663 }
664
Alex Lorenze82d89c2014-08-22 22:56:03 +0000665 // Create the function filters
Sean Evesone15300e2017-08-31 09:11:31 +0000666 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000667 auto NameFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000668 for (const auto &Name : NameFilters)
669 NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
Sean Evesone15300e2017-08-31 09:11:31 +0000670 if (NameWhitelist)
671 NameFilterer->push_back(
672 llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000673 for (const auto &Regex : NameRegexFilters)
674 NameFilterer->push_back(
675 llvm::make_unique<NameRegexCoverageFilter>(Regex));
Vedant Kumar8a622382017-08-04 00:36:24 +0000676 Filters.push_back(std::move(NameFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000677 }
678 if (RegionCoverageLtFilter.getNumOccurrences() ||
679 RegionCoverageGtFilter.getNumOccurrences() ||
680 LineCoverageLtFilter.getNumOccurrences() ||
681 LineCoverageGtFilter.getNumOccurrences()) {
Vedant Kumar8a622382017-08-04 00:36:24 +0000682 auto StatFilterer = llvm::make_unique<CoverageFilters>();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000683 if (RegionCoverageLtFilter.getNumOccurrences())
684 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
685 RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
686 if (RegionCoverageGtFilter.getNumOccurrences())
687 StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
688 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
689 if (LineCoverageLtFilter.getNumOccurrences())
690 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
691 LineCoverageFilter::LessThan, LineCoverageLtFilter));
692 if (LineCoverageGtFilter.getNumOccurrences())
693 StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
694 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
Vedant Kumar8a622382017-08-04 00:36:24 +0000695 Filters.push_back(std::move(StatFilterer));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000696 }
697
Vedant Kumar4b102c32017-08-01 21:23:26 +0000698 if (!Arches.empty()) {
699 for (const std::string &Arch : Arches) {
700 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
701 error("Unknown architecture: " + Arch);
702 return 1;
703 }
704 CoverageArches.emplace_back(Arch);
705 }
706 if (CoverageArches.size() != ObjectFilenames.size()) {
707 error("Number of architectures doesn't match the number of objects");
708 return 1;
709 }
Justin Bogner43795352015-03-11 02:30:51 +0000710 }
711
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000712 for (const std::string &File : InputSourceFiles)
713 collectPaths(File);
714
715 if (DebugDumpCollectedPaths) {
Vedant Kumarbc647982016-09-23 18:57:32 +0000716 for (const std::string &SF : SourceFiles)
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000717 outs() << SF << '\n';
718 ::exit(0);
Justin Bogner116c1662014-09-19 08:13:12 +0000719 }
Vedant Kumar1ce90d82016-09-22 21:49:43 +0000720
Alex Lorenze82d89c2014-08-22 22:56:03 +0000721 return 0;
722 };
723
Alex Lorenze82d89c2014-08-22 22:56:03 +0000724 switch (Cmd) {
725 case Show:
726 return show(argc, argv, commandLineParser);
727 case Report:
728 return report(argc, argv, commandLineParser);
Vedant Kumar7101d732016-07-26 22:50:58 +0000729 case Export:
730 return export_(argc, argv, commandLineParser);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000731 }
732 return 0;
733}
734
735int CodeCoverageTool::show(int argc, const char **argv,
736 CommandLineParserType commandLineParser) {
737
738 cl::OptionCategory ViewCategory("Viewing options");
739
740 cl::opt<bool> ShowLineExecutionCounts(
741 "show-line-counts", cl::Optional,
742 cl::desc("Show the execution counts for each line"), cl::init(true),
743 cl::cat(ViewCategory));
744
745 cl::opt<bool> ShowRegions(
746 "show-regions", cl::Optional,
747 cl::desc("Show the execution counts for each region"),
748 cl::cat(ViewCategory));
749
750 cl::opt<bool> ShowBestLineRegionsCounts(
751 "show-line-counts-or-regions", cl::Optional,
752 cl::desc("Show the execution counts for each line, or the execution "
753 "counts for each region on lines that have multiple regions"),
754 cl::cat(ViewCategory));
755
756 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
757 cl::desc("Show expanded source regions"),
758 cl::cat(ViewCategory));
759
760 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
761 cl::desc("Show function instantiations"),
Vedant Kumar79554e42017-08-02 23:35:24 +0000762 cl::init(true), cl::cat(ViewCategory));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000763
Vedant Kumar7937ef32016-06-28 02:09:39 +0000764 cl::opt<std::string> ShowOutputDirectory(
765 "output-dir", cl::init(""),
766 cl::desc("Directory in which coverage information is written out"));
767 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
768 cl::aliasopt(ShowOutputDirectory));
769
Ying Yi0ef31b72016-08-04 10:39:43 +0000770 cl::opt<uint32_t> TabSize(
Vedant Kumarad547d32016-08-04 18:00:42 +0000771 "tab-size", cl::init(2),
772 cl::desc(
773 "Set tab expansion size for html coverage reports (default = 2)"));
Ying Yi0ef31b72016-08-04 10:39:43 +0000774
Ying Yi84dc9712016-08-24 14:27:23 +0000775 cl::opt<std::string> ProjectTitle(
776 "project-title", cl::Optional,
777 cl::desc("Set project title for the coverage report"));
778
Vedant Kumar7fa75102017-07-11 01:23:29 +0000779 cl::opt<unsigned> NumThreads(
780 "num-threads", cl::init(0),
781 cl::desc("Number of merge threads to use (default: autodetect)"));
782 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
783 cl::aliasopt(NumThreads));
784
Alex Lorenze82d89c2014-08-22 22:56:03 +0000785 auto Err = commandLineParser(argc, argv);
786 if (Err)
787 return Err;
788
Alex Lorenze82d89c2014-08-22 22:56:03 +0000789 ViewOpts.ShowLineNumbers = true;
790 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
791 !ShowRegions || ShowBestLineRegionsCounts;
792 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000793 ViewOpts.ShowExpandedRegions = ShowExpansions;
794 ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000795 ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
Ying Yi0ef31b72016-08-04 10:39:43 +0000796 ViewOpts.TabSize = TabSize;
Ying Yi84dc9712016-08-24 14:27:23 +0000797 ViewOpts.ProjectTitle = ProjectTitle;
Vedant Kumar7937ef32016-06-28 02:09:39 +0000798
Vedant Kumar64d8a022016-06-28 16:12:20 +0000799 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumar7937ef32016-06-28 02:09:39 +0000800 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
801 error("Could not create output directory!", E.message());
802 return 1;
803 }
804 }
Alex Lorenze82d89c2014-08-22 22:56:03 +0000805
Ying Yi84dc9712016-08-24 14:27:23 +0000806 sys::fs::file_status Status;
807 if (sys::fs::status(PGOFilename, Status)) {
808 error("profdata file error: can not get the file status. \n");
809 return 1;
810 }
811
812 auto ModifiedTime = Status.getLastModificationTime();
Pavel Labath757ca882016-10-24 10:59:17 +0000813 std::string ModifiedTimeStr = to_string(ModifiedTime);
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000814 size_t found = ModifiedTimeStr.rfind(':');
Ying Yi84dc9712016-08-24 14:27:23 +0000815 ViewOpts.CreatedTimeStr = (found != std::string::npos)
816 ? "Created: " + ModifiedTimeStr.substr(0, found)
817 : "Created: " + ModifiedTimeStr;
818
Justin Bogner953e2402014-09-20 15:31:56 +0000819 auto Coverage = load();
820 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000821 return 1;
822
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000823 auto Printer = CoveragePrinter::create(ViewOpts);
824
Alex Lorenze82d89c2014-08-22 22:56:03 +0000825 if (!Filters.empty()) {
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000826 auto OSOrErr = Printer->createViewFile("functions", /*InToplevel=*/true);
827 if (Error E = OSOrErr.takeError()) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000828 error("Could not create view file!", toString(std::move(E)));
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000829 return 1;
830 }
831 auto OS = std::move(OSOrErr.get());
832
833 // Show functions.
Justin Bogner953e2402014-09-20 15:31:56 +0000834 for (const auto &Function : Coverage->getCoveredFunctions()) {
835 if (!Filters.matches(Function))
Alex Lorenze82d89c2014-08-22 22:56:03 +0000836 continue;
Justin Bogner953e2402014-09-20 15:31:56 +0000837
838 auto mainView = createFunctionView(Function, *Coverage);
Justin Bogner5a6edad2014-09-19 19:07:17 +0000839 if (!mainView) {
Vedant Kumarb3020632016-07-18 17:53:12 +0000840 warning("Could not read coverage for '" + Function.Name + "'.");
Justin Bogner5a6edad2014-09-19 19:07:17 +0000841 continue;
842 }
Vedant Kumar7937ef32016-06-28 02:09:39 +0000843
Vedant Kumar7937ef32016-06-28 02:09:39 +0000844 mainView->print(*OS.get(), /*WholeFile=*/false, /*ShowSourceName=*/true);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000845 }
Vedant Kumar8d74cb22016-06-29 00:38:21 +0000846
847 Printer->closeViewFile(std::move(OS));
Alex Lorenze82d89c2014-08-22 22:56:03 +0000848 return 0;
849 }
850
851 // Show files
Ying Yi84dc9712016-08-24 14:27:23 +0000852 bool ShowFilenames =
Ying Yi24e91bd2016-09-06 21:41:38 +0000853 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() ||
Ying Yi84dc9712016-08-24 14:27:23 +0000854 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000855
Justin Bogner116c1662014-09-19 08:13:12 +0000856 if (SourceFiles.empty())
Vedant Kumar64d8a022016-06-28 16:12:20 +0000857 // Get the source files from the function coverage mapping.
Justin Bogner953e2402014-09-20 15:31:56 +0000858 for (StringRef Filename : Coverage->getUniqueSourceFiles())
Alex Lorenze82d89c2014-08-22 22:56:03 +0000859 SourceFiles.push_back(Filename);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000860
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000861 // Create an index out of the source files.
862 if (ViewOpts.hasOutputDirectory()) {
Vedant Kumara59334d2016-09-09 01:32:55 +0000863 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage)) {
Vedant Kumarb95dc462016-07-15 01:53:39 +0000864 error("Could not create index file!", toString(std::move(E)));
Vedant Kumar9cbad2c2016-06-28 16:12:24 +0000865 return 1;
866 }
867 }
868
Vedant Kumar7fa75102017-07-11 01:23:29 +0000869 // If NumThreads is not specified, auto-detect a good default.
870 if (NumThreads == 0)
871 NumThreads =
872 std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
873 unsigned(SourceFiles.size())));
874
875 if (!ViewOpts.hasOutputDirectory() || NumThreads == 1) {
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000876 for (const std::string &SourceFile : SourceFiles)
877 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
878 ShowFilenames);
879 } else {
880 // In -output-dir mode, it's safe to use multiple threads to print files.
Vedant Kumar7fa75102017-07-11 01:23:29 +0000881 ThreadPool Pool(NumThreads);
Vedant Kumar6fd94bf2016-10-19 17:55:44 +0000882 for (const std::string &SourceFile : SourceFiles)
883 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
884 Coverage.get(), Printer.get(), ShowFilenames);
885 Pool.wait();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000886 }
887
888 return 0;
889}
890
891int CodeCoverageTool::report(int argc, const char **argv,
892 CommandLineParserType commandLineParser) {
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000893 cl::opt<bool> ShowFunctionSummaries(
894 "show-functions", cl::Optional, cl::init(false),
895 cl::desc("Show coverage summaries for each function"));
896
Alex Lorenze82d89c2014-08-22 22:56:03 +0000897 auto Err = commandLineParser(argc, argv);
898 if (Err)
899 return Err;
900
Vedant Kumar431359a2017-02-28 16:57:28 +0000901 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
Vedant Kumar4c010922016-07-06 21:44:05 +0000902 error("HTML output for summary reports is not yet supported.");
Vedant Kumar431359a2017-02-28 16:57:28 +0000903 return 1;
904 }
Vedant Kumar4c010922016-07-06 21:44:05 +0000905
Justin Bogner953e2402014-09-20 15:31:56 +0000906 auto Coverage = load();
907 if (!Coverage)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000908 return 1;
909
Vedant Kumar702bb9d2016-09-06 22:45:57 +0000910 CoverageReport Report(ViewOpts, *Coverage.get());
Vedant Kumar62eb0fd2017-02-05 20:11:08 +0000911 if (!ShowFunctionSummaries)
Alex Lorenze82d89c2014-08-22 22:56:03 +0000912 Report.renderFileReports(llvm::outs());
Justin Bogner0ef7a2a2015-02-14 02:05:05 +0000913 else
Vedant Kumarf2b067c2017-02-05 20:11:03 +0000914 Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
Alex Lorenze82d89c2014-08-22 22:56:03 +0000915 return 0;
916}
917
Vedant Kumar7101d732016-07-26 22:50:58 +0000918int CodeCoverageTool::export_(int argc, const char **argv,
919 CommandLineParserType commandLineParser) {
920
921 auto Err = commandLineParser(argc, argv);
922 if (Err)
923 return Err;
924
Vedant Kumar431359a2017-02-28 16:57:28 +0000925 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
926 error("Coverage data can only be exported as textual JSON.");
927 return 1;
928 }
929
Vedant Kumar7101d732016-07-26 22:50:58 +0000930 auto Coverage = load();
931 if (!Coverage) {
932 error("Could not load coverage information");
933 return 1;
934 }
935
Vedant Kumar72c3a112017-09-08 18:44:49 +0000936 exportCoverageDataToJson(*Coverage.get(), ViewOpts, outs());
Vedant Kumar7101d732016-07-26 22:50:58 +0000937
938 return 0;
939}
940
Justin Bognerd249a3b2014-10-30 20:57:49 +0000941int showMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000942 CodeCoverageTool Tool;
943 return Tool.run(CodeCoverageTool::Show, argc, argv);
944}
945
Justin Bognerd249a3b2014-10-30 20:57:49 +0000946int reportMain(int argc, const char *argv[]) {
Alex Lorenze82d89c2014-08-22 22:56:03 +0000947 CodeCoverageTool Tool;
948 return Tool.run(CodeCoverageTool::Report, argc, argv);
949}
Vedant Kumar7101d732016-07-26 22:50:58 +0000950
951int exportMain(int argc, const char *argv[]) {
952 CodeCoverageTool Tool;
953 return Tool.run(CodeCoverageTool::Export, argc, argv);
954}