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