Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Support/Statistic.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Statistic.cpp - Easy way to expose stats information --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the 'Statistic' class, which is designed to be an easy
10
// way to expose various success metrics from passes.  These statistics are
11
// printed at the end of a run, when the -stats command line option is enabled
12
// on the command line.
13
//
14
// This is useful for reporting information like the number of instructions
15
// simplified, optimized or removed by various transformations, like this:
16
//
17
// static Statistic NumInstEliminated("GCSE", "Number of instructions killed");
18
//
19
// Later, in the code: ++NumInstEliminated;
20
//
21
//===----------------------------------------------------------------------===//
22
23
#include "llvm/ADT/Statistic.h"
24
#include "llvm/ADT/StringExtras.h"
25
#include "llvm/Support/CommandLine.h"
26
#include "llvm/Support/Compiler.h"
27
#include "llvm/Support/Debug.h"
28
#include "llvm/Support/Format.h"
29
#include "llvm/Support/ManagedStatic.h"
30
#include "llvm/Support/Mutex.h"
31
#include "llvm/Support/Timer.h"
32
#include "llvm/Support/YAMLTraits.h"
33
#include "llvm/Support/raw_ostream.h"
34
#include <algorithm>
35
#include <cstring>
36
using namespace llvm;
37
38
/// -stats - Command line option to cause transformations to emit stats about
39
/// what they did.
40
///
41
static cl::opt<bool> Stats(
42
    "stats",
43
    cl::desc("Enable statistics output from program (available with Asserts)"),
44
    cl::Hidden);
45
46
static cl::opt<bool> StatsAsJSON("stats-json",
47
                                 cl::desc("Display statistics as json data"),
48
                                 cl::Hidden);
49
50
static bool Enabled;
51
static bool PrintOnExit;
52
53
namespace {
54
/// This class is used in a ManagedStatic so that it is created on demand (when
55
/// the first statistic is bumped) and destroyed only when llvm_shutdown is
56
/// called. We print statistics from the destructor.
57
/// This class is also used to look up statistic values from applications that
58
/// use LLVM.
59
class StatisticInfo {
60
  std::vector<Statistic*> Stats;
61
62
  friend void llvm::PrintStatistics();
63
  friend void llvm::PrintStatistics(raw_ostream &OS);
64
  friend void llvm::PrintStatisticsJSON(raw_ostream &OS);
65
66
  /// Sort statistics by debugtype,name,description.
67
  void sort();
68
public:
69
  using const_iterator = std::vector<Statistic *>::const_iterator;
70
71
  StatisticInfo();
72
  ~StatisticInfo();
73
74
0
  void addStatistic(Statistic *S) {
75
0
    Stats.push_back(S);
76
0
  }
77
78
1
  const_iterator begin() const { return Stats.begin(); }
79
1
  const_iterator end() const { return Stats.end(); }
80
1
  iterator_range<const_iterator> statistics() const {
81
1
    return {begin(), end()};
82
1
  }
83
84
  void reset();
85
};
86
} // end anonymous namespace
87
88
static ManagedStatic<StatisticInfo> StatInfo;
89
static ManagedStatic<sys::SmartMutex<true> > StatLock;
90
91
/// RegisterStatistic - The first time a statistic is bumped, this method is
92
/// called.
93
0
void Statistic::RegisterStatistic() {
94
0
  // If stats are enabled, inform StatInfo that this statistic should be
95
0
  // printed.
96
0
  // llvm_shutdown calls destructors while holding the ManagedStatic mutex.
97
0
  // These destructors end up calling PrintStatistics, which takes StatLock.
98
0
  // Since dereferencing StatInfo and StatLock can require taking the
99
0
  // ManagedStatic mutex, doing so with StatLock held would lead to a lock
100
0
  // order inversion. To avoid that, we dereference the ManagedStatics first,
101
0
  // and only take StatLock afterwards.
102
0
  if (!Initialized.load(std::memory_order_relaxed)) {
103
0
    sys::SmartMutex<true> &Lock = *StatLock;
104
0
    StatisticInfo &SI = *StatInfo;
105
0
    sys::SmartScopedLock<true> Writer(Lock);
106
0
    // Check Initialized again after acquiring the lock.
107
0
    if (Initialized.load(std::memory_order_relaxed))
108
0
      return;
109
0
    if (Stats || Enabled)
110
0
      SI.addStatistic(this);
111
0
112
0
    // Remember we have been registered.
113
0
    Initialized.store(true, std::memory_order_release);
114
0
  }
115
0
}
116
117
6
StatisticInfo::StatisticInfo() {
118
6
  // Ensure timergroup lists are created first so they are destructed after us.
119
6
  TimerGroup::ConstructTimerLists();
120
6
}
121
122
// Print information when destroyed, iff command line option is specified.
123
5
StatisticInfo::~StatisticInfo() {
124
5
  if (::Stats || PrintOnExit)
125
0
    llvm::PrintStatistics();
126
5
}
127
128
9
void llvm::EnableStatistics(bool PrintOnExit) {
129
9
  Enabled = true;
130
9
  ::PrintOnExit = PrintOnExit;
131
9
}
132
133
1.24k
bool llvm::AreStatisticsEnabled() {
134
1.24k
  return Enabled || Stats;
135
1.24k
}
136
137
5
void StatisticInfo::sort() {
138
5
  llvm::stable_sort(Stats, [](const Statistic *LHS, const Statistic *RHS) {
139
0
    if (int Cmp = std::strcmp(LHS->getDebugType(), RHS->getDebugType()))
140
0
      return Cmp < 0;
141
0
142
0
    if (int Cmp = std::strcmp(LHS->getName(), RHS->getName()))
143
0
      return Cmp < 0;
144
0
145
0
    return std::strcmp(LHS->getDesc(), RHS->getDesc()) < 0;
146
0
  });
147
5
}
148
149
1
void StatisticInfo::reset() {
150
1
  sys::SmartScopedLock<true> Writer(*StatLock);
151
1
152
1
  // Tell each statistic that it isn't registered so it has to register
153
1
  // again. We're holding the lock so it won't be able to do so until we're
154
1
  // finished. Once we've forced it to re-register (after we return), then zero
155
1
  // the value.
156
1
  for (auto *Stat : Stats) {
157
0
    // Value updates to a statistic that complete before this statement in the
158
0
    // iteration for that statistic will be lost as intended.
159
0
    Stat->Initialized = false;
160
0
    Stat->Value = 0;
161
0
  }
162
1
163
1
  // Clear the registration list and release the lock once we're done. Any
164
1
  // pending updates from other threads will safely take effect after we return.
165
1
  // That might not be what the user wants if they're measuring a compilation
166
1
  // but it's their responsibility to prevent concurrent compilations to make
167
1
  // a single compilation measurable.
168
1
  Stats.clear();
169
1
}
170
171
4
void llvm::PrintStatistics(raw_ostream &OS) {
172
4
  StatisticInfo &Stats = *StatInfo;
173
4
174
4
  // Figure out how long the biggest Value and Name fields are.
175
4
  unsigned MaxDebugTypeLen = 0, MaxValLen = 0;
176
4
  for (size_t i = 0, e = Stats.Stats.size(); i != e; 
++i0
) {
177
0
    MaxValLen = std::max(MaxValLen,
178
0
                         (unsigned)utostr(Stats.Stats[i]->getValue()).size());
179
0
    MaxDebugTypeLen = std::max(MaxDebugTypeLen,
180
0
                         (unsigned)std::strlen(Stats.Stats[i]->getDebugType()));
181
0
  }
182
4
183
4
  Stats.sort();
184
4
185
4
  // Print out the statistics header...
186
4
  OS << "===" << std::string(73, '-') << "===\n"
187
4
     << "                          ... Statistics Collected ...\n"
188
4
     << "===" << std::string(73, '-') << "===\n\n";
189
4
190
4
  // Print all of the statistics.
191
4
  for (size_t i = 0, e = Stats.Stats.size(); i != e; 
++i0
)
192
0
    OS << format("%*u %-*s - %s\n",
193
0
                 MaxValLen, Stats.Stats[i]->getValue(),
194
0
                 MaxDebugTypeLen, Stats.Stats[i]->getDebugType(),
195
0
                 Stats.Stats[i]->getDesc());
196
4
197
4
  OS << '\n';  // Flush the output stream.
198
4
  OS.flush();
199
4
}
200
201
1
void llvm::PrintStatisticsJSON(raw_ostream &OS) {
202
1
  sys::SmartScopedLock<true> Reader(*StatLock);
203
1
  StatisticInfo &Stats = *StatInfo;
204
1
205
1
  Stats.sort();
206
1
207
1
  // Print all of the statistics.
208
1
  OS << "{\n";
209
1
  const char *delim = "";
210
1
  for (const Statistic *Stat : Stats.Stats) {
211
0
    OS << delim;
212
0
    assert(yaml::needsQuotes(Stat->getDebugType()) == yaml::QuotingType::None &&
213
0
           "Statistic group/type name is simple.");
214
0
    assert(yaml::needsQuotes(Stat->getName()) == yaml::QuotingType::None &&
215
0
           "Statistic name is simple");
216
0
    OS << "\t\"" << Stat->getDebugType() << '.' << Stat->getName() << "\": "
217
0
       << Stat->getValue();
218
0
    delim = ",\n";
219
0
  }
220
1
  // Print timers.
221
1
  TimerGroup::printAllJSONValues(OS, delim);
222
1
223
1
  OS << "\n}\n";
224
1
  OS.flush();
225
1
}
226
227
0
void llvm::PrintStatistics() {
228
#if LLVM_ENABLE_STATS
229
  sys::SmartScopedLock<true> Reader(*StatLock);
230
  StatisticInfo &Stats = *StatInfo;
231
232
  // Statistics not enabled?
233
  if (Stats.Stats.empty()) return;
234
235
  // Get the stream to write to.
236
  std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
237
  if (StatsAsJSON)
238
    PrintStatisticsJSON(*OutStream);
239
  else
240
    PrintStatistics(*OutStream);
241
242
#else
243
  // Check if the -stats option is set instead of checking
244
0
  // !Stats.Stats.empty().  In release builds, Statistics operators
245
0
  // do nothing, so stats are never Registered.
246
0
  if (Stats) {
247
0
    // Get the stream to write to.
248
0
    std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
249
0
    (*OutStream) << "Statistics are disabled.  "
250
0
                 << "Build with asserts or with -DLLVM_ENABLE_STATS\n";
251
0
  }
252
0
#endif
253
0
}
254
255
1
const std::vector<std::pair<StringRef, unsigned>> llvm::GetStatistics() {
256
1
  sys::SmartScopedLock<true> Reader(*StatLock);
257
1
  std::vector<std::pair<StringRef, unsigned>> ReturnStats;
258
1
259
1
  for (const auto &Stat : StatInfo->statistics())
260
0
    ReturnStats.emplace_back(Stat->getName(), Stat->getValue());
261
1
  return ReturnStats;
262
1
}
263
264
1
void llvm::ResetStatistics() {
265
1
  StatInfo->reset();
266
1
}