1 //===-- Statistic.cpp - Easy way to expose stats information --------------===//
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
7 //===----------------------------------------------------------------------===//
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.
14 // This is useful for reporting information like the number of instructions
15 // simplified, optimized or removed by various transformations, like this:
17 // static Statistic NumInstEliminated("GCSE", "Number of instructions killed");
19 // Later, in the code: ++NumInstEliminated;
21 //===----------------------------------------------------------------------===//
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"
38 /// -stats - Command line option to cause transformations to emit stats about
41 static cl::opt
<bool> Stats(
43 cl::desc("Enable statistics output from program (available with Asserts)"),
46 static cl::opt
<bool> StatsAsJSON("stats-json",
47 cl::desc("Display statistics as json data"),
51 static bool PrintOnExit
;
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
60 std::vector
<Statistic
*> Stats
;
62 friend void llvm::PrintStatistics();
63 friend void llvm::PrintStatistics(raw_ostream
&OS
);
64 friend void llvm::PrintStatisticsJSON(raw_ostream
&OS
);
66 /// Sort statistics by debugtype,name,description.
69 using const_iterator
= std::vector
<Statistic
*>::const_iterator
;
74 void addStatistic(Statistic
*S
) {
78 const_iterator
begin() const { return Stats
.begin(); }
79 const_iterator
end() const { return Stats
.end(); }
80 iterator_range
<const_iterator
> statistics() const {
81 return {begin(), end()};
86 } // end anonymous namespace
88 static ManagedStatic
<StatisticInfo
> StatInfo
;
89 static ManagedStatic
<sys::SmartMutex
<true> > StatLock
;
91 /// RegisterStatistic - The first time a statistic is bumped, this method is
93 void Statistic::RegisterStatistic() {
94 // If stats are enabled, inform StatInfo that this statistic should be
96 // llvm_shutdown calls destructors while holding the ManagedStatic mutex.
97 // These destructors end up calling PrintStatistics, which takes StatLock.
98 // Since dereferencing StatInfo and StatLock can require taking the
99 // ManagedStatic mutex, doing so with StatLock held would lead to a lock
100 // order inversion. To avoid that, we dereference the ManagedStatics first,
101 // and only take StatLock afterwards.
102 if (!Initialized
.load(std::memory_order_relaxed
)) {
103 sys::SmartMutex
<true> &Lock
= *StatLock
;
104 StatisticInfo
&SI
= *StatInfo
;
105 sys::SmartScopedLock
<true> Writer(Lock
);
106 // Check Initialized again after acquiring the lock.
107 if (Initialized
.load(std::memory_order_relaxed
))
109 if (Stats
|| Enabled
)
110 SI
.addStatistic(this);
112 // Remember we have been registered.
113 Initialized
.store(true, std::memory_order_release
);
117 StatisticInfo::StatisticInfo() {
118 // Ensure timergroup lists are created first so they are destructed after us.
119 TimerGroup::ConstructTimerLists();
122 // Print information when destroyed, iff command line option is specified.
123 StatisticInfo::~StatisticInfo() {
124 if (::Stats
|| PrintOnExit
)
125 llvm::PrintStatistics();
128 void llvm::EnableStatistics(bool PrintOnExit
) {
130 ::PrintOnExit
= PrintOnExit
;
133 bool llvm::AreStatisticsEnabled() {
134 return Enabled
|| Stats
;
137 void StatisticInfo::sort() {
138 llvm::stable_sort(Stats
, [](const Statistic
*LHS
, const Statistic
*RHS
) {
139 if (int Cmp
= std::strcmp(LHS
->getDebugType(), RHS
->getDebugType()))
142 if (int Cmp
= std::strcmp(LHS
->getName(), RHS
->getName()))
145 return std::strcmp(LHS
->getDesc(), RHS
->getDesc()) < 0;
149 void StatisticInfo::reset() {
150 sys::SmartScopedLock
<true> Writer(*StatLock
);
152 // Tell each statistic that it isn't registered so it has to register
153 // again. We're holding the lock so it won't be able to do so until we're
154 // finished. Once we've forced it to re-register (after we return), then zero
156 for (auto *Stat
: Stats
) {
157 // Value updates to a statistic that complete before this statement in the
158 // iteration for that statistic will be lost as intended.
159 Stat
->Initialized
= false;
163 // Clear the registration list and release the lock once we're done. Any
164 // pending updates from other threads will safely take effect after we return.
165 // That might not be what the user wants if they're measuring a compilation
166 // but it's their responsibility to prevent concurrent compilations to make
167 // a single compilation measurable.
171 void llvm::PrintStatistics(raw_ostream
&OS
) {
172 StatisticInfo
&Stats
= *StatInfo
;
174 // Figure out how long the biggest Value and Name fields are.
175 unsigned MaxDebugTypeLen
= 0, MaxValLen
= 0;
176 for (size_t i
= 0, e
= Stats
.Stats
.size(); i
!= e
; ++i
) {
177 MaxValLen
= std::max(MaxValLen
,
178 (unsigned)utostr(Stats
.Stats
[i
]->getValue()).size());
179 MaxDebugTypeLen
= std::max(MaxDebugTypeLen
,
180 (unsigned)std::strlen(Stats
.Stats
[i
]->getDebugType()));
185 // Print out the statistics header...
186 OS
<< "===" << std::string(73, '-') << "===\n"
187 << " ... Statistics Collected ...\n"
188 << "===" << std::string(73, '-') << "===\n\n";
190 // Print all of the statistics.
191 for (size_t i
= 0, e
= Stats
.Stats
.size(); i
!= e
; ++i
)
192 OS
<< format("%*u %-*s - %s\n",
193 MaxValLen
, Stats
.Stats
[i
]->getValue(),
194 MaxDebugTypeLen
, Stats
.Stats
[i
]->getDebugType(),
195 Stats
.Stats
[i
]->getDesc());
197 OS
<< '\n'; // Flush the output stream.
201 void llvm::PrintStatisticsJSON(raw_ostream
&OS
) {
202 sys::SmartScopedLock
<true> Reader(*StatLock
);
203 StatisticInfo
&Stats
= *StatInfo
;
207 // Print all of the statistics.
209 const char *delim
= "";
210 for (const Statistic
*Stat
: Stats
.Stats
) {
212 assert(yaml::needsQuotes(Stat
->getDebugType()) == yaml::QuotingType::None
&&
213 "Statistic group/type name is simple.");
214 assert(yaml::needsQuotes(Stat
->getName()) == yaml::QuotingType::None
&&
215 "Statistic name is simple");
216 OS
<< "\t\"" << Stat
->getDebugType() << '.' << Stat
->getName() << "\": "
221 TimerGroup::printAllJSONValues(OS
, delim
);
227 void llvm::PrintStatistics() {
228 #if LLVM_ENABLE_STATS
229 sys::SmartScopedLock
<true> Reader(*StatLock
);
230 StatisticInfo
&Stats
= *StatInfo
;
232 // Statistics not enabled?
233 if (Stats
.Stats
.empty()) return;
235 // Get the stream to write to.
236 std::unique_ptr
<raw_ostream
> OutStream
= CreateInfoOutputFile();
238 PrintStatisticsJSON(*OutStream
);
240 PrintStatistics(*OutStream
);
243 // Check if the -stats option is set instead of checking
244 // !Stats.Stats.empty(). In release builds, Statistics operators
245 // do nothing, so stats are never Registered.
247 // Get the stream to write to.
248 std::unique_ptr
<raw_ostream
> OutStream
= CreateInfoOutputFile();
249 (*OutStream
) << "Statistics are disabled. "
250 << "Build with asserts or with -DLLVM_ENABLE_STATS\n";
255 const std::vector
<std::pair
<StringRef
, unsigned>> llvm::GetStatistics() {
256 sys::SmartScopedLock
<true> Reader(*StatLock
);
257 std::vector
<std::pair
<StringRef
, unsigned>> ReturnStats
;
259 for (const auto &Stat
: StatInfo
->statistics())
260 ReturnStats
.emplace_back(Stat
->getName(), Stat
->getValue());
264 void llvm::ResetStatistics() {