[llvm-branch-commits] [clang] [clang][deps] Flush the in-process module cache on a background thread (PR #242385)

Jan Svoboda via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Mon Nov 16 10:52:32 PST 2026


https://github.com/jansvoboda11 updated https://github.com/llvm/llvm-project/pull/242385

>From 9e0cfacdfc529d7903f97222769d583c23dd1a62 Mon Sep 17 00:00:00 2001
From: Jan Svoboda <jan_svoboda at apple.com>
Date: Thu, 12 Nov 2026 21:09:31 -0800
Subject: [PATCH] [clang][deps] Flush the in-process module cache on a
 background thread

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.
---
 .../DependencyScanningService.h               |   9 +-
 .../DependencyScanning/InProcessModuleCache.h |  39 ++++++-
 .../InProcessModuleCache.cpp                  | 103 ++++++++++++++++--
 .../ClangScanDeps/logging-simple-by-name.c    |   3 +-
 clang/test/ClangScanDeps/logging-simple.c     |   3 +-
 .../module-cache-flush-in-background.c        |  50 +++++++++
 clang/tools/clang-scan-deps/Opts.td           |   2 +-
 .../InProcessModuleCacheTest.cpp              |  53 +++++++++
 8 files changed, 249 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/ClangScanDeps/module-cache-flush-in-background.c

diff --git a/clang/include/clang/DependencyScanning/DependencyScanningService.h b/clang/include/clang/DependencyScanning/DependencyScanningService.h
index d1fc26490423cd..7d4f001b970706 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,9 +116,14 @@ class DependencyScanningService {
       : Opts(std::move(Opts)), Logger(this->Opts.LogPath) {
     ModCacheEntries.ValidateAgainstInvalidatedPaths =
         this->Opts.ValidateAgainstInvalidatedPaths;
+    if (this->Opts.FlushModuleCache)
+      ModCacheEntries.startFlushing(Logger);
   }
 
   ~DependencyScanningService() {
+    // The background thread references the logger, which gets destroyed first.
+    ModCacheEntries.stopFlushing();
+    // Just in case, flush whatever the background thread failed to write.
     if (Opts.FlushModuleCache)
       ModCacheEntries.flush();
   }
diff --git a/clang/include/clang/DependencyScanning/InProcessModuleCache.h b/clang/include/clang/DependencyScanning/InProcessModuleCache.h
index 03f0dc230cc029..5be62f6765c8e8 100644
--- a/clang/include/clang/DependencyScanning/InProcessModuleCache.h
+++ b/clang/include/clang/DependencyScanning/InProcessModuleCache.h
@@ -19,6 +19,8 @@
 #include <memory>
 #include <mutex>
 #include <optional>
+#include <thread>
+#include <vector>
 
 namespace llvm {
 class MemoryBuffer;
@@ -38,7 +40,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 +53,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 +65,39 @@ struct ModuleCacheEntries {
   void addInvalidatedPath(StringRef Path);
   std::optional<bool> isDirectoryInvalidated(StringRef Directory) const;
 
-  /// Flushes all PCMs built in-process to disk.
+  ~ModuleCacheEntries();
+
+  /// Flushes all PCMs built in-process that haven't been flushed yet to disk.
   void flush();
 
+  /// 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 startFlushing(AtomicLineLogger &Logger);
+
+  /// Waits for the background thread to flush all written PCMs and stops it.
+  /// PCMs that failed to be written are kept in memory only.
+  void stopFlushing();
+
+  /// Hands \p MapEntry, which was just written, to the background thread.
+  void addPending(ModuleCacheMapEntry &MapEntry);
+
 private:
+  /// The body of the background thread, see \c startFlushing().
+  void flushInBackground(AtomicLineLogger &Logger);
+
+  /// Flushes single entry, see \c startFlushing().
+  void flushEntry(ModuleCacheMapEntry &MapEntry, AtomicLineLogger &Logger);
+
+  /// Entries waiting to be flushed by the background thread. These point into
+  /// \c Map, whose entries have stable addresses.
+  std::mutex PendingMutex;
+  std::vector<ModuleCacheMapEntry *> Pending;
+  /// Notifies the background thread about new pending entries or stopping.
+  std::condition_variable PendingCondVar;
+  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..45265a504ba854 100644
--- a/clang/lib/DependencyScanning/InProcessModuleCache.cpp
+++ b/clang/lib/DependencyScanning/InProcessModuleCache.cpp
@@ -46,6 +46,8 @@ ModuleCacheEntries::isDirectoryInvalidated(StringRef Directory) const {
   return InvalidatedPaths.contains(Directory);
 }
 
+ModuleCacheEntries::~ModuleCacheEntries() { stopFlushing(); }
+
 void ModuleCacheEntries::flush() {
   auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
   for (auto &[Path, Entry] : Map) {
@@ -63,6 +65,86 @@ void ModuleCacheEntries::flush() {
   }
 }
 
+void ModuleCacheEntries::startFlushing(AtomicLineLogger &Logger) {
+  assert(!Flusher.joinable() && "Already flushing in the background");
+  Flusher = std::thread([this, &Logger] { flushInBackground(Logger); });
+}
+
+void ModuleCacheEntries::stopFlushing() {
+  if (!Flusher.joinable())
+    return;
+  {
+    std::lock_guard<std::mutex> Lock(PendingMutex);
+    StopFlushing = true;
+  }
+  PendingCondVar.notify_one();
+  Flusher.join();
+}
+
+void ModuleCacheEntries::addPending(ModuleCacheMapEntry &MapEntry) {
+  // Note: The background thread only gets started or stopped while no PCMs
+  // are being written.
+  if (!Flusher.joinable())
+    return;
+  {
+    std::lock_guard<std::mutex> Lock(PendingMutex);
+    Pending.push_back(&MapEntry);
+  }
+  PendingCondVar.notify_one();
+}
+
+void ModuleCacheEntries::flushInBackground(AtomicLineLogger &Logger) {
+  // This is a compiler-internal output, let's bypass the sandbox.
+  auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
+  std::unique_lock<std::mutex> Lock(PendingMutex);
+  while (true) {
+    PendingCondVar.wait(Lock, [&] { return StopFlushing || !Pending.empty(); });
+    // Flush everything that's been written before stopping.
+    if (Pending.empty())
+      return;
+    std::vector<ModuleCacheMapEntry *> Batch;
+    std::swap(Batch, Pending);
+    Lock.unlock();
+    for (ModuleCacheMapEntry *MapEntry : Batch)
+      flushEntry(*MapEntry, Logger);
+    Lock.lock();
+  }
+}
+
+void ModuleCacheEntries::flushEntry(ModuleCacheMapEntry &MapEntry,
+                                    AtomicLineLogger &Logger) {
+  StringRef Path = MapEntry.getKey();
+  ModuleCacheEntry &Entry = *MapEntry.second;
+  std::shared_ptr<const llvm::MemoryBuffer> InMemory;
+  {
+    std::lock_guard<std::mutex> Lock(Entry.Mutex);
+    if (Entry.State != ModuleCacheEntry::S_Written)
+      return;
+    InMemory = Entry.Buffer;
+  }
+
+  // The contents of an entry in the S_Written state don't change, so we can
+  // write them without holding the lock. This way, importers of the freshly
+  // built PCM don't need to wait for the IO.
+  off_t Size;
+  time_t ModTime;
+  auto Written = writeImpl(Path, *InMemory, Size, ModTime, /*ReadBack=*/true);
+  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.
+  // Small files don't get memory-mapped, in which case we keep the original
+  // buffer to avoid churn. Readers keep the original buffer alive on their own.
+  if ((*Written)->getBufferKind() == llvm::MemoryBuffer::MemoryBuffer_MMap)
+    Entry.Buffer = std::move(*Written);
+  Entry.State = ModuleCacheEntry::S_Flushed;
+}
+
 namespace {
 /// A buffer that keeps the contents of a \c ModuleCacheEntry alive.
 class SharedMemoryBuffer : public llvm::MemoryBuffer {
@@ -147,12 +229,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 +284,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 different contents");
@@ -213,6 +301,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.addPending(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..4966d63fd6992c 100644
--- a/clang/unittests/DependencyScanning/InProcessModuleCacheTest.cpp
+++ b/clang/unittests/DependencyScanning/InProcessModuleCacheTest.cpp
@@ -3,6 +3,7 @@
 #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"
@@ -112,3 +113,55 @@ TEST(InProcessModuleCache, WriteReturnsSharedBuffer) {
   ASSERT_TRUE(*RewrittenOrErr);
   EXPECT_EQ((*RewrittenOrErr)->getBufferStart(), Written->getBufferStart());
 }
+
+TEST(InProcessModuleCache, FlushInBackground) {
+  AtomicLineLogger Logger;
+  ModuleCacheEntries Entries;
+  Entries.startFlushing(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);
+
+  Entries.stopFlushing();
+
+  // 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);
+}



More information about the llvm-branch-commits mailing list