Skip to content

[lldb] Fix stale L1 memory cache read after memory write - #208347

Merged
qiyao merged 1 commit into
llvm:mainfrom
qiyao:fix-l1-cache-overlap-flush
Jul 30, 2026
Merged

qiyao merged 1 commit into
llvm:mainfrom
qiyao:fix-l1-cache-overlap-flush

Conversation

@qiyao

@qiyao qiyao commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

A memory write can leave stale bytes in the L1 memory cache, so a later
memory read of the address that was just written returns the old value.

Reproduce from the CLI with a program that fills a global buffer:

char buf[1024];

int main() {
  for (int i = 0; i < 1024; i++)
    buf[i] = 0x11;
  return 0; // break here
}
(lldb) memory read -f x -s 1 -c 600 &buf[0]
0x100004000: 0x11 0x11 0x11 0x11 ...
(lldb) memory read -f x -s 1 -c 600 &buf[100]
0x100004064: 0x11 0x11 0x11 0x11 ...
(lldb) memory write -s 1 &buf[300] 0xff
(lldb) memory read -f x -s 1 -c 4 &buf[300]
0x10000412c: 0x11 0x11 0x11 0x11

The last read should show 0xff at &buf[300]. Instead it still shows the
old 0x11. The write did reach the process, but the cached copy was never
invalidated, so the read is served from the cache.

The L1 cache (m_L1_cache) is a map keyed by each chunk's start address, and
its readers assume the chunks never overlap. FindL1CacheEntry and Flush
both look only at the single chunk whose start is nearest the address. Flush
starts at the chunk at or below the flushed address and walks forward, so it
never revisits a chunk that starts lower but is long enough to also cover the
address.

AddL1CacheData inserted a new chunk without reconciling what it overlapped, so
two chunks could cover the same address. A read larger than an L2 cache line
(target.memory-cache-line-size, 512 by default) bypasses L2 and is stored in
L1, so the two 600 byte reads above produce two overlapping L1 chunks,
[&buf[0], &buf[600]) and [&buf[100], &buf[700]), both covering &buf[300].

memory write calls MemoryCache::Flush(&buf[300], 1). Flush lands on
[&buf[100], ...), the highest start at or below &buf[300], erases it, and
stops, leaving [&buf[0], ...) in the cache with the stale byte. The final
memory read is fully contained in that surviving chunk, so FindL1CacheEntry
returns the old 0x11.

Fix this in AddL1CacheData by merging a new chunk with every chunk it
intersects into a single chunk spanning their union, so the L1 chunks stay
disjoint. That restores the invariant Flush and FindL1CacheEntry rely on
while keeping the coverage of every merged chunk. The process is stopped while
the cache is populated, so overlapping chunks hold identical bytes; where they
might differ, the just fetched data wins. With the fix the final read reports
0xff.

Add a unit test that exercises the overlap shapes a merge must handle: a new
chunk extending an existing one to the right or the left, a new chunk that
covers or is covered by an existing one, a new chunk that bridges two existing
chunks, and non-overlapping chunks that must stay separate.

@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-lldb

Author: Yao Qi (qiyao)

Changes

A memory write can leave stale bytes in the L1 memory cache, so a later
memory read of the address that was just written returns the old value.

Reproduce from the CLI with a program that fills a global buffer:

char buf[1024];

int main() {
  for (int i = 0; i &lt; 1024; i++)
    buf[i] = 0x11;
  return 0; // break here
}
(lldb) memory read -f x -s 1 -c 600 &amp;buf[0]
0x100004000: 0x11 0x11 0x11 0x11 ...
(lldb) memory read -f x -s 1 -c 600 &amp;buf[100]
0x100004064: 0x11 0x11 0x11 0x11 ...
(lldb) memory write -s 1 &amp;buf[300] 0xff
(lldb) memory read -f x -s 1 -c 4 &amp;buf[300]
0x10000412c: 0x11 0x11 0x11 0x11

The last read should show 0xff at &amp;buf[300]. Instead it still shows the
old 0x11. The write did reach the process, but the cached copy was never
invalidated, so the read is served from the cache.

The L1 cache (m_L1_cache) is a map keyed by each chunk's start address, and
its readers assume the chunks never overlap. FindL1CacheEntry and Flush
both look only at the single chunk whose start is nearest the address. Flush
starts at the chunk at or below the flushed address and walks forward, so it
never revisits a chunk that starts lower but is long enough to also cover the
address.

AddL1CacheData inserted a new chunk without reconciling what it overlapped, so
two chunks could cover the same address. A read larger than an L2 cache line
(target.memory-cache-line-size, 512 by default) bypasses L2 and is stored in
L1, so the two 600 byte reads above produce two overlapping L1 chunks,
[&amp;buf[0], &amp;buf[600]) and [&amp;buf[100], &amp;buf[700]), both covering &amp;buf[300].

memory write calls MemoryCache::Flush(&amp;buf[300], 1). Flush lands on
[&amp;buf[100], ...), the highest start at or below &amp;buf[300], erases it, and
stops, leaving [&amp;buf[0], ...) in the cache with the stale byte. The final
memory read is fully contained in that surviving chunk, so FindL1CacheEntry
returns the old 0x11.

Fix this in AddL1CacheData by merging a new chunk with every chunk it
intersects into a single chunk spanning their union, so the L1 chunks stay
disjoint. That restores the invariant Flush and FindL1CacheEntry rely on
while keeping the coverage of every merged chunk. The process is stopped while
the cache is populated, so overlapping chunks hold identical bytes; where they
might differ, the just fetched data wins. With the fix the final read reports
0xff.

Add a unit test that exercises the overlap shapes a merge must handle: a new
chunk extending an existing one to the right or the left, a new chunk that
covers or is covered by an existing one, a new chunk that bridges two existing
chunks, and non-overlapping chunks that must stay separate.


Full diff: https://github.com/llvm/llvm-project/pull/208347.diff

2 Files Affected:

  • (modified) lldb/source/Target/Memory.cpp (+61-1)
  • (modified) lldb/unittests/Target/MemoryTest.cpp (+125)
diff --git a/lldb/source/Target/Memory.cpp b/lldb/source/Target/Memory.cpp
index f70da27ec058b..b71ce1da47780 100644
--- a/lldb/source/Target/Memory.cpp
+++ b/lldb/source/Target/Memory.cpp
@@ -16,6 +16,7 @@
 
 #include "llvm/ADT/STLExtras.h"
 
+#include <algorithm>
 #include <cinttypes>
 #include <memory>
 
@@ -48,7 +49,66 @@ void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,
 void MemoryCache::AddL1CacheData(lldb::addr_t addr,
                                  const DataBufferSP &data_buffer_sp) {
   std::lock_guard<std::recursive_mutex> guard(m_mutex);
-  m_L1_cache[addr] = data_buffer_sp;
+  // The L1 cache is kept as a set of non-overlapping chunks: both Flush() and
+  // FindL1CacheEntry() only inspect the single chunk whose start is closest to
+  // a given address, so they assume no two chunks cover the same address.
+  //
+  // A new chunk can overlap ones that are already cached.  Merge the new chunk
+  // with every chunk it intersects into a single chunk spanning their union, so
+  // the coverage of all of them is kept while the invariant holds.  The process
+  // is stopped while the cache is populated, so overlapping chunks hold
+  // identical bytes; where they might differ, the just fetched data wins.
+  const size_t data_byte_size = data_buffer_sp->GetByteSize();
+  // A zero-length chunk can never satisfy a read and would never be flushed, so
+  // there is nothing to cache.
+  if (data_byte_size == 0)
+    return;
+
+  AddrRange new_range(addr, data_byte_size);
+  addr_t merged_base = new_range.GetRangeBase();
+  addr_t merged_end = new_range.GetRangeEnd();
+
+  // Chunks are ordered by start address and do not overlap, so the chunks that
+  // intersect the new one form a contiguous run.  The first one that can
+  // intersect is the chunk starting at or immediately below addr; start there
+  // and walk forward while a chunk still intersects the new range.
+  BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
+  if (pos != m_L1_cache.begin())
+    --pos;
+  BlockMap::iterator merge_first = m_L1_cache.end();
+  BlockMap::iterator merge_end = m_L1_cache.end();
+  while (pos != m_L1_cache.end() && pos->first < new_range.GetRangeEnd()) {
+    AddrRange chunk_range(pos->first, pos->second->GetByteSize());
+    if (chunk_range.DoesIntersect(new_range)) {
+      merged_base = std::min(merged_base, chunk_range.GetRangeBase());
+      merged_end = std::max(merged_end, chunk_range.GetRangeEnd());
+      if (merge_first == m_L1_cache.end())
+        merge_first = pos;
+      merge_end = std::next(pos);
+    }
+    ++pos;
+  }
+
+  // No overlap: insert the new chunk as is.
+  if (merge_first == m_L1_cache.end()) {
+    m_L1_cache[addr] = data_buffer_sp;
+    return;
+  }
+
+  // Build the merged chunk spanning [merged_base, merged_end).  The overlapped
+  // chunks together with the new range cover it with no gap.  Copy the
+  // overlapped chunks first, then the new data on top so the just fetched bytes
+  // win where they overlap.
+  auto merged_buffer_sp =
+      std::make_shared<DataBufferHeap>(merged_end - merged_base, 0);
+  for (BlockMap::iterator it = merge_first; it != merge_end; ++it)
+    memcpy(merged_buffer_sp->GetBytes() + (it->first - merged_base),
+           it->second->GetBytes(), it->second->GetByteSize());
+  memcpy(merged_buffer_sp->GetBytes() + (addr - merged_base),
+         data_buffer_sp->GetBytes(), data_byte_size);
+
+  m_L1_cache.erase(merge_first, merge_end);
+  m_L1_cache[merged_base] = merged_buffer_sp;
 }
 
 void MemoryCache::Flush(addr_t addr, size_t size) {
diff --git a/lldb/unittests/Target/MemoryTest.cpp b/lldb/unittests/Target/MemoryTest.cpp
index 9d04376b4fd5b..1f59e1fe0945c 100644
--- a/lldb/unittests/Target/MemoryTest.cpp
+++ b/lldb/unittests/Target/MemoryTest.cpp
@@ -283,6 +283,131 @@ TEST_F(MemoryTest, TesetMemoryCacheRead) {
                                                        // old cache
 }
 
+TEST_F(MemoryTest, TestAddL1CacheDataMergesOverlappingChunks) {
+  ArchSpec arch("arm64-apple-macosx");
+
+  Platform::SetHostPlatform(PlatformRemoteMacOSX::CreateInstance(true, &arch));
+
+  DebuggerSP debugger_sp = Debugger::CreateInstance();
+  ASSERT_TRUE(debugger_sp);
+
+  TargetSP target_sp = CreateTarget(debugger_sp, arch);
+  ASSERT_TRUE(target_sp);
+
+  ProcessSP process_sp = CreateProcess(target_sp);
+  ASSERT_TRUE(process_sp);
+
+  DummyProcess *process = static_cast<DummyProcess *>(process_sp.get());
+  MemoryCache &mem_cache = process->GetMemoryCache();
+  Status error;
+
+  // Two L1 chunks can end up covering the same address.  AddL1CacheData()
+  // maintains no-overlap-chunks by merging a new chunk with every chunk it
+  // intersects into one chunk spanning their union. Verify the merge for the
+  // various overlap shapes.
+  auto add = [&](lldb::addr_t addr, size_t size, uint8_t fill) {
+    mem_cache.AddL1CacheData(addr,
+                             std::make_shared<DataBufferHeap>(size, fill));
+  };
+
+  // Reads [addr, addr+size). A zero max read size makes any cache miss fail, so
+  // a full-size return proves the range was served entirely from one L1 chunk.
+  auto read_sp = std::make_shared<DataBufferHeap>(0x400, 0);
+  auto l1_read = [&](lldb::addr_t addr, size_t size) -> size_t {
+    process->SetMaxReadSize(0);
+    memset(read_sp->GetBytes(), 0, size);
+    return mem_cache.Read(addr, read_sp->GetBytes(), size, error);
+  };
+  auto bytes_in = [&](size_t offset, size_t len, uint8_t val) -> bool {
+    const uint8_t *bytes = read_sp->GetBytes();
+    for (size_t i = offset; i < offset + len; ++i)
+      if (bytes[i] != val)
+        return false;
+    return true;
+  };
+
+  // Case 1: the new chunk extends the existing one to the right.
+  //   old [0x1000, 0x1100)  new [0x1080, 0x1180)  =>  [0x1000, 0x1180)
+  // Each case clears the cache first so the cases are independent.
+  mem_cache.Clear();
+  add(0x1000, 0x100, 0xAA);
+  add(0x1080, 0x100, 0xBB);
+  EXPECT_EQ(l1_read(0x1000, 0x180), 0x180u); // merged into a single chunk
+  EXPECT_TRUE(bytes_in(0x0, 0x80, 0xAA));    // old bytes outside the overlap
+  EXPECT_TRUE(bytes_in(0x80, 0x100, 0xBB));  // overlap + new: new wins
+
+  // Case 2: the new chunk extends the existing one to the left.
+  //   old [0x2080, 0x2180)  new [0x2000, 0x2100)  =>  [0x2000, 0x2180)
+  mem_cache.Clear();
+  add(0x2080, 0x100, 0xAA);
+  add(0x2000, 0x100, 0xBB);
+  EXPECT_EQ(l1_read(0x2000, 0x180), 0x180u);
+  EXPECT_TRUE(bytes_in(0x0, 0x100, 0xBB));  // new + overlap: new wins
+  EXPECT_TRUE(bytes_in(0x100, 0x80, 0xAA)); // old bytes outside the overlap
+
+  // Case 3: the new chunk fully covers the existing one.
+  //   old [0x3040, 0x3080)  new [0x3000, 0x3100)  =>  [0x3000, 0x3100)
+  mem_cache.Clear();
+  add(0x3040, 0x40, 0xAA);
+  add(0x3000, 0x100, 0xBB);
+  EXPECT_EQ(l1_read(0x3000, 0x100), 0x100u);
+  EXPECT_TRUE(bytes_in(0x0, 0x100, 0xBB));
+
+  // Case 4: the new chunk falls entirely within the existing one.
+  //   old [0x4000, 0x4200)  new [0x4080, 0x4100)  =>  [0x4000, 0x4200)
+  mem_cache.Clear();
+  add(0x4000, 0x200, 0xAA);
+  add(0x4080, 0x80, 0xBB);
+  EXPECT_EQ(l1_read(0x4000, 0x200), 0x200u);
+  EXPECT_TRUE(bytes_in(0x0, 0x80, 0xAA));    // old head
+  EXPECT_TRUE(bytes_in(0x80, 0x80, 0xBB));   // new wins in the middle
+  EXPECT_TRUE(bytes_in(0x100, 0x100, 0xAA)); // old tail
+
+  // Case 5: the new chunk bridges two existing chunks, overlapping both.
+  //   old [0x5000, 0x5080)  old [0x5100, 0x5180)  new [0x5040, 0x5140)
+  //   =>  [0x5000, 0x5180)
+  mem_cache.Clear();
+  add(0x5000, 0x80, 0xAA);
+  add(0x5100, 0x80, 0xCC);
+  add(0x5040, 0x100, 0xBB);
+  EXPECT_EQ(l1_read(0x5000, 0x180), 0x180u); // all three merged into one
+  EXPECT_TRUE(bytes_in(0x0, 0x40, 0xAA));    // first chunk, outside the overlap
+  EXPECT_TRUE(bytes_in(0x40, 0x100, 0xBB));  // new spans the middle
+  EXPECT_TRUE(bytes_in(0x140, 0x40, 0xCC)); // second chunk, outside the overlap
+
+  // Case 6: chunks that do not overlap are left separate, so a read spanning
+  // both misses while each is still served on its own.
+  //   [0x6000, 0x6080)  and  [0x6100, 0x6180), with a gap in between.
+  mem_cache.Clear();
+  add(0x6000, 0x80, 0xAA);
+  add(0x6100, 0x80, 0xBB);
+  EXPECT_EQ(l1_read(0x6000, 0x80), 0x80u);
+  EXPECT_TRUE(bytes_in(0x0, 0x80, 0xAA));
+  EXPECT_EQ(l1_read(0x6100, 0x80), 0x80u);
+  EXPECT_TRUE(bytes_in(0x0, 0x80, 0xBB));
+  EXPECT_NE(l1_read(0x6000, 0x180), 0x180u); // not one chunk: not fully served
+
+  // Case 7: adjacent (touching but not overlapping) chunks are also left
+  // separate, matching the intersect-only merge rule.
+  //   [0x7000, 0x7080)  and  [0x7080, 0x7100).
+  mem_cache.Clear();
+  add(0x7000, 0x80, 0xAA);
+  add(0x7080, 0x80, 0xBB);
+  EXPECT_NE(l1_read(0x7000, 0x100), 0x100u);
+
+  // A write anywhere in a merged chunk flushes the whole chunk, so a re-read
+  // comes from the process rather than returning stale bytes. This is the
+  // condition the disjoint invariant guarantees.
+  mem_cache.Clear();
+  add(0x8000, 0x100, 0xAA);
+  add(0x8080, 0x100, 0xBB); // => merged [0x8000, 0x8180)
+  mem_cache.Flush(0x8040, 0x4);
+  process->SetFiller(0xDD);
+  process->SetMaxReadSize(0x1000);
+  ASSERT_EQ(mem_cache.Read(0x8040, read_sp->GetBytes(), 0x4, error), 0x4u);
+  EXPECT_TRUE(bytes_in(0x0, 0x4, 0xDD));
+}
+
 TEST_F(MemoryTest, TestReadInteger) {
   ArchSpec arch("x86_64-apple-macosx-");
 

@qiyao

qiyao commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

I found this pre-existing bug when I am working on expediting stack memory to lldb on public stop. Fix this bug first. cc @jasonmolenda

@JDevlieghere
JDevlieghere requested a review from jasonmolenda July 8, 2026 23:10
@felipepiovezan

Copy link
Copy Markdown
Contributor

My main concern with this is that it can lead to quadratic complexity under certain insertion patterns, and that it is making the L1 cache much more complicated. We probably need to use some better data structures to keep track of overlapping ranges and allow fast invalidation of all ranges mutated by a given write.

A side note about the commenting style: if we were to keep this patch, I wanted to highlight that we are adding a new invariant to the L1 cache ("ranges are non overlapping"), and there are many comments in the PR repeating this and using it to justify algorithmic decisions. IMO we would be better off having a single line in the header file stating that "the L1 consists of non-overlapping segments", and virtually no comments inside the functions themselves.

All that said, I still believe the better way to attack this problem is to keep the L1 cache simple, and just find a faster way to invalidate multiple ranges.

@qiyao

qiyao commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor Author

My main concern with this is that it can lead to quadratic complexity under certain insertion patterns, and that it is making the L1 cache much more complicated. We probably need to use some better data structures to keep track of overlapping ranges and allow fast invalidation of all ranges mutated by a given write.

I thought about it, it was simpler indeed. My intuition tells me that it's fragile to have a cache allowing overlap.

A side note about the commenting style: if we were to keep this patch, I wanted to highlight that we are adding a new invariant to the L1 cache ("ranges are non overlapping"), and there are many comments in the PR repeating this and using it to justify algorithmic decisions. IMO we would be better off having a single line in the header file stating that "the L1 consists of non-overlapping segments", and virtually no comments inside the functions themselves.

I can simplify and re-organize them if we agree on this approach. When I realized that the overlap chunk scenario wasn't considered when the L1 cache was introduced 11 years ago, I wanted to emphasize every step of the fix, and make them clear.

@felipepiovezan felipepiovezan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about it, it was simpler indeed. My intuition tells me that it's fragile to have a cache allowing overlap.

I pointed at the simplicity as a plus, but my real concern is the quadratic behaviour.
If we have N insertions, each of which has a tiny overlap with the one before, LLDB is going to be quite slow processing that. E.g. [1000, 2100), [2000, 3100), [3000, 4100)....

Maybe the numbers here are not big enough in practice, but it does concern me to have this kind of complexity in LLDB.

Comment thread lldb/source/Target/Memory.cpp Outdated
if (pos != m_L1_cache.begin())
--pos;
BlockMap::iterator merge_first = m_L1_cache.end();
BlockMap::iterator merge_end = m_L1_cache.end();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The four variables here: merge_end, merged_end, merge_first, merged_base, are quite difficult to follow, maybe we can try to come up with slightly more distinct names?
Something like merge_start_it and merge_end_it for the two iterators and merge_start_addr and merge_end_addr for the two final addresses.

Comment thread lldb/source/Target/Memory.cpp Outdated
merged_end = std::max(merged_end, chunk_range.GetRangeEnd());
if (merge_first == m_L1_cache.end())
merge_first = pos;
merge_end = std::next(pos);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can initialize both merge_first and merge_end to the original value of pos (after the decrement), and only advance merge_end here.

Then, at the end, you only compare merge_first != merge_pos.

It's a bit less branchy this way,

@qiyao
qiyao force-pushed the fix-l1-cache-overlap-flush branch from 6e6c9bf to 1ab846b Compare July 27, 2026 15:54
@qiyao qiyao changed the title [lldb] Keep L1 memory cache chunks disjoint [lldb] Fix stale L1 memory cache read after memory write Jul 27, 2026
@qiyao

qiyao commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

I re-implemented this PR, to keep L1 cache simple, allow overlap, as @felipepiovezan suggested in the review.
I added an optimization, which is about the cases that new range contains the existing L1 cache entry or existing L1 cache entry contains the new range.

Comment thread lldb/source/Target/Memory.cpp Outdated
// Erase any blocks from the L1 cache that intersect with the flush range
// Erase any blocks from the L1 cache that intersect with the flush range. A
// chunk that intersects cannot start earlier than this, so scan a bounded
// window rather than the whole cache.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  // chunk that intersects cannot start earlier than this, so scan a bounded
  // window rather than the whole cache.

What is "this" here?

Comment thread lldb/source/Target/Memory.cpp Outdated
--pos;
}
while (pos != m_L1_cache.end()) {
addr_t lowest_possible_start = GetLowestPossibleChunkStart(addr);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, it's this.
I think the comment is slightly out of place, but IMO we can remove it: the name of this variable is already saying exactly what happens

@felipepiovezan felipepiovezan left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I'm still trying to understand, isn't the algorithm still quadratic?

This is the kind of pattern I am worried about:

insert(addr: 100, size: 16KB)

and then we do something like a multi memory read of 1000 pointers, so 1000 8-byte addresses, 8 bytes apart each (so something like reading 8 bytes from each of those addresses: 16000, 16016, 16032, 16048, etc...).

Every time we insert one new 8-byte range in the cache, we are going to scan all previously inserted ranges because max size = 16KB. I.e. this is O(n^2)

@felipepiovezan

Copy link
Copy Markdown
Contributor

I wonder if the right tradeoff here is to make invalidation linear -- since we don't do much of it -- but keep insertion cheap.

@felipepiovezan

Copy link
Copy Markdown
Contributor

Although we still need lookup to be fast, and with overlaps that's tricky.... we might need a better data structure for lookups

@qiyao

qiyao commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

@felipepiovezan , thanks for the review, you're right that the pattern you describe is bad, so I'm going to drop the scan window rather than defend it.

To be precise about the bound first: the scan isn't over the whole cache, only over chunks whose start falls in [addr - (M-1), addr + len), where M is the largest chunk length inserted since the last stop. So one insert is O(log n + k) with k <= min(n, M), and n inserts are O(n log n + n * min(n, M)), linear in n once the inserted ranges are spread further apart than M. But your example is exactly the clustered case: 1000 ranges 16 bytes apart span 16KB, which is M, so k grows to n and it does degenerate to quadratic. M also never shrinks when a chunk is erased, so one big expedited chunk keeps the window wide.

The way out is your suggestion in the following comment, and it also answers the lookup question: a lookup miss is not a correctness problem, it just falls through to L2 or the inferior. Only invalidation has to be exhaustive. So:

  • Flush walks the L1 cache and erases every chunk that intersects the range: O(n), one caller (Process::WriteMemory), which then does a packet round trip anyway.
  • AddL1CacheData goes back to a plain insert: O(log n).
  • FindL1CacheEntry goes back to checking only the nearest chunk starting at or below the address: O(log n), identical to what we ship today, so no new data structure is needed.
  • m_L1_max_chunk_byte_size and GetLowestPossibleChunkStart disappear, along with the comments you flagged above.

If we later want lookups to exploit overlapping chunks, that is a separate change and wants a real interval map. What do you think?

@felipepiovezan

Copy link
Copy Markdown
Contributor

But your example is exactly the clustered case: 1000 ranges 16 bytes apart span

The reason I mentioned this is that there a few places in the code where we read a lot of pointers from memory all at once (from strided addresses, using MultiMemRead), so I think the case where we reach quadratic complexity are real.

Only invalidation has to be exhaustive. So:

  • Flush walks the L1 cache and erases every chunk that intersects the range: O(n), one caller (Process::WriteMemory), which then does a packet round trip anyway.
  • AddL1CacheData goes back to a plain insert: O(log n).
  • FindL1CacheEntry goes back to checking only the nearest chunk starting at or below the address: O(log n), identical to what we ship today, so no new data structure is needed.

I think this is a good compromise. If we detect we're missing too many cache hits when we shouldn't, we can design a more elaborate solution

A `memory write` can leave stale bytes in the L1 memory cache, so a later
`memory read` of the address that was just written returns the old value.

The L1 cache (`m_L1_cache`) is a map keyed by each chunk's start address, and
chunks can overlap: a read larger than an L2 cache line
(`target.memory-cache-line-size`, 512 by default) bypasses L2 and is stored
whole in L1, so two large reads can produce two chunks that both cover the same
address.

`Flush()` invalidates the L1 cache on a write. It started at the chunk at or
below the flushed address and walked forward, stopping at the first chunk that
did not intersect. It therefore never inspected a chunk that starts below the
flushed address but is long enough to reach into it, leaving that chunk behind
with the stale byte. A later read fully contained in that chunk is served from
the cache and returns the old value.

Fix `Flush()` to walk the whole L1 cache and erase every chunk that intersects
the flushed range, so a chunk starting below the address is dropped too.
Lookups (`FindL1CacheEntry()`) and inserts (`AddL1CacheData()`) are unaffected:
a lookup that lands on the wrong overlapping chunk simply misses and falls
through to L2 or the inferior, which is not a correctness problem.

Add a unit test covering partial overlaps, containment, disjoint and adjacent
chunks, and a flush that must drop a lower-starting chunk as well as several
overlapping chunks.
@qiyao
qiyao force-pushed the fix-l1-cache-overlap-flush branch from 1ab846b to ebfe58a Compare July 29, 2026 17:20
@qiyao

qiyao commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

@felipepiovezan , I pushed a new commit, which only changes MemoryCache::Flush. The test now is more like a unit tests for L1 cache.

@felipepiovezan felipepiovezan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Please be careful when merging: the PR message is outdated (the commit message seems correct). When you merge, have a look at what GitHub shows as the preview for the final message: will it use the PR description, or the commit message?

One small note about the llvm convention here: while I personally prefer the squash+force push approach, this is not the convention in the LLVM repo. Here, the prescribed approach is to make a change and then "git commit --fixup", so that reviewers can inspect how feedback was addressed. (Github is configured to squash everything upon merging)

@qiyao

qiyao commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

LGTM! Please be careful when merging: the PR message is outdated (the commit message seems correct). When you merge, have a look at what GitHub shows as the preview for the final message: will it use the PR description, or the commit message?

Thanks for reminding me. I'll double check the message is my commit message.

One small note about the llvm convention here: while I personally prefer the squash+force push approach, this is not the convention in the LLVM repo. Here, the prescribed approach is to make a change and then "git commit --fixup", so that reviewers can inspect how feedback was addressed. (Github is configured to squash everything upon merging)

Good to know the "git commit --fixup" tip. I usually add delta commits to address review comments (TIL --fixup), design of this PR was changed after the review each time, so I take the force push approach.

@qiyao
qiyao merged commit 6ddd80a into llvm:main Jul 30, 2026
12 checks passed
@qiyao
qiyao deleted the fix-l1-cache-overlap-flush branch July 30, 2026 09:10
@qiyao

qiyao commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

For the record, GitHub preview message is the PR description, I manually replaced it with the commit message.

jgreenbaum pushed a commit to jgreenbaum/llvm-project that referenced this pull request Aug 3, 2026
A `memory write` can leave stale bytes in the L1 memory cache, so a later
`memory read` of the address that was just written returns the old value.

The L1 cache (`m_L1_cache`) is a map keyed by each chunk's start address, and
chunks can overlap: a read larger than an L2 cache line
(`target.memory-cache-line-size`, 512 by default) bypasses L2 and is stored
whole in L1, so two large reads can produce two chunks that both cover the same
address.

`Flush()` invalidates the L1 cache on a write. It started at the chunk at or
below the flushed address and walked forward, stopping at the first chunk that
did not intersect. It therefore never inspected a chunk that starts below the
flushed address but is long enough to reach into it, leaving that chunk behind
with the stale byte. A later read fully contained in that chunk is served from
the cache and returns the old value.

Fix `Flush()` to walk the whole L1 cache and erase every chunk that intersects
the flushed range, so a chunk starting below the address is dropped too.
Lookups (`FindL1CacheEntry()`) and inserts (`AddL1CacheData()`) are unaffected:
a lookup that lands on the wrong overlapping chunk simply misses and falls
through to L2 or the inferior, which is not a correctness problem.

Add a unit test covering partial overlaps, containment, disjoint and adjacent
chunks, and a flush that must drop a lower-starting chunk as well as several
overlapping chunks.
adrian-prantl pushed a commit to swiftlang/llvm-project that referenced this pull request Aug 14, 2026
A `memory write` can leave stale bytes in the L1 memory cache, so a later
`memory read` of the address that was just written returns the old value.

The L1 cache (`m_L1_cache`) is a map keyed by each chunk's start address, and
chunks can overlap: a read larger than an L2 cache line
(`target.memory-cache-line-size`, 512 by default) bypasses L2 and is stored
whole in L1, so two large reads can produce two chunks that both cover the same
address.

`Flush()` invalidates the L1 cache on a write. It started at the chunk at or
below the flushed address and walked forward, stopping at the first chunk that
did not intersect. It therefore never inspected a chunk that starts below the
flushed address but is long enough to reach into it, leaving that chunk behind
with the stale byte. A later read fully contained in that chunk is served from
the cache and returns the old value.

Fix `Flush()` to walk the whole L1 cache and erase every chunk that intersects
the flushed range, so a chunk starting below the address is dropped too.
Lookups (`FindL1CacheEntry()`) and inserts (`AddL1CacheData()`) are unaffected:
a lookup that lands on the wrong overlapping chunk simply misses and falls
through to L2 or the inferior, which is not a correctness problem.

Add a unit test covering partial overlaps, containment, disjoint and adjacent
chunks, and a flush that must drop a lower-starting chunk as well as several
overlapping chunks.

(cherry picked from commit 6ddd80a)
@qiyao

qiyao commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

/cherry-pick ebfe58a

@llvmbot

llvmbot commented Aug 14, 2026

Copy link
Copy Markdown
Member

Failed to cherry-pick: ebfe58a

https://github.com/llvm/llvm-project/actions/runs/31822965684

Please manually backport the fix and push it to your github fork. Once this is done, please create a pull request

@qiyao

qiyao commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

/cherry-pick 6ddd80a

@llvmbot

llvmbot commented Aug 14, 2026

Copy link
Copy Markdown
Member

/pull-request #216369

dyung pushed a commit to llvmbot/llvm-project that referenced this pull request Aug 18, 2026
A `memory write` can leave stale bytes in the L1 memory cache, so a later
`memory read` of the address that was just written returns the old value.

The L1 cache (`m_L1_cache`) is a map keyed by each chunk's start address, and
chunks can overlap: a read larger than an L2 cache line
(`target.memory-cache-line-size`, 512 by default) bypasses L2 and is stored
whole in L1, so two large reads can produce two chunks that both cover the same
address.

`Flush()` invalidates the L1 cache on a write. It started at the chunk at or
below the flushed address and walked forward, stopping at the first chunk that
did not intersect. It therefore never inspected a chunk that starts below the
flushed address but is long enough to reach into it, leaving that chunk behind
with the stale byte. A later read fully contained in that chunk is served from
the cache and returns the old value.

Fix `Flush()` to walk the whole L1 cache and erase every chunk that intersects
the flushed range, so a chunk starting below the address is dropped too.
Lookups (`FindL1CacheEntry()`) and inserts (`AddL1CacheData()`) are unaffected:
a lookup that lands on the wrong overlapping chunk simply misses and falls
through to L2 or the inferior, which is not a correctness problem.

Add a unit test covering partial overlaps, containment, disjoint and adjacent
chunks, and a flush that must drop a lower-starting chunk as well as several
overlapping chunks.

(cherry picked from commit 6ddd80a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Development

Successfully merging this pull request may close these issues.

3 participants