Coverage Report

Created: 2018-08-19 14:04

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/llvm-cov/CodeCoverage.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- 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
16
#include "CoverageExporterJson.h"
17
#include "CoverageFilters.h"
18
#include "CoverageReport.h"
19
#include "CoverageSummaryInfo.h"
20
#include "CoverageViewOptions.h"
21
#include "RenderingSupport.h"
22
#include "SourceCoverageView.h"
23
#include "llvm/ADT/SmallString.h"
24
#include "llvm/ADT/StringRef.h"
25
#include "llvm/ADT/Triple.h"
26
#include "llvm/ProfileData/Coverage/CoverageMapping.h"
27
#include "llvm/ProfileData/InstrProfReader.h"
28
#include "llvm/Support/CommandLine.h"
29
#include "llvm/Support/FileSystem.h"
30
#include "llvm/Support/Format.h"
31
#include "llvm/Support/MemoryBuffer.h"
32
#include "llvm/Support/Path.h"
33
#include "llvm/Support/Process.h"
34
#include "llvm/Support/Program.h"
35
#include "llvm/Support/ScopedPrinter.h"
36
#include "llvm/Support/ThreadPool.h"
37
#include "llvm/Support/Threading.h"
38
#include "llvm/Support/ToolOutputFile.h"
39
40
#include <functional>
41
#include <map>
42
#include <system_error>
43
44
using namespace llvm;
45
using namespace coverage;
46
47
void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping,
48
                              const CoverageViewOptions &Options,
49
                              raw_ostream &OS);
50
51
namespace {
52
/// The implementation of the coverage tool.
53
class CodeCoverageTool {
54
public:
55
  enum Command {
56
    /// The show command.
57
    Show,
58
    /// The report command.
59
    Report,
60
    /// The export command.
61
    Export
62
  };
63
64
  int run(Command Cmd, int argc, const char **argv);
65
66
private:
67
  /// Print the error message to the error output stream.
68
  void error(const Twine &Message, StringRef Whence = "");
69
70
  /// Print the warning message to the error output stream.
71
  void warning(const Twine &Message, StringRef Whence = "");
72
73
  /// Convert \p Path into an absolute path and append it to the list
74
  /// of collected paths.
75
  void addCollectedPath(const std::string &Path);
76
77
  /// If \p Path is a regular file, collect the path. If it's a
78
  /// directory, recursively collect all of the paths within the directory.
79
  void collectPaths(const std::string &Path);
80
81
  /// Return a memory buffer for the given source file.
82
  ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile);
83
84
  /// Create source views for the expansions of the view.
85
  void attachExpansionSubViews(SourceCoverageView &View,
86
                               ArrayRef<ExpansionRecord> Expansions,
87
                               const CoverageMapping &Coverage);
88
89
  /// Create the source view of a particular function.
90
  std::unique_ptr<SourceCoverageView>
91
  createFunctionView(const FunctionRecord &Function,
92
                     const CoverageMapping &Coverage);
93
94
  /// Create the main source view of a particular source file.
95
  std::unique_ptr<SourceCoverageView>
96
  createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage);
97
98
  /// Load the coverage mapping data. Return nullptr if an error occurred.
99
  std::unique_ptr<CoverageMapping> load();
100
101
  /// Create a mapping from files in the Coverage data to local copies
102
  /// (path-equivalence).
103
  void remapPathNames(const CoverageMapping &Coverage);
104
105
  /// Remove input source files which aren't mapped by \p Coverage.
106
  void removeUnmappedInputs(const CoverageMapping &Coverage);
107
108
  /// If a demangler is available, demangle all symbol names.
109
  void demangleSymbols(const CoverageMapping &Coverage);
110
111
  /// Write out a source file view to the filesystem.
112
  void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage,
113
                           CoveragePrinter *Printer, bool ShowFilenames);
114
115
  typedef llvm::function_ref<int(int, const char **)> CommandLineParserType;
116
117
  int doShow(int argc, const char **argv,
118
             CommandLineParserType commandLineParser);
119
120
  int doReport(int argc, const char **argv,
121
               CommandLineParserType commandLineParser);
122
123
  int doExport(int argc, const char **argv,
124
               CommandLineParserType commandLineParser);
125
126
  std::vector<StringRef> ObjectFilenames;
127
  CoverageViewOptions ViewOpts;
128
  CoverageFiltersMatchAll Filters;
129
  CoverageFilters IgnoreFilenameFilters;
130
131
  /// The path to the indexed profile.
132
  std::string PGOFilename;
133
134
  /// A list of input source files.
135
  std::vector<std::string> SourceFiles;
136
137
  /// In -path-equivalence mode, this maps the absolute paths from the coverage
138
  /// mapping data to the input source files.
139
  StringMap<std::string> RemappedFilenames;
140
141
  /// The coverage data path to be remapped from, and the source path to be
142
  /// remapped to, when using -path-equivalence.
143
  Optional<std::pair<std::string, std::string>> PathRemapping;
144
145
  /// The architecture the coverage mapping data targets.
146
  std::vector<StringRef> CoverageArches;
147
148
  /// A cache for demangled symbols.
149
  DemangleCache DC;
150
151
  /// A lock which guards printing to stderr.
152
  std::mutex ErrsLock;
153
154
  /// A container for input source file buffers.
155
  std::mutex LoadedSourceFilesLock;
156
  std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>>
157
      LoadedSourceFiles;
158
159
  /// Whitelist from -name-whitelist to be used for filtering.
160
  std::unique_ptr<SpecialCaseList> NameWhitelist;
161
};
162
}
163
164
static std::string getErrorString(const Twine &Message, StringRef Whence,
165
37
                                  bool Warning) {
166
37
  std::string Str = (Warning ? 
"warning"15
:
"error"22
);
167
37
  Str += ": ";
168
37
  if (!Whence.empty())
169
17
    Str += Whence.str() + ": ";
170
37
  Str += Message.str() + "\n";
171
37
  return Str;
172
37
}
173
174
22
void CodeCoverageTool::error(const Twine &Message, StringRef Whence) {
175
22
  std::unique_lock<std::mutex> Guard{ErrsLock};
176
22
  ViewOpts.colored_ostream(errs(), raw_ostream::RED)
177
22
      << getErrorString(Message, Whence, false);
178
22
}
179
180
15
void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) {
181
15
  std::unique_lock<std::mutex> Guard{ErrsLock};
182
15
  ViewOpts.colored_ostream(errs(), raw_ostream::RED)
183
15
      << getErrorString(Message, Whence, true);
184
15
}
185
186
83
void CodeCoverageTool::addCollectedPath(const std::string &Path) {
187
83
  SmallString<128> EffectivePath(Path);
188
83
  if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) {
189
0
    error(EC.message(), Path);
190
0
    return;
191
0
  }
192
83
  sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true);
193
83
  if (!IgnoreFilenameFilters.matchesFilename(EffectivePath))
194
81
    SourceFiles.emplace_back(EffectivePath.str());
195
83
}
196
197
81
void CodeCoverageTool::collectPaths(const std::string &Path) {
198
81
  llvm::sys::fs::file_status Status;
199
81
  llvm::sys::fs::status(Path, Status);
200
81
  if (!llvm::sys::fs::exists(Status)) {
201
7
    if (PathRemapping)
202
7
      addCollectedPath(Path);
203
0
    else
204
0
      warning("Source file doesn't exist, proceeded by ignoring it.", Path);
205
7
    return;
206
7
  }
207
74
208
74
  if (llvm::sys::fs::is_regular_file(Status)) {
209
64
    addCollectedPath(Path);
210
64
    return;
211
64
  }
212
10
213
10
  if (llvm::sys::fs::is_directory(Status)) {
214
6
    std::error_code EC;
215
6
    for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E;
216
22
         F != E; 
F.increment(EC)16
) {
217
16
218
16
      if (EC) {
219
0
        warning(EC.message(), F->path());
220
0
        continue;
221
0
      }
222
16
223
16
      if (llvm::sys::fs::is_regular_file(F->path()))
224
12
        addCollectedPath(F->path());
225
16
    }
226
6
  }
227
10
}
228
229
ErrorOr<const MemoryBuffer &>
230
146
CodeCoverageTool::getSourceFile(StringRef SourceFile) {
231
146
  // If we've remapped filenames, look up the real location for this file.
232
146
  std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock};
233
146
  if (!RemappedFilenames.empty()) {
234
142
    auto Loc = RemappedFilenames.find(SourceFile);
235
142
    if (Loc != RemappedFilenames.end())
236
142
      SourceFile = Loc->second;
237
142
  }
238
146
  for (const auto &Files : LoadedSourceFiles)
239
188
    if (sys::fs::equivalent(SourceFile, Files.first))
240
10
      return *Files.second;
241
146
  auto Buffer = MemoryBuffer::getFile(SourceFile);
242
136
  if (auto EC = Buffer.getError()) {
243
14
    error(EC.message(), SourceFile);
244
14
    return EC;
245
14
  }
246
122
  LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get()));
247
122
  return *LoadedSourceFiles.back().second;
248
122
}
249
250
void CodeCoverageTool::attachExpansionSubViews(
251
    SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions,
252
184
    const CoverageMapping &Coverage) {
253
184
  if (!ViewOpts.ShowExpandedRegions)
254
180
    return;
255
4
  for (const auto &Expansion : Expansions) {
256
3
    auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);
257
3
    if (ExpansionCoverage.empty())
258
0
      continue;
259
3
    auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename());
260
3
    if (!SourceBuffer)
261
0
      continue;
262
3
263
3
    auto SubViewExpansions = ExpansionCoverage.getExpansions();
264
3
    auto SubView =
265
3
        SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(),
266
3
                                   ViewOpts, std::move(ExpansionCoverage));
267
3
    attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
268
3
    View.addExpansion(Expansion.Region, std::move(SubView));
269
3
  }
270
4
}
271
272
std::unique_ptr<SourceCoverageView>
273
CodeCoverageTool::createFunctionView(const FunctionRecord &Function,
274
30
                                     const CoverageMapping &Coverage) {
275
30
  auto FunctionCoverage = Coverage.getCoverageForFunction(Function);
276
30
  if (FunctionCoverage.empty())
277
0
    return nullptr;
278
30
  auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename());
279
30
  if (!SourceBuffer)
280
3
    return nullptr;
281
27
282
27
  auto Expansions = FunctionCoverage.getExpansions();
283
27
  auto View = SourceCoverageView::create(DC.demangle(Function.Name),
284
27
                                         SourceBuffer.get(), ViewOpts,
285
27
                                         std::move(FunctionCoverage));
286
27
  attachExpansionSubViews(*View, Expansions, Coverage);
287
27
288
27
  return View;
289
27
}
290
291
std::unique_ptr<SourceCoverageView>
292
CodeCoverageTool::createSourceFileView(StringRef SourceFile,
293
113
                                       const CoverageMapping &Coverage) {
294
113
  auto SourceBuffer = getSourceFile(SourceFile);
295
113
  if (!SourceBuffer)
296
11
    return nullptr;
297
102
  auto FileCoverage = Coverage.getCoverageForFile(SourceFile);
298
102
  if (FileCoverage.empty())
299
0
    return nullptr;
300
102
301
102
  auto Expansions = FileCoverage.getExpansions();
302
102
  auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(),
303
102
                                         ViewOpts, std::move(FileCoverage));
304
102
  attachExpansionSubViews(*View, Expansions, Coverage);
305
102
  if (!ViewOpts.ShowFunctionInstantiations)
306
1
    return View;
307
101
308
124
  
for (const auto &Group : Coverage.getInstantiationGroups(SourceFile))101
{
309
124
    // Skip functions which have a single instantiation.
310
124
    if (Group.size() < 2)
311
98
      continue;
312
26
313
60
    
for (const FunctionRecord *Function : Group.getInstantiations())26
{
314
60
      std::unique_ptr<SourceCoverageView> SubView{nullptr};
315
60
316
60
      StringRef Funcname = DC.demangle(Function->Name);
317
60
318
60
      if (Function->ExecutionCount > 0) {
319
52
        auto SubViewCoverage = Coverage.getCoverageForFunction(*Function);
320
52
        auto SubViewExpansions = SubViewCoverage.getExpansions();
321
52
        SubView = SourceCoverageView::create(
322
52
            Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage));
323
52
        attachExpansionSubViews(*SubView, SubViewExpansions, Coverage);
324
52
      }
325
60
326
60
      unsigned FileID = Function->CountedRegions.front().FileID;
327
60
      unsigned Line = 0;
328
60
      for (const auto &CR : Function->CountedRegions)
329
446
        if (CR.FileID == FileID)
330
446
          Line = std::max(CR.LineEnd, Line);
331
60
      View->addInstantiation(Funcname, Line, std::move(SubView));
332
60
    }
333
26
  }
334
101
  return View;
335
101
}
336
337
114
static bool modifiedTimeGT(StringRef LHS, StringRef RHS) {
338
114
  sys::fs::file_status Status;
339
114
  if (sys::fs::status(LHS, Status))
340
0
    return false;
341
114
  auto LHSTime = Status.getLastModificationTime();
342
114
  if (sys::fs::status(RHS, Status))
343
0
    return false;
344
114
  auto RHSTime = Status.getLastModificationTime();
345
114
  return LHSTime > RHSTime;
346
114
}
347
348
111
std::unique_ptr<CoverageMapping> CodeCoverageTool::load() {
349
111
  for (StringRef ObjectFilename : ObjectFilenames)
350
114
    if (modifiedTimeGT(ObjectFilename, PGOFilename))
351
0
      warning("profile data may be out of date - object is newer",
352
0
              ObjectFilename);
353
111
  auto CoverageOrErr =
354
111
      CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches);
355
111
  if (Error E = CoverageOrErr.takeError()) {
356
2
    error("Failed to load coverage: " + toString(std::move(E)),
357
2
          join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "));
358
2
    return nullptr;
359
2
  }
360
109
  auto Coverage = std::move(CoverageOrErr.get());
361
109
  unsigned Mismatched = Coverage->getMismatchedCount();
362
109
  if (Mismatched) {
363
1
    warning(Twine(Mismatched) + " functions have mismatched data");
364
1
365
1
    if (ViewOpts.Debug) {
366
1
      for (const auto &HashMismatch : Coverage->getHashMismatches())
367
1
        errs() << "hash-mismatch: "
368
1
               << "No profile record found for '" << HashMismatch.first << "'"
369
1
               << " with hash = 0x" << Twine::utohexstr(HashMismatch.second)
370
1
               << '\n';
371
1
    }
372
1
  }
373
109
374
109
  remapPathNames(*Coverage);
375
109
376
109
  if (!SourceFiles.empty())
377
61
    removeUnmappedInputs(*Coverage);
378
109
379
109
  demangleSymbols(*Coverage);
380
109
381
109
  return Coverage;
382
109
}
383
384
109
void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) {
385
109
  if (!PathRemapping)
386
21
    return;
387
88
388
88
  // Convert remapping paths to native paths with trailing seperators.
389
176
  
auto nativeWithTrailing = [](StringRef Path) -> std::string 88
{
390
176
    if (Path.empty())
391
0
      return "";
392
176
    SmallString<128> NativePath;
393
176
    sys::path::native(Path, NativePath);
394
176
    if (!sys::path::is_separator(NativePath.back()))
395
173
      NativePath += sys::path::get_separator();
396
176
    return NativePath.c_str();
397
176
  };
398
88
  std::string RemapFrom = nativeWithTrailing(PathRemapping->first);
399
88
  std::string RemapTo = nativeWithTrailing(PathRemapping->second);
400
88
401
88
  // Create a mapping from coverage data file paths to local paths.
402
201
  for (StringRef Filename : Coverage.getUniqueSourceFiles()) {
403
201
    SmallString<128> NativeFilename;
404
201
    sys::path::native(Filename, NativeFilename);
405
201
    if (NativeFilename.startswith(RemapFrom)) {
406
200
      RemappedFilenames[Filename] =
407
200
          RemapTo + NativeFilename.substr(RemapFrom.size()).str();
408
200
    }
409
201
  }
410
88
411
88
  // Convert input files from local paths to coverage data file paths.
412
88
  StringMap<std::string> InvRemappedFilenames;
413
88
  for (const auto &RemappedFilename : RemappedFilenames)
414
200
    InvRemappedFilenames[RemappedFilename.getValue()] = RemappedFilename.getKey();
415
88
416
88
  for (std::string &Filename : SourceFiles) {
417
68
    SmallString<128> NativeFilename;
418
68
    sys::path::native(Filename, NativeFilename);
419
68
    auto CovFileName = InvRemappedFilenames.find(NativeFilename);
420
68
    if (CovFileName != InvRemappedFilenames.end())
421
63
      Filename = CovFileName->second;
422
68
  }
423
88
}
424
425
61
void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) {
426
61
  std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles();
427
61
428
61
  auto UncoveredFilesIt = SourceFiles.end();
429
61
  // The user may have specified source files which aren't in the coverage
430
61
  // mapping. Filter these files away.
431
61
  UncoveredFilesIt = std::remove_if(
432
68
      SourceFiles.begin(), SourceFiles.end(), [&](const std::string &SF) {
433
68
        return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(),
434
68
                                   SF);
435
68
      });
436
61
437
61
  SourceFiles.erase(UncoveredFilesIt, SourceFiles.end());
438
61
}
439
440
109
void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
441
109
  if (!ViewOpts.hasDemangler())
442
106
    return;
443
3
444
3
  // Pass function names to the demangler in a temporary file.
445
3
  int InputFD;
446
3
  SmallString<256> InputPath;
447
3
  std::error_code EC =
448
3
      sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath);
449
3
  if (EC) {
450
0
    error(InputPath, EC.message());
451
0
    return;
452
0
  }
453
3
  ToolOutputFile InputTOF{InputPath, InputFD};
454
3
455
3
  unsigned NumSymbols = 0;
456
9
  for (const auto &Function : Coverage.getCoveredFunctions()) {
457
9
    InputTOF.os() << Function.Name << '\n';
458
9
    ++NumSymbols;
459
9
  }
460
3
  InputTOF.os().close();
461
3
462
3
  // Use another temporary file to store the demangler's output.
463
3
  int OutputFD;
464
3
  SmallString<256> OutputPath;
465
3
  EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD,
466
3
                                    OutputPath);
467
3
  if (EC) {
468
0
    error(OutputPath, EC.message());
469
0
    return;
470
0
  }
471
3
  ToolOutputFile OutputTOF{OutputPath, OutputFD};
472
3
  OutputTOF.os().close();
473
3
474
3
  // Invoke the demangler.
475
3
  std::vector<StringRef> ArgsV;
476
3
  for (StringRef Arg : ViewOpts.DemanglerOpts)
477
6
    ArgsV.push_back(Arg);
478
3
  Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
479
3
  std::string ErrMsg;
480
3
  int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV,
481
3
                               /*env=*/None, Redirects, /*secondsToWait=*/0,
482
3
                               /*memoryLimit=*/0, &ErrMsg);
483
3
  if (RC) {
484
0
    error(ErrMsg, ViewOpts.DemanglerOpts[0]);
485
0
    return;
486
0
  }
487
3
488
3
  // Parse the demangler's output.
489
3
  auto BufOrError = MemoryBuffer::getFile(OutputPath);
490
3
  if (!BufOrError) {
491
0
    error(OutputPath, BufOrError.getError().message());
492
0
    return;
493
0
  }
494
3
495
3
  std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError);
496
3
497
3
  SmallVector<StringRef, 8> Symbols;
498
3
  StringRef DemanglerData = DemanglerBuf->getBuffer();
499
3
  DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols,
500
3
                      /*KeepEmpty=*/false);
501
3
  if (Symbols.size() != NumSymbols) {
502
0
    error("Demangler did not provide expected number of symbols");
503
0
    return;
504
0
  }
505
3
506
3
  // Cache the demangled names.
507
3
  unsigned I = 0;
508
3
  for (const auto &Function : Coverage.getCoveredFunctions())
509
9
    // On Windows, lines in the demangler's output file end with "\r\n".
510
9
    // Splitting by '\n' keeps '\r's, so cut them now.
511
9
    DC.DemangledNames[Function.Name] = Symbols[I++].rtrim();
512
3
}
513
514
void CodeCoverageTool::writeSourceFileView(StringRef SourceFile,
515
                                           CoverageMapping *Coverage,
516
                                           CoveragePrinter *Printer,
517
113
                                           bool ShowFilenames) {
518
113
  auto View = createSourceFileView(SourceFile, *Coverage);
519
113
  if (!View) {
520
11
    warning("The file '" + SourceFile + "' isn't covered.");
521
11
    return;
522
11
  }
523
102
524
102
  auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false);
525
102
  if (Error E = OSOrErr.takeError()) {
526
0
    error("Could not create view file!", toString(std::move(E)));
527
0
    return;
528
0
  }
529
102
  auto OS = std::move(OSOrErr.get());
530
102
531
102
  View->print(*OS.get(), /*Wholefile=*/true,
532
102
              /*ShowSourceName=*/ShowFilenames,
533
102
              /*ShowTitle=*/ViewOpts.hasOutputDirectory());
534
102
  Printer->closeViewFile(std::move(OS));
535
102
}
536
537
119
int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) {
538
119
  cl::opt<std::string> CovFilename(
539
119
      cl::Positional, cl::desc("Covered executable or object file."));
540
119
541
119
  cl::list<std::string> CovFilenames(
542
119
      "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore,
543
119
      cl::CommaSeparated);
544
119
545
119
  cl::list<std::string> InputSourceFiles(
546
119
      cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore);
547
119
548
119
  cl::opt<bool> DebugDumpCollectedPaths(
549
119
      "dump-collected-paths", cl::Optional, cl::Hidden,
550
119
      cl::desc("Show the collected paths to source files"));
551
119
552
119
  cl::opt<std::string, true> PGOFilename(
553
119
      "instr-profile", cl::Required, cl::location(this->PGOFilename),
554
119
      cl::desc(
555
119
          "File with the profile data obtained after an instrumented run"));
556
119
557
119
  cl::list<std::string> Arches(
558
119
      "arch", cl::desc("architectures of the coverage mapping binaries"));
559
119
560
119
  cl::opt<bool> DebugDump("dump", cl::Optional,
561
119
                          cl::desc("Show internal debug dump"));
562
119
563
119
  cl::opt<CoverageViewOptions::OutputFormat> Format(
564
119
      "format", cl::desc("Output format for line-based coverage reports"),
565
119
      cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text",
566
119
                            "Text output"),
567
119
                 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html",
568
119
                            "HTML output")),
569
119
      cl::init(CoverageViewOptions::OutputFormat::Text));
570
119
571
119
  cl::opt<std::string> PathRemap(
572
119
      "path-equivalence", cl::Optional,
573
119
      cl::desc("<from>,<to> Map coverage data paths to local source file "
574
119
               "paths"));
575
119
576
119
  cl::OptionCategory FilteringCategory("Function filtering options");
577
119
578
119
  cl::list<std::string> NameFilters(
579
119
      "name", cl::Optional,
580
119
      cl::desc("Show code coverage only for functions with the given name"),
581
119
      cl::ZeroOrMore, cl::cat(FilteringCategory));
582
119
583
119
  cl::list<std::string> NameFilterFiles(
584
119
      "name-whitelist", cl::Optional,
585
119
      cl::desc("Show code coverage only for functions listed in the given "
586
119
               "file"),
587
119
      cl::ZeroOrMore, cl::cat(FilteringCategory));
588
119
589
119
  cl::list<std::string> NameRegexFilters(
590
119
      "name-regex", cl::Optional,
591
119
      cl::desc("Show code coverage only for functions that match the given "
592
119
               "regular expression"),
593
119
      cl::ZeroOrMore, cl::cat(FilteringCategory));
594
119
595
119
  cl::list<std::string> IgnoreFilenameRegexFilters(
596
119
      "ignore-filename-regex", cl::Optional,
597
119
      cl::desc("Skip source code files with file paths that match the given "
598
119
               "regular expression"),
599
119
      cl::ZeroOrMore, cl::cat(FilteringCategory));
600
119
601
119
  cl::opt<double> RegionCoverageLtFilter(
602
119
      "region-coverage-lt", cl::Optional,
603
119
      cl::desc("Show code coverage only for functions with region coverage "
604
119
               "less than the given threshold"),
605
119
      cl::cat(FilteringCategory));
606
119
607
119
  cl::opt<double> RegionCoverageGtFilter(
608
119
      "region-coverage-gt", cl::Optional,
609
119
      cl::desc("Show code coverage only for functions with region coverage "
610
119
               "greater than the given threshold"),
611
119
      cl::cat(FilteringCategory));
612
119
613
119
  cl::opt<double> LineCoverageLtFilter(
614
119
      "line-coverage-lt", cl::Optional,
615
119
      cl::desc("Show code coverage only for functions with line coverage less "
616
119
               "than the given threshold"),
617
119
      cl::cat(FilteringCategory));
618
119
619
119
  cl::opt<double> LineCoverageGtFilter(
620
119
      "line-coverage-gt", cl::Optional,
621
119
      cl::desc("Show code coverage only for functions with line coverage "
622
119
               "greater than the given threshold"),
623
119
      cl::cat(FilteringCategory));
624
119
625
119
  cl::opt<cl::boolOrDefault> UseColor(
626
119
      "use-color", cl::desc("Emit colored output (default=autodetect)"),
627
119
      cl::init(cl::BOU_UNSET));
628
119
629
119
  cl::list<std::string> DemanglerOpts(
630
119
      "Xdemangler", cl::desc("<demangler-path>|<demangler-option>"));
631
119
632
119
  cl::opt<bool> RegionSummary(
633
119
      "show-region-summary", cl::Optional,
634
119
      cl::desc("Show region statistics in summary table"),
635
119
      cl::init(true));
636
119
637
119
  cl::opt<bool> InstantiationSummary(
638
119
      "show-instantiation-summary", cl::Optional,
639
119
      cl::desc("Show instantiation statistics in summary table"));
640
119
641
119
  cl::opt<bool> SummaryOnly(
642
119
      "summary-only", cl::Optional,
643
119
      cl::desc("Export only summary information for each source file"));
644
119
645
119
  cl::opt<unsigned> NumThreads(
646
119
      "num-threads", cl::init(0),
647
119
      cl::desc("Number of merge threads to use (default: autodetect)"));
648
119
  cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
649
119
                        cl::aliasopt(NumThreads));
650
119
651
119
  auto commandLineParser = [&, this](int argc, const char **argv) -> int {
652
119
    cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
653
119
    ViewOpts.Debug = DebugDump;
654
119
655
119
    if (!CovFilename.empty())
656
117
      ObjectFilenames.emplace_back(CovFilename);
657
119
    for (const std::string &Filename : CovFilenames)
658
4
      ObjectFilenames.emplace_back(Filename);
659
119
    if (ObjectFilenames.empty()) {
660
1
      errs() << "No filenames specified!\n";
661
1
      ::exit(1);
662
1
    }
663
118
664
118
    ViewOpts.Format = Format;
665
118
    switch (ViewOpts.Format) {
666
118
    case CoverageViewOptions::OutputFormat::Text:
667
92
      ViewOpts.Colors = UseColor == cl::BOU_UNSET
668
92
                            ? sys::Process::StandardOutHasColors()
669
92
                            : 
UseColor == cl::BOU_TRUE0
;
670
92
      break;
671
118
    case CoverageViewOptions::OutputFormat::HTML:
672
26
      if (UseColor == cl::BOU_FALSE)
673
0
        errs() << "Color output cannot be disabled when generating html.\n";
674
26
      ViewOpts.Colors = true;
675
26
      break;
676
118
    }
677
118
678
118
    // If path-equivalence was given and is a comma seperated pair then set
679
118
    // PathRemapping.
680
118
    auto EquivPair = StringRef(PathRemap).split(',');
681
118
    if (!(EquivPair.first.empty() && 
EquivPair.second.empty()26
))
682
92
      PathRemapping = EquivPair;
683
118
684
118
    // If a demangler is supplied, check if it exists and register it.
685
118
    if (DemanglerOpts.size()) {
686
3
      auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]);
687
3
      if (!DemanglerPathOrErr) {
688
0
        error("Could not find the demangler!",
689
0
              DemanglerPathOrErr.getError().message());
690
0
        return 1;
691
0
      }
692
3
      DemanglerOpts[0] = *DemanglerPathOrErr;
693
3
      ViewOpts.DemanglerOpts.swap(DemanglerOpts);
694
3
    }
695
118
696
118
    // Read in -name-whitelist files.
697
118
    if (!NameFilterFiles.empty()) {
698
2
      std::string SpecialCaseListErr;
699
2
      NameWhitelist =
700
2
          SpecialCaseList::create(NameFilterFiles, SpecialCaseListErr);
701
2
      if (!NameWhitelist)
702
0
        error(SpecialCaseListErr);
703
2
    }
704
118
705
118
    // Create the function filters
706
118
    if (!NameFilters.empty() || 
NameWhitelist101
||
!NameRegexFilters.empty()99
) {
707
21
      auto NameFilterer = llvm::make_unique<CoverageFilters>();
708
21
      for (const auto &Name : NameFilters)
709
21
        NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name));
710
21
      if (NameWhitelist)
711
2
        NameFilterer->push_back(
712
2
            llvm::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist));
713
21
      for (const auto &Regex : NameRegexFilters)
714
2
        NameFilterer->push_back(
715
2
            llvm::make_unique<NameRegexCoverageFilter>(Regex));
716
21
      Filters.push_back(std::move(NameFilterer));
717
21
    }
718
118
719
118
    if (RegionCoverageLtFilter.getNumOccurrences() ||
720
118
        RegionCoverageGtFilter.getNumOccurrences() ||
721
118
        LineCoverageLtFilter.getNumOccurrences() ||
722
118
        LineCoverageGtFilter.getNumOccurrences()) {
723
0
      auto StatFilterer = llvm::make_unique<CoverageFilters>();
724
0
      if (RegionCoverageLtFilter.getNumOccurrences())
725
0
        StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
726
0
            RegionCoverageFilter::LessThan, RegionCoverageLtFilter));
727
0
      if (RegionCoverageGtFilter.getNumOccurrences())
728
0
        StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>(
729
0
            RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter));
730
0
      if (LineCoverageLtFilter.getNumOccurrences())
731
0
        StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
732
0
            LineCoverageFilter::LessThan, LineCoverageLtFilter));
733
0
      if (LineCoverageGtFilter.getNumOccurrences())
734
0
        StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>(
735
0
            RegionCoverageFilter::GreaterThan, LineCoverageGtFilter));
736
0
      Filters.push_back(std::move(StatFilterer));
737
0
    }
738
118
739
118
    // Create the ignore filename filters.
740
118
    for (const auto &RE : IgnoreFilenameRegexFilters)
741
5
      IgnoreFilenameFilters.push_back(
742
5
          llvm::make_unique<NameRegexCoverageFilter>(RE));
743
118
744
118
    if (!Arches.empty()) {
745
8
      for (const std::string &Arch : Arches) {
746
8
        if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) {
747
1
          error("Unknown architecture: " + Arch);
748
1
          return 1;
749
1
        }
750
7
        CoverageArches.emplace_back(Arch);
751
7
      }
752
6
      
if (5
CoverageArches.size() != ObjectFilenames.size()5
) {
753
1
        error("Number of architectures doesn't match the number of objects");
754
1
        return 1;
755
1
      }
756
116
    }
757
116
758
116
    // IgnoreFilenameFilters are applied even when InputSourceFiles specified.
759
116
    for (const std::string &File : InputSourceFiles)
760
81
      collectPaths(File);
761
116
762
116
    if (DebugDumpCollectedPaths) {
763
3
      for (const std::string &SF : SourceFiles)
764
12
        outs() << SF << '\n';
765
3
      ::exit(0);
766
3
    }
767
113
768
113
    ViewOpts.ShowRegionSummary = RegionSummary;
769
113
    ViewOpts.ShowInstantiationSummary = InstantiationSummary;
770
113
    ViewOpts.ExportSummaryOnly = SummaryOnly;
771
113
    ViewOpts.NumThreads = NumThreads;
772
113
773
113
    return 0;
774
113
  };
775
119
776
119
  switch (Cmd) {
777
119
  case Show:
778
82
    return doShow(argc, argv, commandLineParser);
779
119
  case Report:
780
23
    return doReport(argc, argv, commandLineParser);
781
119
  case Export:
782
14
    return doExport(argc, argv, commandLineParser);
783
0
  }
784
0
  return 0;
785
0
}
786
787
int CodeCoverageTool::doShow(int argc, const char **argv,
788
82
                             CommandLineParserType commandLineParser) {
789
82
790
82
  cl::OptionCategory ViewCategory("Viewing options");
791
82
792
82
  cl::opt<bool> ShowLineExecutionCounts(
793
82
      "show-line-counts", cl::Optional,
794
82
      cl::desc("Show the execution counts for each line"), cl::init(true),
795
82
      cl::cat(ViewCategory));
796
82
797
82
  cl::opt<bool> ShowRegions(
798
82
      "show-regions", cl::Optional,
799
82
      cl::desc("Show the execution counts for each region"),
800
82
      cl::cat(ViewCategory));
801
82
802
82
  cl::opt<bool> ShowBestLineRegionsCounts(
803
82
      "show-line-counts-or-regions", cl::Optional,
804
82
      cl::desc("Show the execution counts for each line, or the execution "
805
82
               "counts for each region on lines that have multiple regions"),
806
82
      cl::cat(ViewCategory));
807
82
808
82
  cl::opt<bool> ShowExpansions("show-expansions", cl::Optional,
809
82
                               cl::desc("Show expanded source regions"),
810
82
                               cl::cat(ViewCategory));
811
82
812
82
  cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional,
813
82
                                   cl::desc("Show function instantiations"),
814
82
                                   cl::init(true), cl::cat(ViewCategory));
815
82
816
82
  cl::opt<std::string> ShowOutputDirectory(
817
82
      "output-dir", cl::init(""),
818
82
      cl::desc("Directory in which coverage information is written out"));
819
82
  cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"),
820
82
                                 cl::aliasopt(ShowOutputDirectory));
821
82
822
82
  cl::opt<uint32_t> TabSize(
823
82
      "tab-size", cl::init(2),
824
82
      cl::desc(
825
82
          "Set tab expansion size for html coverage reports (default = 2)"));
826
82
827
82
  cl::opt<std::string> ProjectTitle(
828
82
      "project-title", cl::Optional,
829
82
      cl::desc("Set project title for the coverage report"));
830
82
831
82
  auto Err = commandLineParser(argc, argv);
832
82
  if (Err)
833
2
    return Err;
834
80
835
80
  ViewOpts.ShowLineNumbers = true;
836
80
  ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 ||
837
80
                           
!ShowRegions77
||
ShowBestLineRegionsCounts2
;
838
80
  ViewOpts.ShowRegionMarkers = ShowRegions || 
ShowBestLineRegionsCounts75
;
839
80
  ViewOpts.ShowExpandedRegions = ShowExpansions;
840
80
  ViewOpts.ShowFunctionInstantiations = ShowInstantiations;
841
80
  ViewOpts.ShowOutputDirectory = ShowOutputDirectory;
842
80
  ViewOpts.TabSize = TabSize;
843
80
  ViewOpts.ProjectTitle = ProjectTitle;
844
80
845
80
  if (ViewOpts.hasOutputDirectory()) {
846
31
    if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) {
847
0
      error("Could not create output directory!", E.message());
848
0
      return 1;
849
0
    }
850
80
  }
851
80
852
80
  sys::fs::file_status Status;
853
80
  if (sys::fs::status(PGOFilename, Status)) {
854
0
    error("profdata file error: can not get the file status. \n");
855
0
    return 1;
856
0
  }
857
80
858
80
  auto ModifiedTime = Status.getLastModificationTime();
859
80
  std::string ModifiedTimeStr = to_string(ModifiedTime);
860
80
  size_t found = ModifiedTimeStr.rfind(':');
861
80
  ViewOpts.CreatedTimeStr = (found != std::string::npos)
862
80
                                ? 
"Created: " + ModifiedTimeStr.substr(0, found)77
863
80
                                : 
"Created: " + ModifiedTimeStr3
;
864
80
865
80
  auto Coverage = load();
866
80
  if (!Coverage)
867
1
    return 1;
868
79
869
79
  auto Printer = CoveragePrinter::create(ViewOpts);
870
79
871
79
  if (SourceFiles.empty())
872
26
    // Get the source files from the function coverage mapping.
873
89
    
for (StringRef Filename : Coverage->getUniqueSourceFiles())26
{
874
89
      if (!IgnoreFilenameFilters.matchesFilename(Filename))
875
88
        SourceFiles.push_back(Filename);
876
89
    }
877
79
878
79
  // Create an index out of the source files.
879
79
  if (ViewOpts.hasOutputDirectory()) {
880
31
    if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) {
881
1
      error("Could not create index file!", toString(std::move(E)));
882
1
      return 1;
883
1
    }
884
78
  }
885
78
886
78
  if (!Filters.empty()) {
887
20
    // Build the map of filenames to functions.
888
20
    std::map<llvm::StringRef, std::vector<const FunctionRecord *>>
889
20
        FilenameFunctionMap;
890
20
    for (const auto &SourceFile : SourceFiles)
891
26
      for (const auto &Function : Coverage->getCoveredFunctions(SourceFile))
892
57
        if (Filters.matches(*Coverage.get(), Function))
893
30
          FilenameFunctionMap[SourceFile].push_back(&Function);
894
20
895
20
    // Only print filter matching functions for each file.
896
21
    for (const auto &FileFunc : FilenameFunctionMap) {
897
21
      StringRef File = FileFunc.first;
898
21
      const auto &Functions = FileFunc.second;
899
21
900
21
      auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false);
901
21
      if (Error E = OSOrErr.takeError()) {
902
0
        error("Could not create view file!", toString(std::move(E)));
903
0
        return 1;
904
0
      }
905
21
      auto OS = std::move(OSOrErr.get());
906
21
907
21
      bool ShowTitle = ViewOpts.hasOutputDirectory();
908
30
      for (const auto *Function : Functions) {
909
30
        auto FunctionView = createFunctionView(*Function, *Coverage);
910
30
        if (!FunctionView) {
911
3
          warning("Could not read coverage for '" + Function->Name + "'.");
912
3
          continue;
913
3
        }
914
27
        FunctionView->print(*OS.get(), /*WholeFile=*/false,
915
27
                            /*ShowSourceName=*/true, ShowTitle);
916
27
        ShowTitle = false;
917
27
      }
918
21
919
21
      Printer->closeViewFile(std::move(OS));
920
21
    }
921
20
    return 0;
922
58
  }
923
58
924
58
  // Show files
925
58
  bool ShowFilenames =
926
58
      (SourceFiles.size() != 1) || 
ViewOpts.hasOutputDirectory()39
||
927
58
      
(ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML)26
;
928
58
929
58
  auto NumThreads = ViewOpts.NumThreads;
930
58
931
58
  // If NumThreads is not specified, auto-detect a good default.
932
58
  if (NumThreads == 0)
933
44
    NumThreads =
934
44
        std::max(1U, std::min(llvm::heavyweight_hardware_concurrency(),
935
44
                              unsigned(SourceFiles.size())));
936
58
937
58
  if (!ViewOpts.hasOutputDirectory() || 
NumThreads == 118
) {
938
52
    for (const std::string &SourceFile : SourceFiles)
939
98
      writeSourceFileView(SourceFile, Coverage.get(), Printer.get(),
940
98
                          ShowFilenames);
941
52
  } else {
942
6
    // In -output-dir mode, it's safe to use multiple threads to print files.
943
6
    ThreadPool Pool(NumThreads);
944
6
    for (const std::string &SourceFile : SourceFiles)
945
15
      Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile,
946
15
                 Coverage.get(), Printer.get(), ShowFilenames);
947
6
    Pool.wait();
948
6
  }
949
58
950
58
  return 0;
951
58
}
952
953
int CodeCoverageTool::doReport(int argc, const char **argv,
954
23
                               CommandLineParserType commandLineParser) {
955
23
  cl::opt<bool> ShowFunctionSummaries(
956
23
      "show-functions", cl::Optional, cl::init(false),
957
23
      cl::desc("Show coverage summaries for each function"));
958
23
959
23
  auto Err = commandLineParser(argc, argv);
960
23
  if (Err)
961
0
    return Err;
962
23
963
23
  if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) {
964
1
    error("HTML output for summary reports is not yet supported.");
965
1
    return 1;
966
1
  }
967
22
968
22
  auto Coverage = load();
969
22
  if (!Coverage)
970
1
    return 1;
971
21
972
21
  CoverageReport Report(ViewOpts, *Coverage.get());
973
21
  if (!ShowFunctionSummaries) {
974
16
    if (SourceFiles.empty())
975
13
      Report.renderFileReports(llvm::outs(), IgnoreFilenameFilters);
976
3
    else
977
3
      Report.renderFileReports(llvm::outs(), SourceFiles);
978
16
  } else {
979
5
    if (SourceFiles.empty()) {
980
1
      error("Source files must be specified when -show-functions=true is "
981
1
            "specified");
982
1
      return 1;
983
1
    }
984
4
985
4
    Report.renderFunctionReports(SourceFiles, DC, llvm::outs());
986
4
  }
987
21
  
return 020
;
988
21
}
989
990
int CodeCoverageTool::doExport(int argc, const char **argv,
991
14
                               CommandLineParserType commandLineParser) {
992
14
993
14
  auto Err = commandLineParser(argc, argv);
994
14
  if (Err)
995
0
    return Err;
996
14
997
14
  if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text) {
998
1
    error("Coverage data can only be exported as textual JSON.");
999
1
    return 1;
1000
1
  }
1001
13
1002
13
  auto Coverage = load();
1003
13
  if (!Coverage) {
1004
0
    error("Could not load coverage information");
1005
0
    return 1;
1006
0
  }
1007
13
1008
13
  auto Exporter = CoverageExporterJson(*Coverage.get(), ViewOpts, outs());
1009
13
1010
13
  if (SourceFiles.empty())
1011
12
    Exporter.renderRoot(IgnoreFilenameFilters);
1012
1
  else
1013
1
    Exporter.renderRoot(SourceFiles);
1014
13
1015
13
  return 0;
1016
13
}
1017
1018
82
int showMain(int argc, const char *argv[]) {
1019
82
  CodeCoverageTool Tool;
1020
82
  return Tool.run(CodeCoverageTool::Show, argc, argv);
1021
82
}
1022
1023
23
int reportMain(int argc, const char *argv[]) {
1024
23
  CodeCoverageTool Tool;
1025
23
  return Tool.run(CodeCoverageTool::Report, argc, argv);
1026
23
}
1027
1028
14
int exportMain(int argc, const char *argv[]) {
1029
14
  CodeCoverageTool Tool;
1030
14
  return Tool.run(CodeCoverageTool::Export, argc, argv);
1031
14
}