Skip to content

[LLD][COFF] Prefetch inputs early-on to improve link times - #169224

Merged
aganea merged 6 commits into
llvm:mainfrom
aganea:feat/lld_coff_prefetching
Jan 9, 2026
Merged

aganea merged 6 commits into
llvm:mainfrom
aganea:feat/lld_coff_prefetching

Conversation

@aganea

@aganea aganea commented Nov 23, 2025

Copy link
Copy Markdown
Member

This PR reduces outliers in terms of runtime performance, by asking the OS to prefetch memory-mapped input files in advance, as early as possible. I have implemented the Linux aspect, however I have only tested this on Windows 11 version 24H2, with an active security stack enabled. The machine is a AMD Threadripper PRO 3975WX 32c/64t with 128 GB of RAM and Samsung 990 PRO SSD.

I have used a Unreal Engine-based game to profile the link times. Here's a quick summary of the input data:

                                    Summary
--------------------------------------------------------------------------------
               4,169 Input OBJ files (expanded from all cmd-line inputs)
      26,325,429,114 Size of all consumed OBJ files (non-lazy), in bytes
                   9 PDB type server dependencies
                   0 Precomp OBJ dependencies
         350,516,212 Input debug type records
      18,146,407,324 Size of all input debug type records, in bytes
          15,709,427 Merged TPI records
           4,747,187 Merged IPI records
              56,408 Output PDB strings
          23,410,278 Global symbol records
          45,482,231 Module symbol records
           1,584,608 Public symbol records

In normal conditions - meanning all the pages are already in RAM - this PR has no noticeable effect:

>hyperfine "before\lld-link.exe @Game.exe.rsp" "with_pr\lld-link.exe @Game.exe.rsp"
Benchmark 1: before\lld-link.exe @Game.exe.rsp
  Time (mean ± σ):     29.689 s ±  0.550 s    [User: 259.873 s, System: 37.936 s]
  Range (min … max):   29.026 s … 30.880 s    10 runs

Benchmark 2: with_pr\lld-link.exe @Game.exe.rsp
  Time (mean ± σ):     29.594 s ±  0.342 s    [User: 261.434 s, System: 62.259 s]
  Range (min … max):   29.209 s … 30.171 s    10 runs

Summary
  with_pr\lld-link.exe @Game.exe.rsp ran
    1.00 ± 0.02 times faster than before\lld-link.exe @Game.exe.rsp

However when in production conditions, we're typically working with the Unreal Engine Editor, with exteral DCC tools like Maya, Houdini; we have several instances of Visual Studio open, VSCode with Rust analyzer, etc. All this means that between code change iterations, most of the input OBJs files might have been already evicted from the Windows RAM cache. Consequently, in the following test, I've simulated the worst case condition by evicting all data from RAM with RAMMap64 (ie. RAMMap64.exe -E[wsmt0] with a 5-sec sleep at the end to ensure the System thread actually has time to evict the pages)

>hyperfine -p cleanup.bat "before\lld-link.exe @Game.exe.rsp" "with_pr\lld-link.exe @Game.exe.rsp"
Benchmark 1: before\lld-link.exe @Game.exe.rsp
  Time (mean ± σ):     48.124 s ±  1.770 s    [User: 269.031 s, System: 41.769 s]
  Range (min … max):   46.023 s … 50.388 s    10 runs

Benchmark 2: with_pr\lld-link.exe @Game.exe.rsp
  Time (mean ± σ):     34.192 s ±  0.478 s    [User: 263.620 s, System: 40.991 s]
  Range (min … max):   33.550 s … 34.916 s    10 runs

Summary
  with_pr\lld-link.exe @Game.exe.rsp ran
    1.41 ± 0.06 times faster than before\lld-link.exe @Game.exe.rsp

This is similar to the work done in MachO in #157917

@llvmbot

llvmbot commented Nov 23, 2025 •

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-platform-windows
@llvm/pr-subscribers-lld-coff
@llvm/pr-subscribers-llvm-support

@llvm/pr-subscribers-lld

Author: Alexandre Ganea (aganea)

Changes

This PR reduces outliers in terms of runtime performance, by asking the OS to prefetch memory-mapped input files in advance, as early as possible. I have implemented the Linux aspect, however I have only tested this on Windows 11 version 24H2, with an active security stack enabled. The machine is a AMD Threadripper PRO 3975WX 32c/64t with 128 GB of RAM and Samsung 990 PRO SSD.

I have used a Unreal Engine-based game to profile the link times. Here's a quick summary of the input data:

                                    Summary
--------------------------------------------------------------------------------
               4,169 Input OBJ files (expanded from all cmd-line inputs)
      26,325,429,114 Size of all consumed OBJ files (non-lazy), in bytes
                   9 PDB type server dependencies
                   0 Precomp OBJ dependencies
         350,516,212 Input debug type records
      18,146,407,324 Size of all input debug type records, in bytes
          15,709,427 Merged TPI records
           4,747,187 Merged IPI records
              56,408 Output PDB strings
          23,410,278 Global symbol records
          45,482,231 Module symbol records
           1,584,608 Public symbol records

In normal conditions - meanning all the pages are already in RAM - this PR has no noticeable effect:

&gt;hyperfine "before\lld-link.exe @<!-- -->Game.exe.rsp" "with_pr\lld-link.exe @<!-- -->Game.exe.rsp"
Benchmark 1: before\lld-link.exe @<!-- -->Game.exe.rsp
  Time (mean ± σ):     29.689 s ±  0.550 s    [User: 259.873 s, System: 37.936 s]
  Range (min … max):   29.026 s … 30.880 s    10 runs

Benchmark 2: with_pr\lld-link.exe @<!-- -->Game.exe.rsp
  Time (mean ± σ):     29.594 s ±  0.342 s    [User: 261.434 s, System: 62.259 s]
  Range (min … max):   29.209 s … 30.171 s    10 runs

Summary
  with_pr\lld-link.exe @<!-- -->Game.exe.rsp ran
    1.00 ± 0.02 times faster than before\lld-link.exe @<!-- -->Game.exe.rsp

However when in production conditions, we're typically working with the Unreal Engine Editor, with exteral DCC tools like Maya, Houdini; we have several instances of Visual Studio open, VSCode with Rust analyzer, etc. All this means that between code change iterations, most of the input OBJs files might have been already evicted from the Windows RAM cache. Consequently, in the following test, I've simulated the worst case condition by evicting all data from RAM with RAMMap64 (ie. RAMMap64.exe -E[wsmt0] with a 5-sec sleep at the end to ensure the System thread actually has time to evict the pages)

&gt;hyperfine -p cleanup.bat "before\lld-link.exe @<!-- -->Game.exe.rsp" "with_pr\lld-link.exe @<!-- -->Game.exe.rsp"
Benchmark 1: before\lld-link.exe @<!-- -->Game.exe.rsp
  Time (mean ± σ):     48.124 s ±  1.770 s    [User: 269.031 s, System: 41.769 s]
  Range (min … max):   46.023 s … 50.388 s    10 runs

Benchmark 2: with_pr\lld-link.exe @<!-- -->Game.exe.rsp
  Time (mean ± σ):     34.192 s ±  0.478 s    [User: 263.620 s, System: 40.991 s]
  Range (min … max):   33.550 s … 34.916 s    10 runs

Summary
  with_pr\lld-link.exe @<!-- -->Game.exe.rsp ran
    1.41 ± 0.06 times faster than before\lld-link.exe @<!-- -->Game.exe.rsp

This is similar to the work done in MachO in #157917


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

6 Files Affected:

  • (modified) lld/COFF/Driver.cpp (+7-1)
  • (modified) llvm/include/llvm/Support/FileSystem.h (+2)
  • (modified) llvm/include/llvm/Support/MemoryBuffer.h (+5)
  • (modified) llvm/lib/Support/MemoryBuffer.cpp (+1)
  • (modified) llvm/lib/Support/Unix/Path.inc (+13)
  • (modified) llvm/lib/Support/Windows/Path.inc (+26)
diff --git a/lld/COFF/Driver.cpp b/lld/COFF/Driver.cpp
index 0e528de9c3652..e6e7194a684c1 100644
--- a/lld/COFF/Driver.cpp
+++ b/lld/COFF/Driver.cpp
@@ -164,6 +164,8 @@ static std::future<MBErrPair> createFutureForFile(std::string path) {
                                          /*RequiresNullTerminator=*/false);
     if (!mbOrErr)
       return MBErrPair{nullptr, mbOrErr.getError()};
+    // Prefetch memory pages in the background as we will need them soon enough.
+    (*mbOrErr)->willNeedIfMmap();
     return MBErrPair{std::move(*mbOrErr), std::error_code()};
   });
 }
@@ -337,8 +339,12 @@ void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
         auto retryMb = MemoryBuffer::getFile(*retryPath, /*IsText=*/false,
                                              /*RequiresNullTerminator=*/false);
         ec = retryMb.getError();
-        if (!ec)
+        if (!ec) {
           mb = std::move(*retryMb);
+          // Prefetch memory pages in the background as we will need them soon
+          // enough.
+          mb->willNeedIfMmap();
+        }
       } else {
         // We've already handled this file.
         return;
diff --git a/llvm/include/llvm/Support/FileSystem.h b/llvm/include/llvm/Support/FileSystem.h
index cf2a8104ac813..547d732dc3053 100644
--- a/llvm/include/llvm/Support/FileSystem.h
+++ b/llvm/include/llvm/Support/FileSystem.h
@@ -1310,6 +1310,7 @@ class mapped_file_region {
 
   LLVM_ABI void unmapImpl();
   LLVM_ABI void dontNeedImpl();
+  LLVM_ABI void willNeedImpl();
 
   LLVM_ABI std::error_code init(sys::fs::file_t FD, uint64_t Offset,
                                 mapmode Mode);
@@ -1341,6 +1342,7 @@ class mapped_file_region {
     copyFrom(mapped_file_region());
   }
   void dontNeed() { dontNeedImpl(); }
+  void willNeed() { willNeedImpl(); }
 
   LLVM_ABI size_t size() const;
   LLVM_ABI char *data() const;
diff --git a/llvm/include/llvm/Support/MemoryBuffer.h b/llvm/include/llvm/Support/MemoryBuffer.h
index f092c67265a31..9b0f1f0f7d34e 100644
--- a/llvm/include/llvm/Support/MemoryBuffer.h
+++ b/llvm/include/llvm/Support/MemoryBuffer.h
@@ -83,6 +83,11 @@ class LLVM_ABI MemoryBuffer {
   /// function should not be called on a writable buffer.
   virtual void dontNeedIfMmap() {}
 
+  /// Mark the buffer as to-be-used in a near future. This shall trigger OS
+  /// prefetching from the storage device and into memory, if possible.
+  /// This should be use purely as an read optimization.
+  virtual void willNeedIfMmap() {}
+
   /// Open the specified file as a MemoryBuffer, returning a new MemoryBuffer
   /// if successful, otherwise returning null.
   ///
diff --git a/llvm/lib/Support/MemoryBuffer.cpp b/llvm/lib/Support/MemoryBuffer.cpp
index 23b9f8c5790d2..3ef4cd9086b95 100644
--- a/llvm/lib/Support/MemoryBuffer.cpp
+++ b/llvm/lib/Support/MemoryBuffer.cpp
@@ -243,6 +243,7 @@ class MemoryBufferMMapFile : public MB {
   }
 
   void dontNeedIfMmap() override { MFR.dontNeed(); }
+  void willNeedIfMmap() override { MFR.willNeed(); }
 };
 } // namespace
 
diff --git a/llvm/lib/Support/Unix/Path.inc b/llvm/lib/Support/Unix/Path.inc
index 0d991ead72416..0937adcd1bc18 100644
--- a/llvm/lib/Support/Unix/Path.inc
+++ b/llvm/lib/Support/Unix/Path.inc
@@ -900,6 +900,19 @@ void mapped_file_region::dontNeedImpl() {
 #endif
 }
 
+void mapped_file_region::willNeedImpl() {
+  assert(Mode == mapped_file_region::readonly);
+  if (!Mapping)
+    return;
+#if defined(__MVS__) || defined(_AIX)
+  // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
+#elif defined(POSIX_MADV_WILLNEED)
+  ::posix_madvise(Mapping, Size, POSIX_MADV_WILLNEED);
+#else
+  ::madvise(Mapping, Size, MADV_WILLNEED);
+#endif
+}
+
 int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }
 
 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
diff --git a/llvm/lib/Support/Windows/Path.inc b/llvm/lib/Support/Windows/Path.inc
index be007b7abdb51..8be4105ba6bd8 100644
--- a/llvm/lib/Support/Windows/Path.inc
+++ b/llvm/lib/Support/Windows/Path.inc
@@ -1023,6 +1023,32 @@ void mapped_file_region::unmapImpl() {
 
 void mapped_file_region::dontNeedImpl() {}
 
+void mapped_file_region::willNeedImpl() {
+#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
+  typedef struct _WIN32_MEMORY_RANGE_ENTRY {
+    PVOID VirtualAddress;
+    SIZE_T NumberOfBytes;
+  } WIN32_MEMORY_RANGE_ENTRY, *PWIN32_MEMORY_RANGE_ENTRY;
+#endif
+
+  HMODULE kernelM = llvm::sys::windows::loadSystemModuleSecure(L"kernel32.dll");
+  if (kernelM) {
+    // PrefetchVirtualMemory is only available on Windows 8 and later. Since we
+    // still support compilation on Windows 7, we load the function dynamically.
+    typedef BOOL(WINAPI * PrefetchVirtualMemory_t)(
+        HANDLE hProcess, ULONG_PTR NumberOfEntries,
+        _In_reads_(NumberOfEntries) PWIN32_MEMORY_RANGE_ENTRY VirtualAddresses,
+        ULONG Flags);
+    static const auto pfnPrefetchVirtualMemory =
+        (PrefetchVirtualMemory_t)::GetProcAddress(kernelM,
+                                                  "PrefetchVirtualMemory");
+    if (pfnPrefetchVirtualMemory) {
+      WIN32_MEMORY_RANGE_ENTRY Range{Mapping, Size};
+      pfnPrefetchVirtualMemory(::GetCurrentProcess(), 1, &Range, 0);
+    }
+  }
+}
+
 std::error_code mapped_file_region::sync() const {
   if (!::FlushViewOfFile(Mapping, Size))
     return mapWindowsError(GetLastError());

Comment thread llvm/lib/Support/Windows/Path.inc Outdated
@@ -1023,6 +1023,32 @@ void mapped_file_region::unmapImpl() {

void mapped_file_region::dontNeedImpl() {}

void mapped_file_region::willNeedImpl() {
#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we have many of these cases? I wonder if we should sink this into LLVM with a check for the type definition.

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.

Since we're dlopen'ing and rolling our own function prototype anyway below, maybe we should just define this struct unconditionally (with a name that doesn't clash with the windows header)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

As suggested by @zmodem.

@compnerd No, it seems we don't have many cases like this.

Comment thread llvm/lib/Support/Windows/Path.inc Outdated
} WIN32_MEMORY_RANGE_ENTRY, *PWIN32_MEMORY_RANGE_ENTRY;
#endif

HMODULE kernelM = llvm::sys::windows::loadSystemModuleSecure(L"kernel32.dll");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is where the version is likely more useful. In the case of the minimum deployment version being >7, we should prefer static linking IMO. But, I know that is more challenging and potentially not as valuable to invest in, so more of a passing comment.

@aganea aganea Nov 28, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I agree, I was considering that however right now (you're certainly aware) we're undef'ing _WIN32_WINNT and re-def'ing it with 0x0601 in WindowsSupport.h so we wouldn't take the static linking codepath anyway.

@zmodem zmodem 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.

Those are nice numbers!

I wonder what this does in more low-RAM situations though. Will it increase swapping, or is the OS smart enough to hold back a little on the prefetching then?

We've had reports (https://crbug.com/428641952) that lld is using too much RAM when linking PDBs, and this sounds like it could potentially make that worse.

(Related to that bug, I've been wondering if we could do more of the opposite, and call mapped_file_region::dontNeed() when we're done writing out an object file's code and debug symbols to the final outputs.)

Comment thread llvm/lib/Support/Windows/Path.inc Outdated
@@ -1023,6 +1023,32 @@ void mapped_file_region::unmapImpl() {

void mapped_file_region::dontNeedImpl() {}

void mapped_file_region::willNeedImpl() {
#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)

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.

Since we're dlopen'ing and rolling our own function prototype anyway below, maybe we should just define this struct unconditionally (with a name that doesn't clash with the windows header)?

@aganea

aganea commented Nov 28, 2025 •

Copy link
Copy Markdown
Member Author

I wonder what this does in more low-RAM situations though. Will it increase swapping, or is the OS smart enough to hold back a little on the prefetching then?

The docs are stating that it only brings pages from the storage into physical memory "[prefetch] it is treated as a strong hint by the system and is subject to usual physical memory constraints where it can completely or partially fail under low-memory conditions". The pages aren't even mapped in the working set, this only comes later when the process actually tries to access them, which will create a soft page fault (vs. a hard fault when the page is not in physical memory and has to be brought back from the storage).

We've had reports (https://crbug.com/428641952) that lld is using too much RAM when linking PDBs, and this sounds like it could potentially make that worse.

This is a quite an interesting and challenging problem. However I don't think it would make it worse as stated above; the prefetch hint will simply be ignored. I compared before/after this PR in low memory conditions and surprisingly this PR improves the link times:

Summary
  with_pr\lld-link.exe @Game.exe.rsp ran
    1.10 ± 0.09 times faster than before\lld-link.exe @Game.exe.rsp

I can ask perhaps on that ticket if anyone on Edge could test this PR.

(Related to that bug, I've been wondering if we could do more of the opposite, and call mapped_file_region::dontNeed() when we're done writing out an object file's code and debug symbols to the final outputs.)

Yeah I saw your comment on the ticket. This is quite challenging since in many places in LLD/COFF we're not really copying buffers from the input mmaped buffers, rather taking references to them. Until the PDB has been fully written to the mmap buffer, it is hard to know what to unload. This would require a dependency assessement of the code, to see if such thing is feaseable. But at a first glance it wouldn't be simple. However, we could do that for bitcode modules, when a ThinLTO thread is done with a specific input file. Not sure if that's the case Edge are hitting or not.

Another opportunity for solving the issue raised in the ticket would be to write a memory tracking system in LLVM, and dump the allocated list into a .json file at specific places during the LLD execution. Similar to --time-trace but for memory. That would provide hints as to what type to optimize / free buffers that aren't needed.

@aganea

aganea commented Nov 28, 2025

Copy link
Copy Markdown
Member Author

Also FWIW a summary of the memory usage for the above example: ~13 GB of RAM are allocated by LLD; ~24 GB are memory-mapped inputs; ~3.5 GB are the memory-mapped outputs (PDB and EXE). Overall the working set peaks at about 40.5 GB. For the same thing, link.exe peaks at 57 GB.

@zmodem zmodem 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.

Thank you for the thorough reply! This sounds great to me overall.

Comment thread llvm/lib/Support/Windows/Path.inc Resolved
Comment thread llvm/lib/Support/Windows/Path.inc Outdated
// still support compilation on Windows 7, we load the function dynamically.
typedef BOOL(WINAPI * PrefetchVirtualMemory_t)(
HANDLE hProcess, ULONG_PTR NumberOfEntries,
_In_reads_(NumberOfEntries) MEMORY_RANGE_ENTRY * VirtualAddresses,

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.

ultra nit: * on the VirtualAddresses (i guess clang-format gets confused here, maybe because of the _In_reads_, which we could perhaps drop?)

@aganea aganea Dec 1, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I dropped _In_reads_. For *VirtualAddresses, clang-format puts it back as * VirtualAddresses as above, not sure why.

@zmodem zmodem 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.

Looks great, thanks!

@mstorsjo

mstorsjo commented Dec 2, 2025

Copy link
Copy Markdown
Member

Looks reasonable to me too, FWIW.

@aganea

aganea commented Dec 20, 2025 •

Copy link
Copy Markdown
Member Author

I think I'll gate this behind a flag. In some extreme cases (NonUnity build with Unreal Engine) issuing that many PrefetchVirtualMemory calls is completly freezing the system for a several seconds. I tried batching them since the API supports that, but we currently are opening the files asynchronously. Batching the prefetching requires waiting for all files to be open, which takes several seconds for 16,000+ files (if the file metadata is not in physical memory). In the end, batching + prefetching does not seems to provide a great advantage.

@aganea

aganea commented Dec 20, 2025 •

Copy link
Copy Markdown
Member Author

Added -prefetch-inputs flag and updated release notes. Can you please take another look?

@zmodem zmodem 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.

Apologies for the delayed response, I was out for the holidays.

When you say the system freezes for multiple seconds, does the build still end up faster with this flag, or does the freeze negate the benefit?

It's unfortunate that we can't just enable this by default, but making it available behind a flag sounds good to me, as it will allow people to experiment.

Comment thread lld/COFF/Driver.cpp Resolved
Comment thread lld/docs/ReleaseNotes.rst Resolved
@rnk

rnk commented Jan 8, 2026

Copy link
Copy Markdown
Contributor

I just saw this today, and for a long time I had been thinking that there should be a way to trigger this prefetching.

In practice, when I was actively relinking binaries with LLD, what would happen is that the first link would be slow, and so long as your objects fit in RAM in the FS cache, the next link would be fast, and that was good enough for incremental development. Zach Turner described this behavior as "we don't need to implement incremental linking, the FS cache is our incremental linking strategy". This matches your observation "In normal conditions - meaning all the pages are already in RAM - this PR has no noticeable effect:"

@aganea

aganea commented Jan 9, 2026 •

Copy link
Copy Markdown
Member Author

@hans I addressed your comments.

When you say the system freezes for multiple seconds, does the build still end up faster with this flag, or does the freeze negate the benefit?

I investigated a bit more and this is mainly caused by PrefetchVirtualMemory which waits for the Standby List lock which is also taken by the storage device driver which brings the pages asynchronously into RAM (into the Standby List).

Capture d’écran 2026-01-08 154713

The OS is not frozen per se, it is greatly slowed down while the prefetching occurs (again, only if there are a large number of inputs to handle which do not all fit in RAM). And indeed, prefetching is detrimental to the overall link times when that occurs.

As an example, a Win64 target which takes approx 160 GB of input files (mostly .OBJs):

Before this PR: 432 sec
After this PR:  500 sec

LLD summary:

              20,575 Input OBJ files (expanded from all cmd-line inputs)
     162,743,684,034 Size of all consumed OBJ files (non-lazy), in bytes
                  47 PDB type server dependencies
                   0 Precomp OBJ dependencies
       2,076,402,219 Input debug type records
     122,154,522,140 Size of all input debug type records, in bytes
          14,755,332 Merged TPI records
           4,133,367 Merged IPI records
              47,350 Output PDB strings
         166,232,502 Global symbol records
         109,924,995 Module symbol records
           2,190,897 Public symbol records

This is an extreme case, which is worse than what is suggested in https://crbug.com/428641952. It is a non-jumbo target which we usually don't compile, only occassionaly to validate that we have #included indeed all necessary headers in .CPP files. In jumbo mode it happens often that prior .CPPs included in the jumbo .CPP are implicity using types #included from prior files. So it can take a while until we see dependency issues.

Another target which can almost fit all inputs in RAM does not suffer from prefetching issues:

Before or after this PR: 242 sec

LLD summary:

              17,061 Input OBJ files (expanded from all cmd-line inputs)
     120,979,726,253 Size of all consumed OBJ files (non-lazy), in bytes
                   5 PDB type server dependencies
                   0 Precomp OBJ dependencies
       1,577,138,629 Input debug type records
      91,241,482,224 Size of all input debug type records, in bytes
          11,626,762 Merged TPI records
           3,092,110 Merged IPI records
              38,873 Output PDB strings
         126,437,475 Global symbol records
          69,627,439 Module symbol records
           1,334,901 Public symbol records

The very same target as compiled in production with jumbo files (same build flags):

               3,667 Input OBJ files (expanded from all cmd-line inputs)
      23,001,559,157 Size of all consumed OBJ files (non-lazy), in bytes
                   5 PDB type server dependencies
                   0 Precomp OBJ dependencies
         252,435,120 Input debug type records
      14,894,115,232 Size of all input debug type records, in bytes
          11,601,734 Merged TPI records
           3,039,405 Merged IPI records
              38,998 Output PDB strings
          20,996,737 Global symbol records
          66,433,008 Module symbol records
           1,327,982 Public symbol records

As you can see, the total input files are about an order of magnitude smaller, and so is the link time:

                HOT cache   COLD cache
Before this PR:   17 sec      36 sec
After this PR:    17 sec      21 sec

@aganea
aganea force-pushed the feat/lld_coff_prefetching branch from df1dbde to fe52c01 Compare January 9, 2026 14:33
@aganea
aganea enabled auto-merge (squash) January 9, 2026 14:34
@aganea
aganea merged commit 77b8b33 into llvm:main Jan 9, 2026
R-Goc added a commit to R-Goc/ladybird that referenced this pull request Jan 20, 2026
Since LLVM 22 lld-link has a -prefetch-inputs flag that prefetches the
files on startup. This decreases the number of hard page faults when the
files weren't already in the cache or were evicted for some reason. This
is better when there are less files, so in the case of jumbo builds as
there is less contention on the standby list lock. In extreme cases it
can cause a regression in link time performance, however I didn't
measure any for a relink of LibWeb so this shouldn't be the case for our
project. Said regression should only happen if all objects don't fit
into RAM. For more details see: llvm/llvm-project#169224
R-Goc added a commit to R-Goc/ladybird that referenced this pull request Jan 20, 2026
Since LLVM 22 lld-link has a -prefetch-inputs flag that prefetches the
files on startup. This decreases the number of hard page faults when the
files weren't already in the cache or were evicted for some reason. This
is better when there are less files, so in the case of jumbo builds as
there is less contention on the standby list lock. In extreme cases it
can cause a regression in link time performance, however I didn't
measure any for a relink of LibWeb so this shouldn't be the case for our
project. Said regression should only happen if all objects don't fit
into RAM. For more details see:
llvm/llvm-project#169224
R-Goc added a commit to R-Goc/ladybird that referenced this pull request Jan 20, 2026
Since LLVM 22 lld-link has a -prefetch-inputs flag that prefetches the
files on startup. This decreases the number of hard page faults when the
files weren't already in the cache or were evicted for some reason. This
is better when there are less files, so in the case of jumbo builds as
there is less contention on the standby list lock. In extreme cases it
can cause a regression in link time performance, however I didn't
measure any for a relink of LibWeb so this shouldn't be the case for our
project. Said regression should only happen if all objects don't fit
into RAM. For more details see:
llvm/llvm-project#169224
R-Goc added a commit to R-Goc/ladybird that referenced this pull request Jan 20, 2026
Since LLVM 22 lld-link has a -prefetch-inputs flag that prefetches the
files on startup. This decreases the number of hard page faults when the
files weren't already in the cache or were evicted for some reason. This
is better when there are less files, so in the case of jumbo builds as
there is less contention on the standby list lock. In extreme cases it
can cause a regression in link time performance, however I didn't
measure any for a relink of LibWeb so this shouldn't be the case for our
project. Said regression should only happen if all objects don't fit
into RAM. For more details see:
llvm/llvm-project#169224
@DragonDisciple

Copy link
Copy Markdown
Contributor

Hi @aganea

Our team maintains a downstream fork that's been affected by this commit. I'm not sure of the mechanics yet, but when compiling llvm-min-tblgen on Windows, our MSVC lld linker fails due to the added 'willNeedImpl. function. This function calls another added function, loadSystemModuleSecure. The error we get is just that the symbol can't be resolved within the LLVMSupport library.

lld-link: error: undefined symbol: struct HINSTANCE__* __cdecl llvm::sys::windows::loadSystemModuleSecure(wchar_t const *)
>>> referenced by LLVMSupport.lib(Path.cpp.obj):(public: __cdecl `private: void __cdecl llvm::sys::fs::mapped_file_region::willNeedImpl(void)'::`1'::<lambda_1>::operator()(void) const)

While I dig deeper, I was hoping you may understand and be able to help resolve this. I do know we use a moderately outdated MSVC (clang) compiler.

@aganea

aganea commented Jan 22, 2026 •

Copy link
Copy Markdown
Member Author

Hi @aganea

Our team maintains a downstream fork that's been affected by this commit. I'm not sure of the mechanics yet, but when compiling llvm-min-tblgen on Windows, our MSVC lld linker fails due to the added 'willNeedImpl. function. This function calls another added function, loadSystemModuleSecure. The error we get is just that the symbol can't be resolved within the LLVMSupport library.

lld-link: error: undefined symbol: struct HINSTANCE__* __cdecl llvm::sys::windows::loadSystemModuleSecure(wchar_t const *)
>>> referenced by LLVMSupport.lib(Path.cpp.obj):(public: __cdecl `private: void __cdecl llvm::sys::fs::mapped_file_region::willNeedImpl(void)'::`1'::<lambda_1>::operator()(void) const)

While I dig deeper, I was hoping you may understand and be able to help resolve this. I do know we use a moderately outdated MSVC (clang) compiler.

Hello @DragonDisciple !

This is strange since that API was introduced a while back in 860b1e6. Which version of MSVC / LLD are you using? And which build system, Ninja? Can you check the exact command line passed to LLD when building llvm-min-tblgen and then dump the symbols of the LLVMSupport.lib that is trying to link in? I am indeed seeing that symbol being defined on my end:

C:\git\llvm-project>stage1_msvc\bin\llvm-nm.exe --demangle C:\git\llvm-project\stage1_msvc_debug\lib\LLVMSupport.lib | grep loadSystemModuleSecure
000000d8 r $pdata$?loadSystemModuleSecure@windows@sys@llvm@@YAPEAUHINSTANCE__@@PEB_W@Z
000000b8 r $unwind$?loadSystemModuleSecure@windows@sys@llvm@@YAPEAUHINSTANCE__@@PEB_W@Z
00000d00 T struct HINSTANCE__* __cdecl llvm::sys::windows::loadSystemModuleSecure(wchar_t const *)
000006a0 r struct HINSTANCE__* __cdecl llvm::sys::windows::loadSystemModuleSecure(wchar_t const *)
00000650 r struct HINSTANCE__* __cdecl llvm::sys::windows::loadSystemModuleSecure(wchar_t const *)
00000660 r struct HINSTANCE__* __cdecl llvm::sys::windows::loadSystemModuleSecure(wchar_t const *)

@DragonDisciple

Copy link
Copy Markdown
Contributor

The "digging deeper" will include the linker/symbol information, so I'll get back to you on that as soon as I can. Thanks for the quick response! :)

@Meinersbur

Meinersbur commented Jan 23, 2026 •

Copy link
Copy Markdown
Member

Got the same problem with VS 2022 and VS 2026 (both latest version), using Microsoft's link.exe

LLVMSupport.lib(Path.obj) : error LNK2019: unresolved external symbol "struct HINSTANCE__ * __cdecl llvm::sys::windows::loadSystemModuleSecure(wchar_t const *)" (?loadSystemMo
duleSecure@windows@sys@llvm@@YAPEAUHINSTANCE__@@PEB_W@Z) referenced in function "private: void __cdecl llvm::sys::fs::mapped_file_region::willNeedImpl(void)" (?willNeedImpl@ma
pped_file_region@fs@sys@llvm@@AEAAXXZ) [C:\Users\meinersbur\src\llvm\main\debug_vs18\tools\opt\opt.vcxproj]
C:\Users\meinersbur\src\llvm\main\debug_vs18\Debug\bin\opt.exe : fatal error LNK1120: 1 unresolved externals [C:\Users\meinersbur\src\llvm\main\debug_vs18\tools\opt\opt.vcxpro
j]

Please consider reverting.

This is likely due to HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName) defined in Threading.inc whose inclusion protected by some preprocessor conditional:

#if LLVM_ENABLE_THREADS == 0 ||                                                \
    (!defined(_WIN32) && !defined(HAVE_PTHREAD_H))
...
#else

@aganea

aganea commented Jan 23, 2026

Copy link
Copy Markdown
Member Author

Let me fix that real quick.

@aganea
aganea deleted the feat/lld_coff_prefetching branch January 23, 2026 14:30
@aganea

aganea commented Jan 23, 2026

Copy link
Copy Markdown
Member Author

@DragonDisciple @Meinersbur Can you please apply #177598 see if that fixes the link issues?

aganea added a commit that referenced this pull request Jan 23, 2026
Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
#169224 (comment)
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Jan 23, 2026
…C. (#177598)

Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
llvm/llvm-project#169224 (comment)
@DragonDisciple

Copy link
Copy Markdown
Contributor

Looks like the issue has been fixed with #177598
Root cause is #169224 broke builds that do not build with pthread support?

R-Goc added a commit to R-Goc/ladybird that referenced this pull request Jan 26, 2026
Since LLVM 22 lld-link has a -prefetch-inputs flag that prefetches the
files on startup. This decreases the number of hard page faults when the
files weren't already in the cache or were evicted for some reason. This
is better when there are less files, so in the case of jumbo builds as
there is less contention on the standby list lock. In extreme cases it
can cause a regression in link time performance, however I didn't
measure any for a relink of LibWeb so this shouldn't be the case for our
project. Said regression should only happen if all objects don't fit
into RAM. For more details see:
llvm/llvm-project#169224
HugoSilvaSantos pushed a commit to HugoSilvaSantos/arm-toolchain that referenced this pull request Jan 27, 2026
Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
llvm/llvm-project#169224 (comment)
c-rhodes pushed a commit to llvmbot/llvm-project that referenced this pull request Feb 2, 2026
…7598)

Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
llvm#169224 (comment)

(cherry picked from commit 70ee6e4)
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Feb 2, 2026
…C. (#177598)

Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
llvm/llvm-project#169224 (comment)

(cherry picked from commit 70ee6e4)
gmta pushed a commit to LadybirdBrowser/ladybird that referenced this pull request Feb 2, 2026
Since LLVM 22 lld-link has a -prefetch-inputs flag that prefetches the
files on startup. This decreases the number of hard page faults when the
files weren't already in the cache or were evicted for some reason. This
is better when there are less files, so in the case of jumbo builds as
there is less contention on the standby list lock. In extreme cases it
can cause a regression in link time performance, however I didn't
measure any for a relink of LibWeb so this shouldn't be the case for our
project. Said regression should only happen if all objects don't fit
into RAM. For more details see:
llvm/llvm-project#169224
navaneethshan pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Feb 10, 2026
Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
llvm/llvm-project#169224 (comment)

(cherry picked from commit 70ee6e4)
(cherry picked from commit e4cd2e2)
markrvmurray pushed a commit to markrvmurray/llvm-mc6809 that referenced this pull request Jun 14, 2026
Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
llvm/llvm-project#169224 (comment)
nekoshirro pushed a commit to nekoshirro/Alchemist-LLVM that referenced this pull request Jul 30, 2026
Move Windows-specific function
`llvm::sys::windows::loadSystemModuleSecure` from
`lib/Support/Windows/Threading.inc` into
`lib/Support/Windows/Process.inc`.

This is to fix link problems on Windows, see
llvm/llvm-project#169224 (comment)

(cherry picked from commit 57b3d4a)
Signed-off-by: Hafidz Muzakky <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants