[llvm] [ADT] Introduce LocalStatistic to allow per-pass/per-function stats (PR #187801)

Tobias Stadler via llvm-commits llvm-commits at lists.llvm.org
Fri Mar 20 17:46:09 PDT 2026


https://github.com/tobias-stadler updated https://github.com/llvm/llvm-project/pull/187801

>From 2d5e02816f7573bf706e055f24991f96d59d1559 Mon Sep 17 00:00:00 2001
From: Tobias Stadler <mail at stadler-tobias.de>
Date: Fri, 20 Mar 2026 14:44:33 -0700
Subject: [PATCH 1/2] [spr] initial version

Created using spr 1.3.8-wip
---
 llvm/include/llvm/ADT/Statistic.h    | 118 +++++++++++++--
 llvm/lib/Support/Statistic.cpp       |  73 ++++++++--
 llvm/unittests/ADT/StatisticTest.cpp | 208 ++++++++++++++++++++++-----
 3 files changed, 338 insertions(+), 61 deletions(-)

diff --git a/llvm/include/llvm/ADT/Statistic.h b/llvm/include/llvm/ADT/Statistic.h
index 75d608beb0134..cae9eec84bdf5 100644
--- a/llvm/include/llvm/ADT/Statistic.h
+++ b/llvm/include/llvm/ADT/Statistic.h
@@ -21,11 +21,17 @@
 ///
 /// NOTE: Statistics *must* be declared as global variables.
 ///
+/// LOCAL_STATISTIC provides thread-local counters that are incremented
+/// alongside their corresponding global statistic. They can be independently
+/// reset and queried per-thread. Intended for counting statistics
+/// per-pass/per-function.
+///
 //===----------------------------------------------------------------------===//
 
 #ifndef LLVM_ADT_STATISTIC_H
 #define LLVM_ADT_STATISTIC_H
 
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/Support/Compiler.h"
 #include <atomic>
@@ -45,9 +51,10 @@ namespace llvm {
 
 class raw_ostream;
 class raw_fd_ostream;
-class StringRef;
 
 class TrackingStatistic {
+  friend class LocalTrackingStatistic;
+
 public:
   const char *const DebugType;
   const char *const Name;
@@ -129,6 +136,63 @@ class TrackingStatistic {
   LLVM_ABI void RegisterStatistic();
 };
 
+class LocalTrackingStatistic {
+public:
+  TrackingStatistic *GlobalStat;
+  uint64_t Value = 0;
+  bool Initialized = false;
+
+  LocalTrackingStatistic(TrackingStatistic &Statistic)
+      : GlobalStat(&Statistic) {}
+
+  const char *getDebugType() const { return GlobalStat->DebugType; }
+  const char *getName() const { return GlobalStat->Name; }
+  const char *getDesc() const { return GlobalStat->Desc; }
+
+  uint64_t getValue() const { return Value; }
+
+  // Allow use of this class as the value itself.
+  operator uint64_t() const { return Value; }
+
+  const LocalTrackingStatistic &operator++() {
+    init();
+    ++*GlobalStat;
+    ++Value;
+    return *this;
+  }
+
+  uint64_t operator++(int) {
+    init();
+    ++*GlobalStat;
+    return Value++;
+  }
+
+  const LocalTrackingStatistic &operator+=(const uint64_t &V) {
+    init();
+    *GlobalStat += V;
+    Value += V;
+    return *this;
+  }
+
+  // Delete other operators offered by TrackingStatistic. These can't be
+  // transparently passed through to the global statistic in most cases.
+  void updateMax(uint64_t V) = delete;
+  const LocalTrackingStatistic &operator=(uint64_t Val) = delete;
+  const LocalTrackingStatistic &operator--() = delete;
+  uint64_t operator--(int) = delete;
+  const LocalTrackingStatistic &operator-=(const uint64_t &V) = delete;
+
+protected:
+  void init() {
+    if (Initialized)
+      return;
+    Value = 0;
+    RegisterStatistic();
+  }
+
+  LLVM_ABI void RegisterStatistic();
+};
+
 class NoopStatistic {
 public:
   constexpr NoopStatistic(const char * /*DebugType*/, const char * /*Name*/,
@@ -156,22 +220,48 @@ class NoopStatistic {
   void updateMax(uint64_t V) {}
 };
 
+struct StatisticVal {
+  StringRef DebugType;
+  StringRef Name;
+  uint64_t Value;
+
+  StatisticVal(StringRef DebugType, StringRef Name, uint64_t Value)
+      : DebugType(DebugType), Name(Name), Value(Value) {}
+};
+
 #if LLVM_ENABLE_STATS
-using Statistic = TrackingStatistic;
+using GlobalStatistic = TrackingStatistic;
+using LocalStatistic = LocalTrackingStatistic;
 #else
-using Statistic = NoopStatistic;
+using GlobalStatistic = NoopStatistic;
+using LocalStatistic = NoopStatistic;
 #endif
+using Statistic = GlobalStatistic;
 
-// STATISTIC - A macro to make definition of statistics really simple.  This
-// automatically passes the DEBUG_TYPE of the file into the statistic.
 #if LLVM_ENABLE_STATS
-#define STATISTIC(VARNAME, DESC)                                               \
-  static llvm::Statistic VARNAME = {DEBUG_TYPE, #VARNAME, DESC}
+#define GLOBAL_STATISTIC(VARNAME, DESC)                                        \
+  static llvm::GlobalStatistic VARNAME = {DEBUG_TYPE, #VARNAME, DESC}
+
+#define LOCAL_STATISTIC(VARNAME, DESC)                                         \
+  static llvm::GlobalStatistic VARNAME##_Global = {DEBUG_TYPE, #VARNAME,       \
+                                                   DESC};                      \
+  static thread_local llvm::LocalStatistic VARNAME = {VARNAME##_Global}
 #else
-#define STATISTIC(VARNAME, DESC)                                               \
-  static llvm::Statistic VARNAME [[maybe_unused]] = {DEBUG_TYPE, #VARNAME, DESC}
+#define GLOBAL_STATISTIC(VARNAME, DESC)                                        \
+  static llvm::GlobalStatistic VARNAME                                         \
+      [[maybe_unused]] = {DEBUG_TYPE, #VARNAME, DESC}
+
+#define LOCAL_STATISTIC(VARNAME, DESC)                                         \
+  static llvm::GlobalStatistic VARNAME##_Global = {DEBUG_TYPE, #VARNAME,       \
+                                                   DESC};                      \
+  static thread_local llvm::LocalStatistic VARNAME                             \
+      [[maybe_unused]] = {VARNAME##_Global}
 #endif
 
+// STATISTIC - A macro to make definition of statistics really simple.  This
+// automatically passes the DEBUG_TYPE of the file into the statistic.
+#define STATISTIC(VARNAME, DESC) GLOBAL_STATISTIC(VARNAME, DESC)
+
 // ALWAYS_ENABLED_STATISTIC - A macro to define a statistic like STATISTIC but
 // it is enabled even if LLVM_ENABLE_STATS is off.
 #define ALWAYS_ENABLED_STATISTIC(VARNAME, DESC)                                \
@@ -207,6 +297,12 @@ LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS);
 /// completes.
 LLVM_ABI std::vector<std::pair<StringRef, uint64_t>> GetStatistics();
 
+/// Get the local statistics. Returns statistics collected on the current thread
+/// since the last call to ResetLocalStatistics(). Results are sorted by debug
+/// type, then by name. Local statistics also increment their corresponding
+/// global statistic.
+LLVM_ABI std::vector<StatisticVal> GetLocalStatistics();
+
 /// Reset the statistics. This can be used to zero and de-register the
 /// statistics in order to measure a compilation.
 ///
@@ -222,6 +318,10 @@ LLVM_ABI std::vector<std::pair<StringRef, uint64_t>> GetStatistics();
 /// GetStatistics().
 LLVM_ABI void ResetStatistics();
 
+/// Reset the local statistics. This zeros and de-registers all local
+/// statistics on the current thread without affecting global statistics.
+LLVM_ABI void ResetLocalStatistics();
+
 } // end namespace llvm
 
 #endif // LLVM_ADT_STATISTIC_H
diff --git a/llvm/lib/Support/Statistic.cpp b/llvm/lib/Support/Statistic.cpp
index 24ef3e9abaebc..0c44bf92b8510 100644
--- a/llvm/lib/Support/Statistic.cpp
+++ b/llvm/lib/Support/Statistic.cpp
@@ -58,6 +58,18 @@ void llvm::initStatisticOptions() {
 }
 
 namespace {
+
+/// Comparator for sorting statistics by debugtype,name,description.
+template <typename T> struct StatisticCmp {
+  bool operator()(const T *LHS, const T *RHS) const {
+    if (int Cmp = std::strcmp(LHS->getDebugType(), RHS->getDebugType()))
+      return Cmp < 0;
+    if (int Cmp = std::strcmp(LHS->getName(), RHS->getName()))
+      return Cmp < 0;
+    return std::strcmp(LHS->getDesc(), RHS->getDesc()) < 0;
+  }
+};
+
 /// This class is used in a ManagedStatic so that it is created on demand (when
 /// the first statistic is bumped) and destroyed only when llvm_shutdown is
 /// called. We print statistics from the destructor.
@@ -71,7 +83,8 @@ class StatisticInfo {
   friend void llvm::PrintStatisticsJSON(raw_ostream &OS);
 
   /// Sort statistics by debugtype,name,description.
-  void sort();
+  void sort() { llvm::stable_sort(Stats, StatisticCmp<TrackingStatistic>()); }
+
 public:
   using const_iterator = std::vector<TrackingStatistic *>::const_iterator;
 
@@ -88,10 +101,34 @@ class StatisticInfo {
 
   void reset();
 };
+
+class LocalStatisticInfo {
+  std::vector<LocalTrackingStatistic *> Stats;
+
+public:
+  using const_iterator = decltype(Stats)::const_iterator;
+
+  void addStatistic(LocalTrackingStatistic *S) { Stats.push_back(S); }
+
+  /// Sort statistics by debugtype,name,description.
+  void sort() {
+    llvm::stable_sort(Stats, StatisticCmp<LocalTrackingStatistic>());
+  }
+
+  const_iterator begin() const { return Stats.begin(); }
+  const_iterator end() const { return Stats.end(); }
+
+  void reset() {
+    for (auto *Stat : Stats)
+      Stat->Initialized = false;
+    Stats.clear();
+  }
+};
 } // end anonymous namespace
 
 static ManagedStatic<StatisticInfo> StatInfo;
-static ManagedStatic<sys::SmartMutex<true> > StatLock;
+static ManagedStatic<sys::SmartMutex<true>> StatLock;
+static thread_local LocalStatisticInfo LocalStatInfo;
 
 /// RegisterStatistic - The first time a statistic is bumped, this method is
 /// called.
@@ -119,6 +156,13 @@ void TrackingStatistic::RegisterStatistic() {
   }
 }
 
+void LocalTrackingStatistic::RegisterStatistic() {
+  assert(!Initialized);
+  if (AreStatisticsEnabled())
+    LocalStatInfo.addStatistic(this);
+  Initialized = true;
+}
+
 StatisticInfo::StatisticInfo() {
   // Ensure that necessary timer global objects are created first so they are
   // destructed after us.
@@ -138,19 +182,6 @@ void llvm::EnableStatistics(bool DoPrintOnExit) {
 
 bool llvm::AreStatisticsEnabled() { return Enabled || EnableStats; }
 
-void StatisticInfo::sort() {
-  llvm::stable_sort(
-      Stats, [](const TrackingStatistic *LHS, const TrackingStatistic *RHS) {
-        if (int Cmp = std::strcmp(LHS->getDebugType(), RHS->getDebugType()))
-          return Cmp < 0;
-
-        if (int Cmp = std::strcmp(LHS->getName(), RHS->getName()))
-          return Cmp < 0;
-
-        return std::strcmp(LHS->getDesc(), RHS->getDesc()) < 0;
-      });
-}
-
 void StatisticInfo::reset() {
   sys::SmartScopedLock<true> Writer(*StatLock);
 
@@ -263,6 +294,18 @@ std::vector<std::pair<StringRef, uint64_t>> llvm::GetStatistics() {
   return ReturnStats;
 }
 
+std::vector<StatisticVal> llvm::GetLocalStatistics() {
+  std::vector<StatisticVal> ReturnStats;
+  LocalStatInfo.sort();
+  for (const auto &Stat : LocalStatInfo)
+    ReturnStats.emplace_back(Stat->getDebugType(), Stat->getName(),
+                             Stat->getValue());
+  return ReturnStats;
+}
+
 void llvm::ResetStatistics() {
+  LocalStatInfo.reset();
   StatInfo->reset();
 }
+
+void llvm::ResetLocalStatistics() { LocalStatInfo.reset(); }
diff --git a/llvm/unittests/ADT/StatisticTest.cpp b/llvm/unittests/ADT/StatisticTest.cpp
index 91bc7f24c7f2f..52435f23c63b3 100644
--- a/llvm/unittests/ADT/StatisticTest.cpp
+++ b/llvm/unittests/ADT/StatisticTest.cpp
@@ -7,6 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 using namespace llvm;
@@ -20,15 +21,13 @@ STATISTIC(Counter2, "Counts other things");
 ALWAYS_ENABLED_STATISTIC(AlwaysCounter, "Counts things always");
 
 #if LLVM_ENABLE_STATS
-static void
-extractCounters(const std::vector<std::pair<StringRef, uint64_t>> &Range,
-                OptionalStatistic &S1, OptionalStatistic &S2) {
-  for (const auto &S : Range) {
-    if (S.first == "Counter")
-      S1 = S;
-    if (S.first == "Counter2")
-      S2 = S;
-  }
+static OptionalStatistic
+findStat(const std::vector<std::pair<StringRef, uint64_t>> &Stats,
+         StringRef Name) {
+  auto It = llvm::find_if(Stats, [&](const std::pair<StringRef, uint64_t> &S) {
+    return S.first == Name;
+  });
+  return It != Stats.end() ? std::optional(*It) : std::nullopt;
 }
 #endif
 
@@ -85,15 +84,13 @@ TEST(StatisticTest, API) {
 #if LLVM_ENABLE_STATS
   {
     const auto Range1 = GetStatistics();
-    EXPECT_NE(Range1.begin(), Range1.end());
-    EXPECT_EQ(Range1.begin() + 1, Range1.end());
+    EXPECT_EQ(Range1.size(), 1u);
 
-    OptionalStatistic S1;
-    OptionalStatistic S2;
-    extractCounters(Range1, S1, S2);
+    auto S1 = findStat(Range1, "Counter");
+    auto S2 = findStat(Range1, "Counter2");
 
-    EXPECT_EQ(S1.has_value(), true);
-    EXPECT_EQ(S2.has_value(), false);
+    EXPECT_TRUE(S1.has_value());
+    EXPECT_FALSE(S2.has_value());
   }
 
   // Counter2 will be registered when it's first touched.
@@ -101,19 +98,16 @@ TEST(StatisticTest, API) {
 
   {
     const auto Range = GetStatistics();
-    EXPECT_NE(Range.begin(), Range.end());
-    EXPECT_EQ(Range.begin() + 2, Range.end());
-
-    OptionalStatistic S1;
-    OptionalStatistic S2;
-    extractCounters(Range, S1, S2);
+    EXPECT_EQ(Range.size(), 2u);
 
-    EXPECT_EQ(S1.has_value(), true);
-    EXPECT_EQ(S2.has_value(), true);
+    auto S1 = findStat(Range, "Counter");
+    auto S2 = findStat(Range, "Counter2");
 
+    ASSERT_TRUE(S1.has_value());
     EXPECT_EQ(S1->first, "Counter");
     EXPECT_EQ(S1->second, 2u);
 
+    ASSERT_TRUE(S2.has_value());
     EXPECT_EQ(S2->first, "Counter2");
     EXPECT_EQ(S2->second, 1u);
   }
@@ -129,14 +123,14 @@ TEST(StatisticTest, API) {
   ResetStatistics();
   {
     auto Range = GetStatistics();
-    EXPECT_EQ(Range.begin(), Range.end());
+    EXPECT_TRUE(Range.empty());
     EXPECT_EQ(Counter, 0u);
     EXPECT_EQ(Counter2, 0u);
-    OptionalStatistic S1;
-    OptionalStatistic S2;
-    extractCounters(Range, S1, S2);
-    EXPECT_EQ(S1.has_value(), false);
-    EXPECT_EQ(S2.has_value(), false);
+
+    auto S1 = findStat(Range, "Counter");
+    auto S2 = findStat(Range, "Counter2");
+    EXPECT_FALSE(S1.has_value());
+    EXPECT_FALSE(S2.has_value());
   }
 
   // Now check that they successfully re-register and count.
@@ -145,20 +139,18 @@ TEST(StatisticTest, API) {
 
   {
     auto Range = GetStatistics();
-    EXPECT_EQ(Range.begin() + 2, Range.end());
+    EXPECT_EQ(Range.size(), 2u);
     EXPECT_EQ(Counter, 1u);
     EXPECT_EQ(Counter2, 1u);
 
-    OptionalStatistic S1;
-    OptionalStatistic S2;
-    extractCounters(Range, S1, S2);
-
-    EXPECT_EQ(S1.has_value(), true);
-    EXPECT_EQ(S2.has_value(), true);
+    auto S1 = findStat(Range, "Counter");
+    auto S2 = findStat(Range, "Counter2");
 
+    ASSERT_TRUE(S1.has_value());
     EXPECT_EQ(S1->first, "Counter");
     EXPECT_EQ(S1->second, 1u);
 
+    ASSERT_TRUE(S2.has_value());
     EXPECT_EQ(S2->first, "Counter2");
     EXPECT_EQ(S2->second, 1u);
   }
@@ -169,4 +161,146 @@ TEST(StatisticTest, API) {
 #endif
 }
 
+#undef DEBUG_TYPE
+#define DEBUG_TYPE "local-unittest"
+LOCAL_STATISTIC(LocalCounter, "Counts things locally");
+LOCAL_STATISTIC(LocalCounter2, "Counts other things locally");
+
+#undef DEBUG_TYPE
+#define DEBUG_TYPE "other-unittest"
+LOCAL_STATISTIC(OtherCounter, "Counts things in another debug type");
+
+#if LLVM_ENABLE_STATS
+static std::optional<StatisticVal>
+findLocalStat(const std::vector<StatisticVal> &Stats, StringRef Name) {
+  auto It = llvm::find_if(
+      Stats, [&](const StatisticVal &S) { return S.Name == Name; });
+  return It != Stats.end() ? std::optional(*It) : std::nullopt;
+}
+#endif
+
+TEST(StatisticTest, LocalStatistics) {
+  EnableStatistics();
+  ResetStatistics();
+  ResetLocalStatistics();
+
+#if LLVM_ENABLE_STATS
+  // Verify empty after reset.
+  {
+    auto Local = GetLocalStatistics();
+    EXPECT_TRUE(Local.empty());
+  }
+
+  // Increment local counters and verify basic functionality.
+  LocalCounter++;
+  LocalCounter++;
+  LocalCounter2++;
+
+  EXPECT_EQ(LocalCounter, 2u);
+  EXPECT_EQ(LocalCounter2, 1u);
+
+  {
+    auto Local = GetLocalStatistics();
+    EXPECT_EQ(Local.size(), 2u);
+
+    auto S1 = findLocalStat(Local, "LocalCounter");
+    auto S2 = findLocalStat(Local, "LocalCounter2");
+
+    ASSERT_TRUE(S1.has_value());
+    EXPECT_EQ(S1->DebugType, "local-unittest");
+    EXPECT_EQ(S1->Value, 2u);
+
+    ASSERT_TRUE(S2.has_value());
+    EXPECT_EQ(S2->DebugType, "local-unittest");
+    EXPECT_EQ(S2->Value, 1u);
+  }
+
+  // Verify that global stats are kept in sync.
+  {
+    auto Global = GetStatistics();
+    auto GS1 = findStat(Global, "LocalCounter");
+    auto GS2 = findStat(Global, "LocalCounter2");
+
+    ASSERT_TRUE(GS1.has_value());
+    EXPECT_EQ(GS1->second, 2u);
+
+    ASSERT_TRUE(GS2.has_value());
+    EXPECT_EQ(GS2->second, 1u);
+  }
+
+  // Reset local stats and verify they are cleared while globals remain.
+  ResetLocalStatistics();
+
+  {
+    auto Local = GetLocalStatistics();
+    EXPECT_TRUE(Local.empty());
+  }
+
+  {
+    auto Global = GetStatistics();
+    auto GS1 = findStat(Global, "LocalCounter");
+    ASSERT_TRUE(GS1.has_value());
+    EXPECT_EQ(GS1->second, 2u);
+  }
+
+  // Verify local stats work again after reset.
+  LocalCounter++;
+  LocalCounter2 += 5;
+  {
+    auto Local = GetLocalStatistics();
+    EXPECT_EQ(Local.size(), 2u);
+
+    auto S1 = findLocalStat(Local, "LocalCounter");
+    auto S2 = findLocalStat(Local, "LocalCounter2");
+
+    ASSERT_TRUE(S1.has_value());
+    EXPECT_EQ(S1->Value, 1u);
+
+    ASSERT_TRUE(S2.has_value());
+    EXPECT_EQ(S2->Value, 5u);
+  }
+
+  // Global stats should reflect cumulative totals.
+  {
+    auto Global = GetStatistics();
+    auto GS1 = findStat(Global, "LocalCounter");
+    auto GS2 = findStat(Global, "LocalCounter2");
+
+    ASSERT_TRUE(GS1.has_value());
+    EXPECT_EQ(GS1->second, 3u);
+
+    ASSERT_TRUE(GS2.has_value());
+    EXPECT_EQ(GS2->second, 6u);
+  }
+
+  // Verify sorting across different debug types.
+  ResetLocalStatistics();
+  OtherCounter += 10;
+  LocalCounter++;
+  LocalCounter2 += 3;
+  {
+    auto Local = GetLocalStatistics();
+    EXPECT_EQ(Local.size(), 3u);
+
+    // Results should be sorted by debug type, then by name.
+    EXPECT_EQ(Local[0].DebugType, "local-unittest");
+    EXPECT_EQ(Local[0].Name, "LocalCounter");
+    EXPECT_EQ(Local[0].Value, 1u);
+
+    EXPECT_EQ(Local[1].DebugType, "local-unittest");
+    EXPECT_EQ(Local[1].Name, "LocalCounter2");
+    EXPECT_EQ(Local[1].Value, 3u);
+
+    EXPECT_EQ(Local[2].DebugType, "other-unittest");
+    EXPECT_EQ(Local[2].Name, "OtherCounter");
+    EXPECT_EQ(Local[2].Value, 10u);
+  }
+#else
+  LocalCounter++;
+  LocalCounter2++;
+  auto Local = GetLocalStatistics();
+  EXPECT_TRUE(Local.empty());
+#endif
+}
+
 } // end anonymous namespace

>From 40a01ee8d3970563c0b000e6e0aea4f58e353719 Mon Sep 17 00:00:00 2001
From: Tobias Stadler <mail at stadler-tobias.de>
Date: Fri, 20 Mar 2026 17:45:57 -0700
Subject: [PATCH 2/2] Eliminate global constructors (hopefully)

Created using spr 1.3.8-wip
---
 llvm/include/llvm/ADT/Statistic.h    | 18 ++++++++++--
 llvm/lib/Support/Statistic.cpp       | 43 +++++++++++++++++++++-------
 llvm/unittests/ADT/StatisticTest.cpp | 27 +++++++++++++----
 3 files changed, 70 insertions(+), 18 deletions(-)

diff --git a/llvm/include/llvm/ADT/Statistic.h b/llvm/include/llvm/ADT/Statistic.h
index cae9eec84bdf5..0523c80bca5a5 100644
--- a/llvm/include/llvm/ADT/Statistic.h
+++ b/llvm/include/llvm/ADT/Statistic.h
@@ -49,6 +49,13 @@
 
 namespace llvm {
 
+class LocalStatisticInfo;
+
+/// Pointer to the thread-local local statistics storage. Non-null when local
+/// statistics are enabled on the current thread. Set by
+/// EnableLocalStatistics(), cleared by ShutdownLocalStatistics().
+LLVM_ABI extern thread_local LocalStatisticInfo *LocalStatInfo;
+
 class raw_ostream;
 class raw_fd_ostream;
 
@@ -142,7 +149,7 @@ class LocalTrackingStatistic {
   uint64_t Value = 0;
   bool Initialized = false;
 
-  LocalTrackingStatistic(TrackingStatistic &Statistic)
+  constexpr LocalTrackingStatistic(TrackingStatistic &Statistic)
       : GlobalStat(&Statistic) {}
 
   const char *getDebugType() const { return GlobalStat->DebugType; }
@@ -184,7 +191,7 @@ class LocalTrackingStatistic {
 
 protected:
   void init() {
-    if (Initialized)
+    if (!LocalStatInfo || Initialized)
       return;
     Value = 0;
     RegisterStatistic();
@@ -297,6 +304,13 @@ LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS);
 /// completes.
 LLVM_ABI std::vector<std::pair<StringRef, uint64_t>> GetStatistics();
 
+/// Enable local statistics collection on the current thread. Call
+/// ShutdownLocalStatistics() to clean up.
+LLVM_ABI void EnableLocalStatistics();
+
+/// Shut down local statistics on the current thread, freeing resources.
+LLVM_ABI void ShutdownLocalStatistics();
+
 /// Get the local statistics. Returns statistics collected on the current thread
 /// since the last call to ResetLocalStatistics(). Results are sorted by debug
 /// type, then by name. Local statistics also increment their corresponding
diff --git a/llvm/lib/Support/Statistic.cpp b/llvm/lib/Support/Statistic.cpp
index 0c44bf92b8510..bf3ad3431a7dc 100644
--- a/llvm/lib/Support/Statistic.cpp
+++ b/llvm/lib/Support/Statistic.cpp
@@ -24,6 +24,7 @@
 
 #include "DebugOptions.h"
 
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
@@ -102,8 +103,10 @@ class StatisticInfo {
   void reset();
 };
 
-class LocalStatisticInfo {
-  std::vector<LocalTrackingStatistic *> Stats;
+} // end anonymous namespace
+
+class llvm::LocalStatisticInfo {
+  SmallVector<LocalTrackingStatistic *> Stats;
 
 public:
   using const_iterator = decltype(Stats)::const_iterator;
@@ -124,11 +127,10 @@ class LocalStatisticInfo {
     Stats.clear();
   }
 };
-} // end anonymous namespace
 
 static ManagedStatic<StatisticInfo> StatInfo;
 static ManagedStatic<sys::SmartMutex<true>> StatLock;
-static thread_local LocalStatisticInfo LocalStatInfo;
+thread_local LocalStatisticInfo *llvm::LocalStatInfo = nullptr;
 
 /// RegisterStatistic - The first time a statistic is bumped, this method is
 /// called.
@@ -157,9 +159,8 @@ void TrackingStatistic::RegisterStatistic() {
 }
 
 void LocalTrackingStatistic::RegisterStatistic() {
-  assert(!Initialized);
-  if (AreStatisticsEnabled())
-    LocalStatInfo.addStatistic(this);
+  assert(!Initialized && LocalStatInfo);
+  LocalStatInfo->addStatistic(this);
   Initialized = true;
 }
 
@@ -296,16 +297,36 @@ std::vector<std::pair<StringRef, uint64_t>> llvm::GetStatistics() {
 
 std::vector<StatisticVal> llvm::GetLocalStatistics() {
   std::vector<StatisticVal> ReturnStats;
-  LocalStatInfo.sort();
-  for (const auto &Stat : LocalStatInfo)
+  if (!LocalStatInfo)
+    return ReturnStats;
+  LocalStatInfo->sort();
+  for (const auto &Stat : *LocalStatInfo)
     ReturnStats.emplace_back(Stat->getDebugType(), Stat->getName(),
                              Stat->getValue());
   return ReturnStats;
 }
 
 void llvm::ResetStatistics() {
-  LocalStatInfo.reset();
+  ResetLocalStatistics();
   StatInfo->reset();
 }
 
-void llvm::ResetLocalStatistics() { LocalStatInfo.reset(); }
+void llvm::EnableLocalStatistics() {
+  if (LocalStatInfo || !AreStatisticsEnabled())
+    return;
+  LocalStatInfo = new LocalStatisticInfo();
+}
+
+void llvm::ShutdownLocalStatistics() {
+  if (!LocalStatInfo)
+    return;
+  LocalStatInfo->reset();
+  delete LocalStatInfo;
+  LocalStatInfo = nullptr;
+}
+
+void llvm::ResetLocalStatistics() {
+  if (!LocalStatInfo)
+    return;
+  LocalStatInfo->reset();
+}
diff --git a/llvm/unittests/ADT/StatisticTest.cpp b/llvm/unittests/ADT/StatisticTest.cpp
index 52435f23c63b3..7deab750db21b 100644
--- a/llvm/unittests/ADT/StatisticTest.cpp
+++ b/llvm/unittests/ADT/StatisticTest.cpp
@@ -182,10 +182,25 @@ findLocalStat(const std::vector<StatisticVal> &Stats, StringRef Name) {
 TEST(StatisticTest, LocalStatistics) {
   EnableStatistics();
   ResetStatistics();
-  ResetLocalStatistics();
 
 #if LLVM_ENABLE_STATS
-  // Verify empty after reset.
+  // Increment a local counter before enabling local stats. This should
+  // still update the global stat but not be tracked locally.
+  LocalCounter++;
+  {
+    auto Global = GetStatistics();
+    auto GS = findStat(Global, "LocalCounter");
+    ASSERT_TRUE(GS.has_value());
+    EXPECT_EQ(GS->second, 1u);
+  }
+  {
+    auto Local = GetLocalStatistics();
+    EXPECT_TRUE(Local.empty());
+  }
+
+  // Now enable local stats and verify the pre-enable increment isn't tracked.
+  EnableLocalStatistics();
+
   {
     auto Local = GetLocalStatistics();
     EXPECT_TRUE(Local.empty());
@@ -222,7 +237,7 @@ TEST(StatisticTest, LocalStatistics) {
     auto GS2 = findStat(Global, "LocalCounter2");
 
     ASSERT_TRUE(GS1.has_value());
-    EXPECT_EQ(GS1->second, 2u);
+    EXPECT_EQ(GS1->second, 3u);
 
     ASSERT_TRUE(GS2.has_value());
     EXPECT_EQ(GS2->second, 1u);
@@ -240,7 +255,7 @@ TEST(StatisticTest, LocalStatistics) {
     auto Global = GetStatistics();
     auto GS1 = findStat(Global, "LocalCounter");
     ASSERT_TRUE(GS1.has_value());
-    EXPECT_EQ(GS1->second, 2u);
+    EXPECT_EQ(GS1->second, 3u);
   }
 
   // Verify local stats work again after reset.
@@ -267,7 +282,7 @@ TEST(StatisticTest, LocalStatistics) {
     auto GS2 = findStat(Global, "LocalCounter2");
 
     ASSERT_TRUE(GS1.has_value());
-    EXPECT_EQ(GS1->second, 3u);
+    EXPECT_EQ(GS1->second, 4u);
 
     ASSERT_TRUE(GS2.has_value());
     EXPECT_EQ(GS2->second, 6u);
@@ -296,11 +311,13 @@ TEST(StatisticTest, LocalStatistics) {
     EXPECT_EQ(Local[2].Value, 10u);
   }
 #else
+  EnableLocalStatistics();
   LocalCounter++;
   LocalCounter2++;
   auto Local = GetLocalStatistics();
   EXPECT_TRUE(Local.empty());
 #endif
+  ShutdownLocalStatistics();
 }
 
 } // end anonymous namespace



More information about the llvm-commits mailing list