Author: Jan Svoboda
Date: 2026-11-17T13:10:55-08:00
New Revision: 1035e21720d074ef836cafc93aa5b179c3431510

URL: 
https://github.com/llvm/llvm-project/commit/1035e21720d074ef836cafc93aa5b179c3431510
DIFF: 
https://github.com/llvm/llvm-project/commit/1035e21720d074ef836cafc93aa5b179c3431510.diff

LOG: [clang][deps] Flush the in-process module cache on a background thread 
(#242385)

The in-process module cache keeps every PCM built during the lifetime of
the
dependency scanning service in memory, and flushes them to disk at the
end.
Long-running builds that scan many variants of modules (e.g. with
different
search paths or macro definitions) accumulate tens of gigabytes worth of
scanning PCMs this way. Moreover, the final flush is single-threaded and
happens after all scanning work is done.

This PR makes the service start a background thread that flushes each
PCM to
disk as soon as it's written, and then replaces its in-memory buffer
with the
memory-mapped file. Readers of the in-memory buffer keep it alive on
their own
(shared ownership), and importers of the freshly built PCM never wait
for the
IO, since the file gets written without holding the entry lock. Reads
and
timestamps are still served from memory. The final flush is kept, but
only
writes PCMs the background thread failed to write. With
`-no-flush-module-cache`, nothing changes.

I tried several approaches, all measured on a scan of the macOS SDK
where
TUs import various frameworks (Foundation, AppKit, CoreData,
AVFoundation,
Metal, CoreML, SceneKit, MapKit, ...), with each `-I` and `-D` variant
creating a distinct module context. Clean scans at -j14 on 14 cores, all
configurations run in shuffled order in each round, scan time from
`-print-timing` with `-o /dev/null`, mean with 95% CI, difference to no
flush
paired by round, peak memory footprint from `/usr/bin/time -l`.

100 contexts (500 TUs, 7400 PCMs, 0.7 GB), 15 rounds:

  | Configuration | Scan time | vs. no flush | Footprint |
  |---|--:|--:|--:|
  | no flush (lower bound) | 9.12s ± 0.04s | | 993 MB |
  | flush on background thread | 9.19s ± 0.03s | +0.8% ± 0.2% | 390 MB |
  | flush on 1-thread pool | 9.22s ± 0.03s | +1.1% ± 0.5% | 387 MB |
  | parallel flush at end | 9.59s ± 0.04s | +5.1% ± 0.3% | 1006 MB |
  | synchronous write-through | 9.63s ± 0.09s | +5.6% ± 1.0% | 367 MB |
  | spill over 256 MB limit | 9.70s ± 0.07s | +6.3% ± 0.5% | 606 MB |
| serial flush at end (before) | 10.46s ± 0.05s | +14.7% ± 0.4% | 1002
MB |

400 contexts (2000 TUs, 29600 PCMs, 2.7 GB), 10 rounds:

  | Configuration | Scan time | vs. no flush | Footprint |
  |---|--:|--:|--:|
  | no flush (lower bound) | 35.28s ± 0.09s | | 3.1 GB |
| flush on background thread | 35.64s ± 0.12s | +1.0% ± 0.5% | 419 MB |
  | flush on 1-thread pool | 35.67s ± 0.05s | +1.1% ± 0.3% | 391 MB |
  | spill over 256 MB limit | 36.19s ± 0.08s | +2.6% ± 0.2% | 654 MB |
  | synchronous write-through | 37.09s ± 0.06s | +5.1% ± 0.3% | 370 MB |
  | parallel flush at end | 37.15s ± 0.10s | +5.3% ± 0.3% | 3.2 GB |
| serial flush at end (before) | 40.86s ± 0.33s | +15.8% ± 1.0% | 3.2 GB
|

The approaches:
* Spilling the least recently used PCMs to disk once they exceed a
memory
limit (checked at the start of each TU) bounds memory, but needs a knob,
LRU bookkeeping, and pays for synchronous writes in the scanning threads
and for the final flush (+2.6-6.3%, more when more of the cache exceeds
the limit). Making the limit strict by reserving memory in `write()`
added
  another 3-6% in a separate measurement, because writers serialize on
  spilling.
* Writing PCMs through to disk synchronously in `write()` uses the least
  memory, but costs ~5% because the scanning threads wait for the IO.
* Parallelizing the final flush across all cores recovers about two
thirds
  of its cost, but keeps all PCMs in memory until the end.
* Flushing on a background thread costs ~1% compared to not flushing at
all.
A thread pool with a single thread performs the same as a dedicated
thread
  with a pending list, which is simpler.

The background thread keeps up with the scan: in instrumented runs of
both
workloads, there were no pending PCMs left when the service ended, and
the
final flush found nothing to write. Peak memory footprint goes down to
~390-420 MB, compared to ~210-230 MB for an incremental scan, where all
PCMs are
memory-mapped from disk.

Added: 
    clang/test/ClangScanDeps/module-cache-flush-in-background.c

Modified: 
    clang/include/clang/DependencyScanning/DependencyScanningService.h
    clang/include/clang/DependencyScanning/InProcessModuleCache.h
    clang/lib/DependencyScanning/InProcessModuleCache.cpp
    clang/test/ClangScanDeps/logging-simple-by-name.c
    clang/test/ClangScanDeps/logging-simple.c
    clang/tools/clang-scan-deps/Opts.td
    clang/unittests/DependencyScanning/InProcessModuleCacheTest.cpp

Removed: 
    


################################################################################
diff  --git 
a/clang/include/clang/DependencyScanning/DependencyScanningService.h 
b/clang/include/clang/DependencyScanning/DependencyScanningService.h
index d1fc26490423cd..2e085670ebd03d 100644
--- a/clang/include/clang/DependencyScanning/DependencyScanningService.h
+++ b/clang/include/clang/DependencyScanning/DependencyScanningService.h
@@ -94,8 +94,8 @@ struct DependencyScanningServiceOptions {
   bool AsyncScanModules = false;
   /// The build session timestamp for validate-once-per-build-session logic.
   std::time_t BuildSessionTimestamp; // = std::chrono::system_clock::now();
-  /// Whether to automatically flush the module cache from memory to disk at 
the
-  /// end of the service lifetime.
+  /// Whether to automatically flush the module cache from memory to disk. PCMs
+  /// get flushed on a background thread as soon as they're built.
   bool FlushModuleCache = true;
   /// Whether the caching VFS should cache missing filesystem entries.
   bool CacheNegativeStats = shouldCacheNegativeStatsDefault();
@@ -116,11 +116,16 @@ class DependencyScanningService {
       : Opts(std::move(Opts)), Logger(this->Opts.LogPath) {
     ModCacheEntries.ValidateAgainstInvalidatedPaths =
         this->Opts.ValidateAgainstInvalidatedPaths;
+    if (this->Opts.FlushModuleCache)
+      ModCacheEntries.startBackgroundFlushing(Logger);
   }
 
   ~DependencyScanningService() {
-    if (Opts.FlushModuleCache)
-      ModCacheEntries.flush();
+    if (Opts.FlushModuleCache) {
+      ModCacheEntries.stopBackgroundFlushing();
+      // TODO: Consider allowing clients to skip this to terminate ASAP.
+      ModCacheEntries.flushLeftovers(Logger);
+    }
   }
 
   const DependencyScanningServiceOptions &getOpts() const { return Opts; }

diff  --git a/clang/include/clang/DependencyScanning/InProcessModuleCache.h 
b/clang/include/clang/DependencyScanning/InProcessModuleCache.h
index 03f0dc230cc029..4c6999fb008c03 100644
--- a/clang/include/clang/DependencyScanning/InProcessModuleCache.h
+++ b/clang/include/clang/DependencyScanning/InProcessModuleCache.h
@@ -16,9 +16,12 @@
 
 #include <atomic>
 #include <condition_variable>
+#include <deque>
 #include <memory>
 #include <mutex>
 #include <optional>
+#include <thread>
+#include <vector>
 
 namespace llvm {
 class MemoryBuffer;
@@ -38,7 +41,10 @@ struct ModuleCacheEntry {
   enum {
     S_Unknown,
     S_Read,
+    /// Written to the module cache, but only kept in memory.
     S_Written,
+    /// Written to the module cache and flushed to disk.
+    S_Flushed,
   } State = S_Unknown;
   /// The buffer we've read from disk or written to the module cache, if any.
   /// Buffers returned from \c ModuleCache::read() share ownership of this, so
@@ -48,6 +54,9 @@ struct ModuleCacheEntry {
   time_t ModTime = 0;
 };
 
+using ModuleCacheMapEntry =
+    llvm::StringMapEntry<std::unique_ptr<ModuleCacheEntry>>;
+
 struct ModuleCacheEntries {
   std::mutex Mutex;
   llvm::StringMap<std::unique_ptr<ModuleCacheEntry>> Map;
@@ -57,10 +66,37 @@ struct ModuleCacheEntries {
   void addInvalidatedPath(StringRef Path);
   std::optional<bool> isDirectoryInvalidated(StringRef Directory) const;
 
-  /// Flushes all PCMs built in-process to disk.
-  void flush();
+  /// Adds \p MapEntry into the queue of entries to be flushed.
+  void scheduleFlush(ModuleCacheMapEntry &MapEntry);
+
+  /// Starts a background thread that flushes PCMs built in-process to disk as
+  /// soon as they're written, replacing their in-memory buffers with
+  /// memory-mapped files.
+  void startBackgroundFlushing(AtomicLineLogger &Logger);
+
+  /// Stops the background thread as soon as it finishes flushing the current
+  /// PCM. PCMs it didn't get to are left for \c flushLeftovers().
+  void stopBackgroundFlushing();
+
+  /// Flushes all PCMs built in-process that haven't been flushed yet.
+  void flushLeftovers(AtomicLineLogger &Logger);
+
+  ~ModuleCacheEntries();
 
 private:
+  /// Flushes a single cache entry.
+  static void flushEntry(StringRef Path, ModuleCacheEntry &Entry,
+                         AtomicLineLogger &Logger, bool ReadBack);
+
+  /// Entries waiting to be flushed. These point into \c Map, whose entries 
have
+  /// stable addresses.
+  std::mutex FlushMutex;
+  std::deque<ModuleCacheMapEntry *> FlushEntries;
+  /// Notifies the background thread about new pending entries or stopping.
+  std::condition_variable FlushCondVar;
+  bool StopFlushing = false;
+  std::thread Flusher;
+
   mutable std::mutex InvalidatedPathsMutex;
   llvm::StringSet<> InvalidatedPaths;
   std::atomic<bool> AnyInvalidatedPaths = false;

diff  --git a/clang/lib/DependencyScanning/InProcessModuleCache.cpp 
b/clang/lib/DependencyScanning/InProcessModuleCache.cpp
index 76cbdddfda5230..28ac1637ddebd1 100644
--- a/clang/lib/DependencyScanning/InProcessModuleCache.cpp
+++ b/clang/lib/DependencyScanning/InProcessModuleCache.cpp
@@ -46,21 +46,85 @@ ModuleCacheEntries::isDirectoryInvalidated(StringRef 
Directory) const {
   return InvalidatedPaths.contains(Directory);
 }
 
-void ModuleCacheEntries::flush() {
-  auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
-  for (auto &[Path, Entry] : Map) {
-    if (Entry->State == ModuleCacheEntry::S_Written) {
-      assert(Entry->Buffer && "Wrote PCM with no contents");
-      // Note: We could propagate Entry->ModTime to the on-disk file, but
-      // implicitly-built modules (unlike explicitly-built modules) don't use
-      // that metadata to refer to imports, rendering this unnecessary.
-      off_t Size;
-      time_t ModTime;
-      // Best-effort: ignore errors (e.g. read-only cache directory).
-      (void)writeImpl(Path, *Entry->Buffer, Size, ModTime,
-                      /*ReadBack=*/false);
+ModuleCacheEntries::~ModuleCacheEntries() {
+  assert(!Flusher.joinable() && "Concurrent flushing was not stopped");
+}
+
+void ModuleCacheEntries::scheduleFlush(ModuleCacheMapEntry &MapEntry) {
+  // We're not flushing at all, nothing to schedule.
+  if (!Flusher.joinable())
+    return;
+
+  {
+    std::lock_guard<std::mutex> Lock(FlushMutex);
+    FlushEntries.push_back(&MapEntry);
+  }
+  FlushCondVar.notify_one();
+}
+
+void ModuleCacheEntries::startBackgroundFlushing(AtomicLineLogger &Logger) {
+  assert(!Flusher.joinable() && "Already started concurrent flushing");
+  Flusher = std::thread([this, &Logger] {
+    std::unique_lock<std::mutex> PendingLock(FlushMutex);
+    while (true) {
+      FlushCondVar.wait(PendingLock,
+                        [&] { return StopFlushing || !FlushEntries.empty(); });
+      // Leave the remaining entries to flushLeftovers().
+      if (StopFlushing)
+        return;
+      ModuleCacheMapEntry &MapEntry = *FlushEntries.front();
+      FlushEntries.pop_front();
+      PendingLock.unlock();
+      flushEntry(MapEntry.getKey(), *MapEntry.second, Logger,
+                 /*ReadBack=*/true);
+      PendingLock.lock();
     }
+  });
+}
+
+void ModuleCacheEntries::stopBackgroundFlushing() {
+  assert(Flusher.joinable() && "Never started concurrent flushing");
+  {
+    std::lock_guard<std::mutex> Lock(FlushMutex);
+    StopFlushing = true;
   }
+  FlushCondVar.notify_one();
+  Flusher.join();
+}
+
+void ModuleCacheEntries::flushLeftovers(AtomicLineLogger &Logger) {
+  assert(!Flusher.joinable() && "Flushing leftovers concurrently");
+  for (auto &[Name, Entry] : llvm::make_pointee_range(FlushEntries))
+    flushEntry(Name, *Entry, Logger, /*ReadBack=*/false);
+}
+
+void ModuleCacheEntries::flushEntry(StringRef Path, ModuleCacheEntry &Entry,
+                                    AtomicLineLogger &Logger, bool ReadBack) {
+  // This is a compiler-internal output, let's bypass the sandbox.
+  auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
+
+  std::shared_ptr<const llvm::MemoryBuffer> InMemoryBuffer;
+  {
+    std::lock_guard<std::mutex> Lock(Entry.Mutex);
+    if (Entry.State != ModuleCacheEntry::S_Written)
+      return;
+    InMemoryBuffer = Entry.Buffer;
+  }
+
+  off_t Size;
+  time_t ModTime;
+  auto Written = writeImpl(Path, *InMemoryBuffer, Size, ModTime, ReadBack);
+  if (!Written) {
+    // Best-effort: keep the buffer in memory and let flush() try again.
+    Logger.log() << "pcm_flush_failed: " << Path;
+    return;
+  }
+  Logger.log() << "pcm_flush: " << Path;
+
+  std::lock_guard<std::mutex> Lock(Entry.Mutex);
+  // Note: We keep Entry.ModTime, since that's what readers have already seen.
+  Entry.Buffer = std::move(*Written);
+  Entry.State = ModuleCacheEntry::S_Flushed;
 }
 
 namespace {
@@ -147,12 +211,16 @@ class InProcessModuleCache : public ModuleCache {
   // recreated for each translation unit.
   InMemoryModuleCache InMemory;
 
-  ModuleCacheEntry &getOrCreateEntry(StringRef Filename) {
+  ModuleCacheMapEntry &getOrCreateMapEntry(StringRef Filename) {
     std::lock_guard<std::mutex> Lock(Entries.Mutex);
-    auto &Entry = Entries.Map[Filename];
-    if (!Entry)
-      Entry = std::make_unique<ModuleCacheEntry>();
-    return *Entry;
+    auto &MapEntry = *Entries.Map.try_emplace(Filename).first;
+    if (!MapEntry.second)
+      MapEntry.second = std::make_unique<ModuleCacheEntry>();
+    return MapEntry;
+  }
+
+  ModuleCacheEntry &getOrCreateEntry(StringRef Filename) {
+    return *getOrCreateMapEntry(Filename).second;
   }
 
 public:
@@ -198,10 +266,12 @@ class InProcessModuleCache : public ModuleCache {
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
   write(StringRef Path, std::unique_ptr<llvm::MemoryBuffer> Buffer, off_t 
&Size,
         time_t &ModTime) override {
-    ModuleCacheEntry &Entry = getOrCreateEntry(Path);
+    ModuleCacheMapEntry &MapEntry = getOrCreateMapEntry(Path);
+    ModuleCacheEntry &Entry = *MapEntry.second;
     std::lock_guard<std::mutex> Lock(Entry.Mutex);
     Logger.log() << "pcm_write: " << Path;
-    if (Entry.State == ModuleCacheEntry::S_Written) {
+    if (Entry.State == ModuleCacheEntry::S_Written ||
+        Entry.State == ModuleCacheEntry::S_Flushed) {
       assert(Entry.Buffer && "Wrote PCM with no contents");
       assert(Entry.Buffer->getBuffer() == Buffer->getBuffer() &&
              "Wrote the same PCM with 
diff erent contents");
@@ -213,6 +283,7 @@ class InProcessModuleCache : public ModuleCache {
     Entry.Buffer = std::move(Buffer);
     Entry.ModTime = llvm::sys::toTimeT(std::chrono::system_clock::now());
     Entry.State = ModuleCacheEntry::S_Written;
+    Entries.scheduleFlush(MapEntry);
     Size = Entry.Buffer->getBufferSize();
     ModTime = Entry.ModTime;
     return std::make_unique<SharedMemoryBuffer>(Entry.Buffer);

diff  --git a/clang/test/ClangScanDeps/logging-simple-by-name.c 
b/clang/test/ClangScanDeps/logging-simple-by-name.c
index b02fad5117ea9c..c88a8bcac23757 100644
--- a/clang/test/ClangScanDeps/logging-simple-by-name.c
+++ b/clang/test/ClangScanDeps/logging-simple-by-name.c
@@ -15,7 +15,8 @@
 // RUN: clang-scan-deps -compilation-database %t/cdb.json \
 // RUN:   -format experimental-full -log-path=%t/scan.log -j 1 \
 // RUN:   -module-names=M,N -o %t/deps.json
-// RUN: FileCheck %s < %t/scan.log
+// The background thread flushes PCMs at nondeterministic points, ignore that.
+// RUN: grep -v pcm_flush: %t/scan.log | FileCheck %s
 
 // CHECK: [{{[0-9]+\.[0-9]+}}] [[#PID:]] [[#TID1:]]: logging_start
 // CHECK-NEXT: [{{[0-9]+\.[0-9]+}}] [[#PID]] [[#TID1]]: 
init_compiler_instance_with_context:{{.*}}

diff  --git a/clang/test/ClangScanDeps/logging-simple.c 
b/clang/test/ClangScanDeps/logging-simple.c
index 444fdf1ab6e203..69c0616b7e67d3 100644
--- a/clang/test/ClangScanDeps/logging-simple.c
+++ b/clang/test/ClangScanDeps/logging-simple.c
@@ -7,7 +7,8 @@
 
 // RUN: clang-scan-deps -compilation-database %t/cdb.json \
 // RUN:   -format experimental-full -log-path=%t/scan.log -j 1 -o %t/deps.json
-// RUN: FileCheck %s < %t/scan.log
+// The background thread flushes PCMs at nondeterministic points, ignore that.
+// RUN: grep -v pcm_flush: %t/scan.log | FileCheck %s
 
 // The check lines below form a strict sequence of events logged when we only
 // build a single scanning pcm. We should only log these events, no more and no

diff  --git a/clang/test/ClangScanDeps/module-cache-flush-in-background.c 
b/clang/test/ClangScanDeps/module-cache-flush-in-background.c
new file mode 100644
index 00000000000000..26ecccceed9f60
--- /dev/null
+++ b/clang/test/ClangScanDeps/module-cache-flush-in-background.c
@@ -0,0 +1,50 @@
+// Test that PCMs built in-process get flushed to disk in the background.
+
+// UNSUPPORTED: system-windows
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+
+// Without flushing, nothing gets written to disk.
+// RUN: clang-scan-deps -compilation-database %t/cdb.json 
-no-flush-module-cache \
+// RUN:   -format experimental-full -j 1 -o %t/deps-no-flush.json
+// RUN: find %t/cache -name "*.pcm" | count 0
+
+// By default, both PCMs get flushed in the background.
+// RUN: rm -rf %t/cache
+// RUN: clang-scan-deps -compilation-database %t/cdb.json 
-log-path=%t/scan.log \
+// RUN:   -format experimental-full -j 1 -o %t/deps-flush.json
+// RUN: find %t/cache -name "M-*.pcm" | count 1
+// RUN: find %t/cache -name "N-*.pcm" | count 1
+// RUN: FileCheck %s < %t/scan.log
+// RUN: 
diff  %t/deps-no-flush.json %t/deps-flush.json
+
+// CHECK-DAG: pcm_flush: {{.*}}M-{{.*}}.pcm
+// CHECK-DAG: pcm_flush: {{.*}}N-{{.*}}.pcm
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu1.c -fmodules -fimplicit-module-maps 
-fmodules-cache-path=DIR/cache",
+  "file": "DIR/tu1.c"
+},{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu2.c -fmodules -fimplicit-module-maps 
-fmodules-cache-path=DIR/cache",
+  "file": "DIR/tu2.c"
+}]
+
+//--- module.modulemap
+module M { header "M.h" }
+module N { header "N.h" }
+
+//--- M.h
+void m(void);
+
+//--- N.h
+void n(void);
+
+//--- tu1.c
+#include "M.h"
+
+//--- tu2.c
+#include "N.h"

diff  --git a/clang/tools/clang-scan-deps/Opts.td 
b/clang/tools/clang-scan-deps/Opts.td
index 663d8468847f39..7ff3da1800cb6c 100644
--- a/clang/tools/clang-scan-deps/Opts.td
+++ b/clang/tools/clang-scan-deps/Opts.td
@@ -56,7 +56,7 @@ def async_scan_modules : F<"async-scan-modules", "Scan 
modules asynchronously">;
 
 def round_trip_args : F<"round-trip-args", "verify that command-line arguments 
are canonical by parsing and re-serializing">;
 
-def no_flush_module_cache : F<"no-flush-module-cache", "do not flush the 
module cache from memory to disk at the end of the scan">;
+def no_flush_module_cache : F<"no-flush-module-cache", "do not flush the 
module cache from memory to disk">;
 
 def verbatim_args : F<"verbatim-args", "Pass commands to the scanner verbatim 
without adjustments">;
 

diff  --git a/clang/unittests/DependencyScanning/InProcessModuleCacheTest.cpp 
b/clang/unittests/DependencyScanning/InProcessModuleCacheTest.cpp
index fd2f24e9851291..e97bdfc8d2a017 100644
--- a/clang/unittests/DependencyScanning/InProcessModuleCacheTest.cpp
+++ b/clang/unittests/DependencyScanning/InProcessModuleCacheTest.cpp
@@ -3,10 +3,14 @@
 #include "clang/Basic/AtomicLineLogger.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Testing/Support/Error.h"
 
 #include "gtest/gtest.h"
 
+#include <chrono>
+#include <thread>
+
 using namespace clang;
 using namespace clang::dependencies;
 
@@ -112,3 +116,72 @@ TEST(InProcessModuleCache, WriteReturnsSharedBuffer) {
   ASSERT_TRUE(*RewrittenOrErr);
   EXPECT_EQ((*RewrittenOrErr)->getBufferStart(), Written->getBufferStart());
 }
+
+TEST(InProcessModuleCache, FlushInBackground) {
+  AtomicLineLogger Logger;
+  ModuleCacheEntries Entries;
+  Entries.startBackgroundFlushing(Logger);
+  std::shared_ptr<ModuleCache> ModCache =
+      makeInProcessModuleCache(Entries, Logger);
+
+  llvm::SmallString<256> Dir;
+  ASSERT_FALSE(llvm::sys::fs::createUniqueDirectory("cache", Dir));
+  llvm::SmallString<256> Path(Dir);
+  llvm::sys::path::append(Path, "M.pcm");
+
+  // Large enough for the buffer to be memory-mapped when read back.
+  std::string Contents(1024 * 1024, 'm');
+  off_t Size;
+  time_t WrittenModTime;
+  auto WrittenOrErr = ModCache->write(
+      Path, llvm::MemoryBuffer::getMemBufferCopy(Contents, Path), Size,
+      WrittenModTime);
+  ASSERT_EQ(WrittenOrErr.getError(), std::error_code{});
+  std::unique_ptr<llvm::MemoryBuffer> Written = std::move(*WrittenOrErr);
+
+  // Nothing guarantees the background thread gets scheduled before we stop it,
+  // and stopping leaves unflushed PCMs behind. Wait until it swaps in the
+  // memory-mapped buffer, which happens after the PCM appears on disk.
+  auto IsFlushed = [&] {
+    off_t ReadSize;
+    time_t ReadModTime;
+    auto Read = ModCache->read(Path, ReadSize, ReadModTime);
+    if (!Read) {
+      llvm::consumeError(Read.takeError());
+      return false;
+    }
+    return (*Read)->getBufferKind() == llvm::MemoryBuffer::MemoryBuffer_MMap;
+  };
+  auto Deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);
+  while (!IsFlushed() && std::chrono::steady_clock::now() < Deadline)
+    std::this_thread::sleep_for(std::chrono::milliseconds(1));
+
+  Entries.stopBackgroundFlushing();
+
+  // The PCM got written to disk without an explicit flush.
+  EXPECT_TRUE(llvm::sys::fs::exists(Path));
+
+  // Flushing should not invalidate the previously-returned buffer.
+  EXPECT_EQ(Written->getBuffer(), Contents);
+
+  // The flushed PCM is now memory-mapped from disk, with the same metadata.
+  time_t ModTime;
+  std::unique_ptr<llvm::MemoryBuffer> Read;
+  ASSERT_THAT_ERROR(ModCache->read(Path, Size, ModTime).moveInto(Read),
+                    llvm::Succeeded());
+  EXPECT_EQ(Read->getBuffer(), Contents);
+  EXPECT_EQ(Read->getBufferKind(), llvm::MemoryBuffer::MemoryBuffer_MMap);
+  EXPECT_EQ(Size, off_t(Contents.size()));
+  EXPECT_EQ(ModTime, WrittenModTime);
+
+  // Writing the same contents again keeps the PCM flushed.
+  ASSERT_EQ(ModCache
+                ->write(Path,
+                        llvm::MemoryBuffer::getMemBufferCopy(Contents, Path),
+                        Size, ModTime)
+                .getError(),
+            std::error_code{});
+  EXPECT_EQ(ModTime, WrittenModTime);
+
+  llvm::sys::fs::remove_directories(Dir);
+}


        
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to