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

Bob Haarman via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Fri Apr 6 18:16:42 PDT 2018


inglorion created this revision.
inglorion added reviewers: dsanders, rtereshin.
Herald added a subscriber: hiraditya.

Statistic and ManagedStatic both use mutexes. There was a lock order
inversion where, during initialization, Statistic's mutex would be
held while taking ManagedStatic's, and in llvm_shutdown,
ManagedStatic's mutex would be held while taking Statistic's
mutex. This change causes Statistic's initialization code to avoid
holding its mutex while calling ManagedStatic's methods, avoiding the
inversion.


https://reviews.llvm.org/D45398

Files:
  llvm/lib/Support/Statistic.cpp


Index: llvm/lib/Support/Statistic.cpp
===================================================================
--- llvm/lib/Support/Statistic.cpp
+++ llvm/lib/Support/Statistic.cpp
@@ -94,10 +94,20 @@
 void Statistic::RegisterStatistic() {
   // If stats are enabled, inform StatInfo that this statistic should be
   // printed.
-  sys::SmartScopedLock<true> Writer(*StatLock);
+  // There is a possible lock order inversion here. llvm_shutdown calls us
+  // while holding the ManagedStatic mutex. If we take StatLock and call
+  // ManagedStatic methods, we can end up taking the locks in the opposite
+  // order. To avoid that, we call all ManagedStatic methods before acquiring
+  // StatLock.
   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.141465.patch
Type: text/x-patch
Size: 1199 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20180407/6fd2bfea/attachment.bin>


More information about the llvm-commits mailing list