[PATCH] D45398: Fix lock order inversion between ManagedStatic and Statistic

Bob Haarman via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Apr 17 16:40:29 PDT 2018


This revision was automatically updated to reflect the committed changes.
inglorion marked an inline comment as done.
Closed by commit rL330236: Fix lock order inversion between ManagedStatic and Statistic (authored by inglorion, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D45398?vs=141697&id=142867#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D45398

Files:
  llvm/trunk/lib/Support/Statistic.cpp


Index: llvm/trunk/lib/Support/Statistic.cpp
===================================================================
--- llvm/trunk/lib/Support/Statistic.cpp
+++ llvm/trunk/lib/Support/Statistic.cpp
@@ -94,10 +94,21 @@
 void Statistic::RegisterStatistic() {
   // If stats are enabled, inform StatInfo that this statistic should be
   // printed.
-  sys::SmartScopedLock<true> Writer(*StatLock);
+  // llvm_shutdown calls destructors while holding the ManagedStatic mutex.
+  // These destructors end up calling PrintStatistics, which takes StatLock.
+  // Since dereferencing StatInfo and StatLock can require taking the
+  // ManagedStatic mutex, doing so with StatLock held would lead to a lock
+  // order inversion. To avoid that, we dereference the ManagedStatics first,
+  // and only take StatLock afterwards.
   if (!Initialized.load(std::memory_order_relaxed)) {
+    sys::SmartMutex<true> &Lock = *StatLock;
+    StatisticInfo &SI = *StatInfo;
+    sys::SmartScopedLock<true> Writer(Lock);
+    // Check Initialized again after acquiring the lock.
+    if (Initialized.load(std::memory_order_relaxed))
+      return;
     if (Stats || Enabled)
-      StatInfo->addStatistic(this);
+      SI.addStatistic(this);
 
     // Remember we have been registered.
     Initialized.store(true, std::memory_order_release);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D45398.142867.patch
Type: text/x-patch
Size: 1318 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20180417/c47b5a2b/attachment.bin>


More information about the llvm-commits mailing list