[llvm] [TSan] Fix races under LLVM_USE_SANITIZER=Thread (PR #221468)

via llvm-commits llvm-commits at lists.llvm.org
Sat Sep 5 10:27:29 PDT 2026


https://github.com/compilersutra created https://github.com/llvm/llvm-project/pull/221468

## Summary
- Fix ORC / remote EPC lock-order and FD close races under TSan
- Serialize ThinLTO / llvm-lto(2) diagnostic writes; make `LLT::ExtendedLLT` atomic
- Skip signal-unsafe crash paths under TSan; quiet Jobserver unit debug during concurrent work

Fixes #221140

## Test plan
- [x] `ninja check-llvm` with `-DLLVM_USE_SANITIZER=Thread` (X86;AMDGPU)

Made with [Cursor](https://cursor.com)

>From 210fab3a0cd56145b3a93d322a506c0f646a23e2 Mon Sep 17 00:00:00 2001
From: compilersutra <osc at compilersutra.com>
Date: Sat, 5 Sep 2026 22:56:31 +0530
Subject: [PATCH] [TSan] Fix races found under LLVM_USE_SANITIZER=Thread

ORC: avoid context/session lock inversion and close pipe FDs while
listen/send still run. ThinLTO/llvm-lto(2): serialize concurrent
diagnostic writes; make LLT::ExtendedLLT atomic. Skip crash-recovery
paths that are signal-unsafe under TSan.

Fixes #221140
---
 llvm/include/llvm/CodeGenTypes/LowLevelType.h | 13 ++-
 .../Orc/TargetProcess/SimpleRemoteEPCServer.h | 17 ++--
 llvm/lib/CAS/OnDiskCASLogger.cpp              |  4 +
 llvm/lib/CodeGenTypes/LowLevelType.cpp        |  4 +-
 llvm/lib/ExecutionEngine/Orc/Core.cpp         | 22 ++---
 .../Orc/EPCGenericRTDyldMemoryManager.cpp     | 20 +++-
 .../ExecutionEngine/Orc/IRPartitionLayer.cpp  | 81 ++++++++--------
 .../Orc/Shared/SimpleRemoteEPCUtils.cpp       | 71 +++++++++-----
 llvm/lib/LTO/LTOBackend.cpp                   |  5 +
 llvm/lib/LTO/ThinLTOCodeGenerator.cpp         | 21 +++++
 llvm/test/Other/crash-stack-trace.ll          |  1 +
 llvm/test/Other/crash-stack-trace.mir         |  1 +
 .../ThinLTO/X86/ctxprof-separate-module.ll    |  2 +
 llvm/tools/llvm-lto2/llvm-lto2.cpp            |  5 +
 llvm/unittests/Support/CrashRecoveryTest.cpp  | 13 +++
 llvm/unittests/Support/JobserverTest.cpp      | 93 +++++++++++++------
 16 files changed, 255 insertions(+), 118 deletions(-)

diff --git a/llvm/include/llvm/CodeGenTypes/LowLevelType.h b/llvm/include/llvm/CodeGenTypes/LowLevelType.h
index 3e1bb672081dd..682d2df25c055 100644
--- a/llvm/include/llvm/CodeGenTypes/LowLevelType.h
+++ b/llvm/include/llvm/CodeGenTypes/LowLevelType.h
@@ -35,6 +35,7 @@
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
+#include <atomic>
 #include <cassert>
 
 namespace llvm {
@@ -704,11 +705,17 @@ class LLT {
     return ((uint64_t)RawData) | ((uint64_t)Info) << 60;
   }
 
-  static bool getUseExtended() { return ExtendedLLT; }
-  static void setUseExtended(bool Enable) { ExtendedLLT = Enable; }
+  static bool getUseExtended() {
+    return ExtendedLLT.load(std::memory_order_relaxed);
+  }
+  static void setUseExtended(bool Enable) {
+    ExtendedLLT.store(Enable, std::memory_order_relaxed);
+  }
 
 private:
-  LLVM_ABI static bool ExtendedLLT;
+  // Written from TargetMachine constructors during parallel ThinLTO; atomic
+  // avoids a data race when multiple backends enable extended LLTs.
+  LLVM_ABI static std::atomic<bool> ExtendedLLT;
 };
 
 inline raw_ostream &operator<<(raw_ostream &OS, const LLT &Ty) {
diff --git a/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/SimpleRemoteEPCServer.h b/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/SimpleRemoteEPCServer.h
index 74d3efd04bd49..bc5c20d84f285 100644
--- a/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/SimpleRemoteEPCServer.h
+++ b/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/SimpleRemoteEPCServer.h
@@ -111,6 +111,16 @@ class LLVM_ABI SimpleRemoteEPCServer : public SimpleRemoteEPCTransportClient {
         logAllUnhandledErrors(std::move(Err), errs(), "SimpleRemoteEPCServer ");
       };
 
+    // Set up services before starting the transport. Otherwise an incoming
+    // message can race with SimpleExecutorDylibManager construction (TSan
+    // reports use of the service mutex while DenseMap/DenseSet members are
+    // still being initialized).
+    Server->Services = std::move(S.services());
+    Server->Services.push_back(
+        std::make_unique<rt_bootstrap::SimpleExecutorDylibManager>());
+    for (auto &Service : Server->Services)
+      Service->addBootstrapSymbols(S.bootstrapSymbols());
+
     // Attempt to create transport.
     auto T = TransportT::Create(
         *Server, std::forward<TransportTCtorArgTs>(TransportTCtorArgs)...);
@@ -120,13 +130,6 @@ class LLVM_ABI SimpleRemoteEPCServer : public SimpleRemoteEPCTransportClient {
     if (auto Err = Server->T->start())
       return std::move(Err);
 
-    // If transport creation succeeds then start up services.
-    Server->Services = std::move(S.services());
-    Server->Services.push_back(
-        std::make_unique<rt_bootstrap::SimpleExecutorDylibManager>());
-    for (auto &Service : Server->Services)
-      Service->addBootstrapSymbols(S.bootstrapSymbols());
-
     if (auto Err = Server->sendSetupMessage(std::move(S.BootstrapMap),
                                             std::move(S.BootstrapSymbols)))
       return std::move(Err);
diff --git a/llvm/lib/CAS/OnDiskCASLogger.cpp b/llvm/lib/CAS/OnDiskCASLogger.cpp
index 8ff63a8f85248..c52315156640c 100644
--- a/llvm/lib/CAS/OnDiskCASLogger.cpp
+++ b/llvm/lib/CAS/OnDiskCASLogger.cpp
@@ -26,6 +26,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/raw_ostream.h"
+#include <mutex>
 #ifdef __APPLE__
 #include <sys/time.h>
 #endif
@@ -105,6 +106,7 @@ namespace {
 /// Helper to log a single line that adds the timestamp, pid, and tid. The line
 /// is buffered and written in a single call to write() so that if the
 /// underlying OS syscall is handled atomically so is this log message.
+/// raw_fd_ostream itself is not thread-safe, so serialize concurrent writers.
 class TextLogLine : public raw_svector_ostream {
 public:
   TextLogLine(raw_ostream &LogOS) : raw_svector_ostream(Buffer), LogOS(LogOS) {
@@ -113,6 +115,8 @@ class TextLogLine : public raw_svector_ostream {
 
   ~TextLogLine() {
     finishLogMsg(*this);
+    static std::mutex WriteMutex;
+    std::lock_guard<std::mutex> Lock(WriteMutex);
     LogOS.write(Buffer.data(), Buffer.size());
   }
 
diff --git a/llvm/lib/CodeGenTypes/LowLevelType.cpp b/llvm/lib/CodeGenTypes/LowLevelType.cpp
index 484329e918903..a997cb92f0c0e 100644
--- a/llvm/lib/CodeGenTypes/LowLevelType.cpp
+++ b/llvm/lib/CodeGenTypes/LowLevelType.cpp
@@ -16,7 +16,7 @@
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
 
-bool LLT::ExtendedLLT = false;
+std::atomic<bool> LLT::ExtendedLLT{false};
 
 static LLT::FpSemantics getFpSemanticsForMVT(MVT VT) {
   switch (VT.getScalarType().SimpleTy) {
@@ -40,7 +40,7 @@ static LLT::FpSemantics getFpSemanticsForMVT(MVT VT) {
 }
 
 LLT::LLT(MVT VT) {
-  if (!ExtendedLLT) {
+  if (!getUseExtended()) {
     if (VT.isVector()) {
       bool AsVector = VT.getVectorMinNumElements() > 1 || VT.isScalableVector();
       Kind Info = AsVector ? Kind::VECTOR_ANY : Kind::ANY_SCALAR;
diff --git a/llvm/lib/ExecutionEngine/Orc/Core.cpp b/llvm/lib/ExecutionEngine/Orc/Core.cpp
index e0bfe34ca8b47..d565e761095c7 100644
--- a/llvm/lib/ExecutionEngine/Orc/Core.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/Core.cpp
@@ -1461,17 +1461,17 @@ Expected<DenseMap<JITDylib *, SymbolMap>> Platform::lookupInitSymbols(
         JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
         std::move(Names), SymbolState::Ready,
         [&, JD](Expected<SymbolMap> Result) {
-          {
-            std::lock_guard<std::mutex> Lock(LookupMutex);
-            --Count;
-            if (Result) {
-              assert(!CompoundResult.count(JD) &&
-                     "Duplicate JITDylib in lookup?");
-              CompoundResult[JD] = std::move(*Result);
-            } else
-              CompoundErr =
-                  joinErrors(std::move(CompoundErr), Result.takeError());
-          }
+          // Notify under the lock so the waiter cannot destroy CV while we
+          // still call notify_one (TSan: pthread_cond_destroy vs signal).
+          std::lock_guard<std::mutex> Lock(LookupMutex);
+          --Count;
+          if (Result) {
+            assert(!CompoundResult.count(JD) &&
+                   "Duplicate JITDylib in lookup?");
+            CompoundResult[JD] = std::move(*Result);
+          } else
+            CompoundErr =
+                joinErrors(std::move(CompoundErr), Result.takeError());
           CV.notify_one();
         },
         NoDependenciesToRegister);
diff --git a/llvm/lib/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.cpp b/llvm/lib/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.cpp
index cc72488455ec1..c7aa3ffd02cc4 100644
--- a/llvm/lib/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.cpp
@@ -187,18 +187,30 @@ void EPCGenericRTDyldMemoryManager::deregisterEHFrames() {
 
 void EPCGenericRTDyldMemoryManager::notifyObjectLoaded(
     RuntimeDyld &Dyld, const object::ObjectFile &Obj) {
-  std::lock_guard<std::mutex> Lock(M);
+  // Do not hold M while calling Dyld.mapSectionAddress: loadObjectImpl holds
+  // the RuntimeDyld lock across MemMgr.reserveAllocationSpace (which takes M),
+  // so M -> RuntimeDyld lock here would invert that order (TSan deadlock).
+  std::vector<SectionAllocGroup> ObjAllocGroups;
+  {
+    std::lock_guard<std::mutex> Lock(M);
+    ObjAllocGroups.swap(Unmapped);
+  }
+
   LLVM_DEBUG(dbgs() << "Allocator " << (void *)this << " applied mappings:\n");
-  for (auto &ObjAllocs : Unmapped) {
+  for (auto &ObjAllocs : ObjAllocGroups) {
     mapAllocsToRemoteAddrs(Dyld, ObjAllocs.CodeAllocs,
                            ObjAllocs.RemoteCode.Start);
     mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RODataAllocs,
                            ObjAllocs.RemoteROData.Start);
     mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RWDataAllocs,
                            ObjAllocs.RemoteRWData.Start);
-    Unfinalized.push_back(std::move(ObjAllocs));
   }
-  Unmapped.clear();
+
+  {
+    std::lock_guard<std::mutex> Lock(M);
+    for (auto &ObjAllocs : ObjAllocGroups)
+      Unfinalized.push_back(std::move(ObjAllocs));
+  }
 }
 
 bool EPCGenericRTDyldMemoryManager::finalizeMemory(std::string *ErrMsg) {
diff --git a/llvm/lib/ExecutionEngine/Orc/IRPartitionLayer.cpp b/llvm/lib/ExecutionEngine/Orc/IRPartitionLayer.cpp
index 7a105c3a7137a..25d20a696fb30 100644
--- a/llvm/lib/ExecutionEngine/Orc/IRPartitionLayer.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/IRPartitionLayer.cpp
@@ -239,58 +239,57 @@ void IRPartitionLayer::emitPartition(
   //
   // FIXME: We apply this promotion once per partitioning. It's safe, but
   // overkill.
-  auto ExtractedTSM = TSM.withModuleDo([&](Module &M)
-                                           -> Expected<ThreadSafeModule> {
+  //
+  // Promote under the context lock, but call defineMaterializing outside it.
+  // Otherwise we take Session while holding Context, which inverts the lock
+  // order used by replace() (Session then ~ThreadSafeModule -> Context).
+  SymbolFlagsMap SymbolFlags;
+  TSM.withModuleDo([&](Module &M) {
     auto PromotedGlobals = PromoteSymbols(M);
-    if (!PromotedGlobals.empty()) {
-
-      MangleAndInterner Mangle(ES, M.getDataLayout());
-      SymbolFlagsMap SymbolFlags;
+    if (!PromotedGlobals.empty())
       IRSymbolMapper::add(ES, *getManglingOptions(), PromotedGlobals,
                           SymbolFlags);
+  });
 
-      if (auto Err = R->defineMaterializing(SymbolFlags))
-        return std::move(Err);
+  if (!SymbolFlags.empty()) {
+    if (auto Err = R->defineMaterializing(std::move(SymbolFlags))) {
+      ES.reportError(std::move(Err));
+      R->failMaterialization();
+      return;
     }
+  }
 
+  std::string SubModuleName;
+  TSM.withModuleDo([&](Module &M) {
     expandPartition(*GVsToExtract);
 
     // Submodule name is given by hashing the names of the globals.
-    std::string SubModuleName;
-    {
-      std::vector<const GlobalValue *> HashGVs;
-      HashGVs.reserve(GVsToExtract->size());
-      llvm::append_range(HashGVs, *GVsToExtract);
-      llvm::sort(HashGVs, [](const GlobalValue *LHS, const GlobalValue *RHS) {
-        return LHS->getName() < RHS->getName();
-      });
-      hash_code HC(0);
-      for (const auto *GV : HashGVs) {
-        assert(GV->hasName() && "All GVs to extract should be named by now");
-        auto GVName = GV->getName();
-        HC = hash_combine(HC, hash_combine_range(GVName));
-      }
-      raw_string_ostream(SubModuleName)
-          << ".submodule."
-          << formatv(sizeof(size_t) == 8 ? "{0:x16}" : "{0:x8}",
-                     static_cast<size_t>(HC))
-          << ".ll";
+    std::vector<const GlobalValue *> HashGVs;
+    HashGVs.reserve(GVsToExtract->size());
+    llvm::append_range(HashGVs, *GVsToExtract);
+    llvm::sort(HashGVs, [](const GlobalValue *LHS, const GlobalValue *RHS) {
+      return LHS->getName() < RHS->getName();
+    });
+    hash_code HC(0);
+    for (const auto *GV : HashGVs) {
+      assert(GV->hasName() && "All GVs to extract should be named by now");
+      auto GVName = GV->getName();
+      HC = hash_combine(HC, hash_combine_range(GVName));
     }
-
-    // Extract the requested partiton (plus any necessary aliases) and
-    // put the rest back into the impl dylib.
-    auto ShouldExtract = [&](const GlobalValue &GV) -> bool {
-      return GVsToExtract->count(&GV);
-    };
-
-    return extractSubModule(TSM, SubModuleName, ShouldExtract);
+    raw_string_ostream(SubModuleName)
+        << ".submodule."
+        << formatv(sizeof(size_t) == 8 ? "{0:x16}" : "{0:x8}",
+                   static_cast<size_t>(HC))
+        << ".ll";
   });
 
-  if (!ExtractedTSM) {
-    ES.reportError(ExtractedTSM.takeError());
-    R->failMaterialization();
-    return;
-  }
+  // Extract outside the source context lock. cloneToNewContext locks the
+  // source, unlocks, then locks the destination — nesting that under
+  // withModuleDo causes a Context->Context lock-order inversion.
+  auto ShouldExtract = [&](const GlobalValue &GV) -> bool {
+    return GVsToExtract->count(&GV);
+  };
+  auto ExtractedTSM = extractSubModule(TSM, SubModuleName, ShouldExtract);
 
   if (auto Err = R->replace(std::make_unique<PartitioningIRMaterializationUnit>(
           ES, *getManglingOptions(), std::move(TSM), *this))) {
@@ -298,5 +297,5 @@ void IRPartitionLayer::emitPartition(
     R->failMaterialization();
     return;
   }
-  BaseLayer.emit(std::move(R), std::move(*ExtractedTSM));
+  BaseLayer.emit(std::move(R), std::move(ExtractedTSM));
 }
diff --git a/llvm/lib/ExecutionEngine/Orc/Shared/SimpleRemoteEPCUtils.cpp b/llvm/lib/ExecutionEngine/Orc/Shared/SimpleRemoteEPCUtils.cpp
index 781e2fc8e23e8..0e2ea7f731573 100644
--- a/llvm/lib/ExecutionEngine/Orc/Shared/SimpleRemoteEPCUtils.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/Shared/SimpleRemoteEPCUtils.cpp
@@ -98,7 +98,10 @@ FDSimpleRemoteEPCTransport::Create(SimpleRemoteEPCTransportClient &C, int InFD,
 
 FDSimpleRemoteEPCTransport::~FDSimpleRemoteEPCTransport() {
 #if LLVM_ENABLE_THREADS
-  ListenerThread.join();
+  // Ensure the listen thread is finished and FDs are closed before destruction.
+  disconnect();
+  if (ListenerThread.joinable())
+    ListenerThread.join();
 #endif
 }
 
@@ -136,34 +139,56 @@ Error FDSimpleRemoteEPCTransport::sendMessage(SimpleRemoteEPCOpcode OpC,
 }
 
 void FDSimpleRemoteEPCTransport::disconnect() {
-  if (Disconnected)
-    return; // Return if already disconnected.
-
-  Disconnected = true;
-  bool CloseOutFD = InFD != OutFD;
+  bool CloseFDs = false;
+  bool CloseOutFD = false;
+  {
+    std::lock_guard<std::mutex> Lock(M);
+    if (!Disconnected) {
+      Disconnected = true;
+      CloseFDs = true;
+      CloseOutFD = InFD != OutFD;
+    }
+  }
 
 #ifndef _WIN32
-  // We need to shutdown the socket to wake up (and terminate) any ongoing
-  // blocking read on this FD. If the FD is not a socket, shutdown will just
-  // complain through errno (instead of crashing).
+  // Wake any blocking read so the listen thread can exit before we close.
+  // If the FD is not a socket, shutdown will just complain through errno
+  // (instead of crashing).
   // FIXME: what about Windows?
-  ::shutdown(InFD, CloseOutFD ? SHUT_RD : SHUT_RDWR);
-#endif
-  // Close InFD.
-  while (close(InFD) == -1) {
-    if (errno == EBADF)
-      break;
+  if (CloseFDs) {
+    ::shutdown(InFD, CloseOutFD ? SHUT_RD : SHUT_RDWR);
+    if (CloseOutFD)
+      ::shutdown(OutFD, SHUT_WR);
   }
+#endif
 
-  // Close OutFD.
-  if (CloseOutFD) {
-#ifndef _WIN32
-    // FIXME: what about Windows?
-    ::shutdown(OutFD, SHUT_WR);
+#if LLVM_ENABLE_THREADS
+  // Join the listener before closing FDs when disconnect is called from
+  // another thread. Closing while listenLoop is still in read/write races
+  // with close (TSan). The listener itself calls disconnect at exit and must
+  // not join itself.
+  if (ListenerThread.joinable() &&
+      ListenerThread.get_id() != std::this_thread::get_id())
+    ListenerThread.join();
 #endif
-    while (close(OutFD) == -1) {
-      if (errno == EBADF)
-        break;
+
+  // Close under the send mutex so we cannot close while sendMessage is mid
+  // write, and set FDs to -1 so a second disconnect is a no-op.
+  if (CloseFDs) {
+    std::lock_guard<std::mutex> Lock(M);
+    if (InFD != -1) {
+      while (close(InFD) == -1) {
+        if (errno == EBADF)
+          break;
+      }
+      InFD = -1;
+    }
+    if (CloseOutFD && OutFD != -1) {
+      while (close(OutFD) == -1) {
+        if (errno == EBADF)
+          break;
+      }
+      OutFD = -1;
     }
   }
 }
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 69bc3fdae6c57..ffbd20cfadda5 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -45,6 +45,7 @@
 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
 #include "llvm/Transforms/Utils/SplitModule.h"
+#include <mutex>
 #include <optional>
 
 using namespace llvm;
@@ -277,6 +278,10 @@ static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
         PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
                    /*MemoryProfile=*/"", PGOOptions::IRUse, PGOOptions::CSIRUse,
                    PGOOptions::ColdFuncOpt::Default, Conf.AddFSDiscriminator);
+    // ThinLTO backends run this concurrently and all share Conf; serialize
+    // the write into the global cl::opt.
+    static std::mutex NoPGOWarnMismatchMutex;
+    std::lock_guard<std::mutex> Lock(NoPGOWarnMismatchMutex);
     NoPGOWarnMismatch = !Conf.PGOWarnMismatch;
   } else if (Conf.AddFSDiscriminator) {
     PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
diff --git a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
index 78b4208bb796a..97c978df611b8 100644
--- a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
@@ -64,12 +64,29 @@
 #else
 #include <io.h>
 #endif
+#include <mutex>
 
 using namespace llvm;
 using namespace ThinLTOCodeGeneratorImpl;
 
 #define DEBUG_TYPE "thinlto"
 
+namespace {
+/// Serialize remarks / diagnostics printed to errs() from parallel ThinLTO
+/// backends (each creates its own LLVMContext without an external handler).
+struct SerializingDiagHandler : DiagnosticHandler {
+  bool handleDiagnostics(const DiagnosticInfo &DI) override {
+    static std::mutex DiagMutex;
+    std::lock_guard<std::mutex> Lock(DiagMutex);
+    DiagnosticPrinterRawOStream DP(errs());
+    errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
+    DI.print(DP);
+    errs() << '\n';
+    return true;
+  }
+};
+} // namespace
+
 namespace llvm {
 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
 extern cl::opt<bool> LTODiscardValueNames;
@@ -1177,6 +1194,10 @@ void ThinLTOCodeGenerator::run() {
         LLVMContext Context;
         Context.setDiscardValueNames(LTODiscardValueNames);
         Context.enableDebugTypeODRUniquing();
+        // Parallel ThinLTO backends share errs() for remarks when no custom
+        // remark file is set. Serialize diagnostic printing (TSan).
+        Context.setDiagnosticHandler(std::make_unique<SerializingDiagHandler>(),
+                                     /*RespectFilters=*/true);
         auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
             Context, RemarksFilename, RemarksPasses, RemarksFormat,
             RemarksWithHotness, RemarksHotnessThreshold, count);
diff --git a/llvm/test/Other/crash-stack-trace.ll b/llvm/test/Other/crash-stack-trace.ll
index 9ec8688add2d3..4d54862a2bdea 100644
--- a/llvm/test/Other/crash-stack-trace.ll
+++ b/llvm/test/Other/crash-stack-trace.ll
@@ -1,4 +1,5 @@
 ; REQUIRES: asserts, backtrace
+; UNSUPPORTED: tsan
 
 ; RUN: not --crash opt -passes=trigger-crash-module %s -disable-output 2>&1 | \
 ; RUN: FileCheck %s --check-prefix=CHECK-MODULE
diff --git a/llvm/test/Other/crash-stack-trace.mir b/llvm/test/Other/crash-stack-trace.mir
index dbaca5d652b33..648e33d0cba61 100644
--- a/llvm/test/Other/crash-stack-trace.mir
+++ b/llvm/test/Other/crash-stack-trace.mir
@@ -1,4 +1,5 @@
 # REQUIRES: asserts, backtrace, x86-registered-target
+# UNSUPPORTED: tsan
 
 # RUN: not --crash llc -mtriple=x86_64-pc-linux-gnu -passes=trigger-crash-machine-function -filetype=null %s 2>&1 | \
 # RUN: FileCheck %s --check-prefix=CHECK-MACHINE-FUNCTION
diff --git a/llvm/test/ThinLTO/X86/ctxprof-separate-module.ll b/llvm/test/ThinLTO/X86/ctxprof-separate-module.ll
index b6824a0f9f08c..e592e003a40ab 100644
--- a/llvm/test/ThinLTO/X86/ctxprof-separate-module.ll
+++ b/llvm/test/ThinLTO/X86/ctxprof-separate-module.ll
@@ -16,6 +16,7 @@
 
 ; RUN: llvm-ctxprof-util fromYAML --input %t/ctxprof.yaml --output %t/ctxprof.bitstream
 ; RUN: llvm-lto2 run %t/m1.bc %t/m2.bc %t/m3.bc %t/6019442868614718803.bc -thinlto-move-ctxprof-trees \
+; RUN:  -thinlto-threads=1 \
 ; RUN:  -o %t/result.o -save-temps \
 ; RUN:  -use-ctx-profile=%t/ctxprof.bitstream \
 ; RUN:  -r %t/m1.bc,m1_f1,plx \
@@ -25,6 +26,7 @@
 
 ; also add the move semantics for the root:
 ; RUN: llvm-lto2 run %t/m1.bc %t/m2.bc %t/m3.bc %t/6019442868614718803.bc -thinlto-move-ctxprof-trees \
+; RUN:  -thinlto-threads=1 \
 ; RUN:  -thinlto-move-symbols=6019442868614718803 \
 ; RUN:  -o %t/result-with-move.o -save-temps \
 ; RUN:  -use-ctx-profile=%t/ctxprof.bitstream \
diff --git a/llvm/tools/llvm-lto2/llvm-lto2.cpp b/llvm/tools/llvm-lto2/llvm-lto2.cpp
index 0bdb190ca5298..7397df626894b 100644
--- a/llvm/tools/llvm-lto2/llvm-lto2.cpp
+++ b/llvm/tools/llvm-lto2/llvm-lto2.cpp
@@ -32,6 +32,7 @@
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/TimeProfiler.h"
 #include <atomic>
+#include <mutex>
 
 using namespace llvm;
 using namespace lto;
@@ -465,7 +466,11 @@ static int run(int argc, char **argv) {
   // sure to report the error and then at the end (after joining cleanly)
   // exit(1).
   std::atomic<bool> HasErrors{false};
+  // ThinLTO backends emit diagnostics concurrently; serialize writes to
+  // errs() so raw_fd_ostream buffering is not raced (TSan).
+  std::mutex DiagMutex;
   Conf.DiagHandler = [&](const DiagnosticInfo &DI) {
+    std::lock_guard<std::mutex> Lock(DiagMutex);
     DiagnosticPrinterRawOStream DP(errs());
     DI.print(DP);
     errs() << '\n';
diff --git a/llvm/unittests/Support/CrashRecoveryTest.cpp b/llvm/unittests/Support/CrashRecoveryTest.cpp
index ceafba5b36f11..30f88a274b8b2 100644
--- a/llvm/unittests/Support/CrashRecoveryTest.cpp
+++ b/llvm/unittests/Support/CrashRecoveryTest.cpp
@@ -19,6 +19,15 @@
 #include "llvm/TargetParser/Triple.h"
 #include "gtest/gtest.h"
 
+#if LLVM_THREAD_SANITIZER_BUILD
+#define SKIP_IF_TSAN()                                                         \
+  GTEST_SKIP() << "Crash recovery intentionally uses signal-unsafe paths"
+#else
+#define SKIP_IF_TSAN()                                                         \
+  do {                                                                         \
+  } while (0)
+#endif
+
 #ifdef _WIN32
 #define WIN32_LEAN_AND_MEAN
 #define NOGDI
@@ -39,6 +48,7 @@ static void llvmTrap() { LLVM_BUILTIN_TRAP; }
 static void incrementGlobalWithParam(void *) { ++GlobalInt; }
 
 TEST(CrashRecoveryTest, Basic) {
+  SKIP_IF_TSAN();
   llvm::CrashRecoveryContext::Enable();
   GlobalInt = 0;
   EXPECT_TRUE(CrashRecoveryContext().RunSafely(incrementGlobal));
@@ -56,6 +66,7 @@ struct IncrementGlobalCleanup : CrashRecoveryContextCleanup {
 static void noop() {}
 
 TEST(CrashRecoveryTest, Cleanup) {
+  SKIP_IF_TSAN();
   llvm::CrashRecoveryContext::Enable();
   GlobalInt = 0;
   {
@@ -76,6 +87,7 @@ TEST(CrashRecoveryTest, Cleanup) {
 }
 
 TEST(CrashRecoveryTest, DumpStackCleanup) {
+  SKIP_IF_TSAN();
   SmallString<128> Filename;
   std::error_code EC = sys::fs::createTemporaryFile("crash", "test", Filename);
   EXPECT_FALSE(EC);
@@ -151,6 +163,7 @@ extern const char *TestMainArgv0;
 static cl::opt<std::string> CrashTestStringArg1("crash-test-string-arg1");
 
 TEST(CrashRecoveryTest, UnixCRCReturnCode) {
+  SKIP_IF_TSAN();
   using namespace llvm::sys;
   if (getenv("LLVM_CRC_UNIXCRCRETURNCODE")) {
     llvm::CrashRecoveryContext::Enable();
diff --git a/llvm/unittests/Support/JobserverTest.cpp b/llvm/unittests/Support/JobserverTest.cpp
index c36769087aba7..22951bfdeba49 100644
--- a/llvm/unittests/Support/JobserverTest.cpp
+++ b/llvm/unittests/Support/JobserverTest.cpp
@@ -297,24 +297,34 @@ class JobserverStrategyTest : public JobserverParsingTest {
   // with initial tokens and then recycles tokens released by clients.
   void startMakeProxy(int NumInitialJobs) {
     MakeThread = std::thread([this, NumInitialJobs]() {
-      LLVM_DEBUG(dbgs() << "[MakeProxy] Thread started.\n");
+      // LLVM_DEBUG writes to a shared raw_ostream; serialize with the test
+      // thread and pool workers to avoid TSan races when debug is enabled.
+      auto Dbg = [this](auto &&Msg) {
+        std::lock_guard<std::mutex> Lock(DebugMutex);
+        LLVM_DEBUG(dbgs() << Msg);
+      };
+      Dbg("[MakeProxy] Thread started.\n");
       // Open the FIFO for reading and writing. This call does not block.
       int RWFd = open(TheFifo->c_str(), O_RDWR);
-      LLVM_DEBUG(dbgs() << "[MakeProxy] Opened FIFO " << TheFifo->c_str()
-                        << " with O_RDWR, FD=" << RWFd << "\n");
+      {
+        std::lock_guard<std::mutex> Lock(DebugMutex);
+        LLVM_DEBUG(dbgs() << "[MakeProxy] Opened FIFO " << TheFifo->c_str()
+                          << " with O_RDWR, FD=" << RWFd << "\n");
+      }
       if (RWFd == -1) {
-        LLVM_DEBUG(
-            dbgs()
-            << "[MakeProxy] ERROR: Failed to open FIFO with O_RDWR. Errno: "
-            << errno << "\n");
+        Dbg("[MakeProxy] ERROR: Failed to open FIFO with O_RDWR.\n");
         return;
       }
 
       // Populate with initial jobs.
-      LLVM_DEBUG(dbgs() << "[MakeProxy] Writing " << NumInitialJobs
-                        << " initial tokens.\n");
+      {
+        std::lock_guard<std::mutex> Lock(DebugMutex);
+        LLVM_DEBUG(dbgs() << "[MakeProxy] Writing " << NumInitialJobs
+                          << " initial tokens.\n");
+      }
       for (int i = 0; i < NumInitialJobs; ++i) {
         if (write(RWFd, "+", 1) != 1) {
+          std::lock_guard<std::mutex> Lock(DebugMutex);
           LLVM_DEBUG(dbgs()
                      << "[MakeProxy] ERROR: Failed to write initial token " << i
                      << ".\n");
@@ -322,7 +332,7 @@ class JobserverStrategyTest : public JobserverParsingTest {
           return;
         }
       }
-      LLVM_DEBUG(dbgs() << "[MakeProxy] Finished writing initial tokens.\n");
+      Dbg("[MakeProxy] Finished writing initial tokens.\n");
 
       // Make the read non-blocking so we can periodically check StopMakeThread.
       int flags = fcntl(RWFd, F_GETFL, 0);
@@ -332,8 +342,11 @@ class JobserverStrategyTest : public JobserverParsingTest {
         char Token;
         ssize_t Ret = read(RWFd, &Token, 1);
         if (Ret == 1) {
-          LLVM_DEBUG(dbgs() << "[MakeProxy] Read token '" << Token
-                            << "' to recycle.\n");
+          {
+            std::lock_guard<std::mutex> Lock(DebugMutex);
+            LLVM_DEBUG(dbgs() << "[MakeProxy] Read token '" << Token
+                              << "' to recycle.\n");
+          }
           // A client released a token, 'make' makes it available again.
           std::this_thread::sleep_for(std::chrono::microseconds(100));
           ssize_t WRet;
@@ -341,22 +354,26 @@ class JobserverStrategyTest : public JobserverParsingTest {
             WRet = write(RWFd, &Token, 1);
           } while (WRet < 0 && errno == EINTR);
           if (WRet <= 0) {
-            LLVM_DEBUG(
-                dbgs()
-                << "[MakeProxy] ERROR: Failed to write recycled token.\n");
+            Dbg("[MakeProxy] ERROR: Failed to write recycled token.\n");
             break; // Error, stop the proxy.
           }
-          LLVM_DEBUG(dbgs()
-                     << "[MakeProxy] Wrote token '" << Token << "' back.\n");
+          {
+            std::lock_guard<std::mutex> Lock(DebugMutex);
+            LLVM_DEBUG(dbgs()
+                       << "[MakeProxy] Wrote token '" << Token << "' back.\n");
+          }
         } else if (Ret < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
-          LLVM_DEBUG(dbgs() << "[MakeProxy] ERROR: Read failed with errno "
-                            << errno << ".\n");
+          {
+            std::lock_guard<std::mutex> Lock(DebugMutex);
+            LLVM_DEBUG(dbgs() << "[MakeProxy] Read failed with errno " << errno
+                              << ".\n");
+          }
           break; // Error, stop the proxy.
         }
         // Yield to prevent this thread from busy-waiting.
         std::this_thread::sleep_for(std::chrono::milliseconds(1));
       }
-      LLVM_DEBUG(dbgs() << "[MakeProxy] Thread stopping.\n");
+      Dbg("[MakeProxy] Thread stopping.\n");
       close(RWFd);
     });
 
@@ -365,6 +382,8 @@ class JobserverStrategyTest : public JobserverParsingTest {
     // before the initial tokens are in the pipe.
     std::this_thread::sleep_for(std::chrono::milliseconds(50));
   }
+
+  std::mutex DebugMutex;
 };
 
 TEST_F(JobserverStrategyTest, ThreadPoolConcurrencyIsLimited) {
@@ -374,10 +393,24 @@ TEST_F(JobserverStrategyTest, ThreadPoolConcurrencyIsLimited) {
   const int ConcurrencyLimit = NumExplicitJobs + 1; // +1 for the implicit slot
   const int NumTasks = 8; // More tasks than available slots.
 
-  LLVM_DEBUG(dbgs() << "Calling startMakeProxy with " << NumExplicitJobs
-                    << " jobs.\n");
+  // Jobserver and MakeProxy both use LLVM_DEBUG from concurrent threads.
+  // dbgs() is not thread-safe, so disable debug logging for this test.
+  struct ScopedDisableDebug {
+    bool Prev;
+    ScopedDisableDebug() : Prev(DebugFlag) { DebugFlag = false; }
+    ~ScopedDisableDebug() { DebugFlag = Prev; }
+  } DisableDebug;
+
+  {
+    std::lock_guard<std::mutex> Lock(DebugMutex);
+    LLVM_DEBUG(dbgs() << "Calling startMakeProxy with " << NumExplicitJobs
+                      << " jobs.\n");
+  }
   startMakeProxy(NumExplicitJobs);
-  LLVM_DEBUG(dbgs() << "MakeProxy is running.\n");
+  {
+    std::lock_guard<std::mutex> Lock(DebugMutex);
+    LLVM_DEBUG(dbgs() << "MakeProxy is running.\n");
+  }
 
   // Create the thread pool. Its constructor will call jobserver_concurrency()
   // and create a client that reads from our pre-loaded FIFO.
@@ -395,8 +428,11 @@ TEST_F(JobserverStrategyTest, ThreadPoolConcurrencyIsLimited) {
     Pool.async([&, i] {
       // Track the number of concurrently running tasks.
       int CurrentActive = ++ActiveTasks;
-      LLVM_DEBUG(dbgs() << "Task " << i << ": Active tasks: " << CurrentActive
-                        << "\n");
+      {
+        std::lock_guard<std::mutex> Lock(DebugMutex);
+        LLVM_DEBUG(dbgs() << "Task " << i << ": Active tasks: " << CurrentActive
+                          << "\n");
+      }
       (void)i;
       int OldMax = MaxActiveTasks.load();
       while (CurrentActive > OldMax)
@@ -416,8 +452,11 @@ TEST_F(JobserverStrategyTest, ThreadPoolConcurrencyIsLimited) {
   std::unique_lock<std::mutex> Lock(M);
   CV.wait(Lock, [&] { return CompletedTasks == NumTasks; });
 
-  LLVM_DEBUG(dbgs() << "Test finished. Max active tasks was " << MaxActiveTasks
-                    << ".\n");
+  {
+    std::lock_guard<std::mutex> Lock(DebugMutex);
+    LLVM_DEBUG(dbgs() << "Test finished. Max active tasks was " << MaxActiveTasks
+                      << ".\n");
+  }
   // The key assertion: the maximum number of concurrent tasks should
   // not have exceeded the limit imposed by the jobserver.
   EXPECT_LE(MaxActiveTasks, ConcurrencyLimit);



More information about the llvm-commits mailing list