[clang] [clang] Make `PCHContainerReader::ExtractPCH()` return a buffer (PR #244697)
Jan Svoboda via cfe-commits
cfe-commits at lists.llvm.org
Thu Dec 3 15:56:07 PST 2026
https://github.com/jansvoboda11 updated https://github.com/llvm/llvm-project/pull/244697
>From 6ad93f74dbf1be28fcc84abfd1e64b3c2e571824 Mon Sep 17 00:00:00 2001
From: Jan Svoboda <jan_svoboda at apple.com>
Date: Fri, 20 Nov 2026 11:18:41 -0800
Subject: [PATCH 1/2] [clang] Make `PCHContainerReader::ExtractPCH()` return a
buffer
`ExtractPCH()` used to return a view into the buffer holding the PCM,
leaving it up to the callers to keep that buffer alive. This patch changes
it to take the PCM buffer by-value and return the sub-buffer holding just
the AST file by-value as well. This gives the readers more room to decide
how the AST file is exposed, e.g. to make a copy when needed. No
functional change intended.
The callers are updated as follows:
* The importing compiler instance, the module manager and the global
module index builder extract the AST file once, up front. The
`SubMemoryBuffer` helper moves to the object file reader, the only one
that needs it.
* `ASTReader::ReadASTCore()` and `ModuleManager::addModule()` now rely on
the buffer already being extracted instead of extracting it again. This
relies on the in-memory module cache only holding extracted buffers,
which is why `ASTUnit::LoadFromASTFile()` extracts the AST file read from
stdin before adding it. As a side effect, `ModuleFile::SizeInBits` (used
only for the module size statistics) is now the size of the AST file
rather than of the whole container.
* `ASTReader::getOriginalSourceFile()` and the disk-reading path of
`ASTReader::readASTFileControlBlock()` extract the AST file they read.
The buffer `readASTFileControlBlock()` finds in the in-memory module
cache is used as-is.
---
.../ObjectFilePCHContainerReader.h | 5 ++-
.../Serialization/PCHContainerOperations.h | 14 ++++---
clang/lib/Frontend/ASTUnit.cpp | 5 ++-
clang/lib/Frontend/CompilerInstance.cpp | 26 +------------
clang/lib/Serialization/ASTReader.cpp | 10 +++--
clang/lib/Serialization/GlobalModuleIndex.cpp | 6 ++-
clang/lib/Serialization/ModuleManager.cpp | 5 ++-
.../ObjectFilePCHContainerReader.cpp | 38 ++++++++++++++++++-
.../Serialization/PCHContainerOperations.cpp | 7 ++--
9 files changed, 69 insertions(+), 47 deletions(-)
diff --git a/clang/include/clang/Serialization/ObjectFilePCHContainerReader.h b/clang/include/clang/Serialization/ObjectFilePCHContainerReader.h
index 06778d25d7e523..916d81aa6d2aba 100644
--- a/clang/include/clang/Serialization/ObjectFilePCHContainerReader.h
+++ b/clang/include/clang/Serialization/ObjectFilePCHContainerReader.h
@@ -17,8 +17,9 @@ namespace clang {
class ObjectFilePCHContainerReader : public PCHContainerReader {
ArrayRef<StringRef> getFormats() const override;
- /// Returns the serialized AST inside the PCH container Buffer.
- StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const override;
+ /// Returns a buffer with the serialized AST inside the PCH container Buffer.
+ std::unique_ptr<llvm::MemoryBuffer>
+ ExtractPCH(std::unique_ptr<llvm::MemoryBuffer> Buffer) const override;
};
} // namespace clang
diff --git a/clang/include/clang/Serialization/PCHContainerOperations.h b/clang/include/clang/Serialization/PCHContainerOperations.h
index c9a7e334ce6eb3..3887ccc2d54e6a 100644
--- a/clang/include/clang/Serialization/PCHContainerOperations.h
+++ b/clang/include/clang/Serialization/PCHContainerOperations.h
@@ -12,12 +12,12 @@
#include "clang/Basic/Module.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
-#include "llvm/Support/MemoryBufferRef.h"
#include <memory>
namespace llvm {
+class MemoryBuffer;
class raw_pwrite_stream;
-}
+} // namespace llvm
namespace clang {
@@ -58,8 +58,9 @@ class PCHContainerReader {
/// Equivalent to the format passed to -fmodule-format=
virtual llvm::ArrayRef<llvm::StringRef> getFormats() const = 0;
- /// Returns the serialized AST inside the PCH container Buffer.
- virtual llvm::StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const = 0;
+ /// Returns a buffer with the serialized AST inside the PCH container Buffer.
+ virtual std::unique_ptr<llvm::MemoryBuffer>
+ ExtractPCH(std::unique_ptr<llvm::MemoryBuffer> Buffer) const = 0;
};
/// Implements write operations for a raw pass-through PCH container.
@@ -79,8 +80,9 @@ class RawPCHContainerWriter : public PCHContainerWriter {
/// Implements read operations for a raw pass-through PCH container.
class RawPCHContainerReader : public PCHContainerReader {
llvm::ArrayRef<llvm::StringRef> getFormats() const override;
- /// Simply returns the buffer contained in Buffer.
- llvm::StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const override;
+ /// Simply returns Buffer, since the container is the serialized AST itself.
+ std::unique_ptr<llvm::MemoryBuffer>
+ ExtractPCH(std::unique_ptr<llvm::MemoryBuffer> Buffer) const override;
};
/// A registry of PCHContainerWriter and -Reader objects for different formats.
diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp
index 738fe99cef46bb..79fb857308189b 100644
--- a/clang/lib/Frontend/ASTUnit.cpp
+++ b/clang/lib/Frontend/ASTUnit.cpp
@@ -824,8 +824,9 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
if (Filename == "-")
if (auto FE = llvm::expectedToOptional(TmpFileMgr.getSTDIN()))
if (auto BufRef = TmpFileMgr.getBufferForFile(*FE)) {
- auto Buf = llvm::MemoryBuffer::getMemBufferCopy(
- (*BufRef)->getBuffer(), (*BufRef)->getBufferIdentifier());
+ auto Buf =
+ PCHContainerRdr.ExtractPCH(llvm::MemoryBuffer::getMemBufferCopy(
+ (*BufRef)->getBuffer(), (*BufRef)->getBufferIdentifier()));
off_t BufSize = Buf->getBufferSize();
AST->ModCache->getInMemoryModuleCache().addBuiltPCM(
"-", std::move(Buf), BufSize, /*ModTime=*/0);
diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp
index 0b42e03d1320ef..8813dd1cd2fa97 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1533,28 +1533,6 @@ static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
return false;
}
-namespace {
-/// A buffer exposing a sub-range of an owned buffer.
-class SubMemoryBuffer : public llvm::MemoryBuffer {
- std::unique_ptr<llvm::MemoryBuffer> Underlying;
-
-public:
- SubMemoryBuffer(std::unique_ptr<llvm::MemoryBuffer> Underlying,
- StringRef Range)
- : Underlying(std::move(Underlying)) {
- init(Range.begin(), Range.end(), /*RequiresNullTerminator=*/false);
- }
-
- StringRef getBufferIdentifier() const override {
- return Underlying->getBufferIdentifier();
- }
-
- BufferKind getBufferKind() const override {
- return Underlying->getBufferKind();
- }
-};
-} // namespace
-
/// Compile a module in a separate compiler instance.
/// Returns true on success, false on failure.
static bool compileModuleImpl(CompilerInstance &ImportingInstance,
@@ -1604,10 +1582,8 @@ static bool compileModuleImpl(CompilerInstance &ImportingInstance,
// Readers use the module cache's view of the written PCM. Extracting the AST
// file (which may be wrapped in an object file) isn't strictly necessary, but
// it's more efficient to do so now rather than repeatedly in the readers.
- const PCHContainerReader &Rdr = ImportingInstance.getPCHContainerReader();
- StringRef ExtractedBuffer = Rdr.ExtractPCH(*Buffer);
Buffer =
- std::make_unique<SubMemoryBuffer>(std::move(Buffer), ExtractedBuffer);
+ ImportingInstance.getPCHContainerReader().ExtractPCH(std::move(Buffer));
ImportingInstance.getModuleCache().getInMemoryModuleCache().addBuiltPCM(
ModuleFileName, std::move(Buffer), Size, ModTime);
diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp
index db04c06f3cee73..6c26c3177eac0b 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -5443,7 +5443,7 @@ ASTReader::ASTReadResult ASTReader::ReadASTCore(
});
ModuleFile &F = *M;
BitstreamCursor &Stream = F.Stream;
- Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
+ Stream = BitstreamCursor(F.Buffer->getBuffer());
F.SizeInBits = F.Buffer->getBufferSize() * 8;
// Sniff for the signature.
@@ -5977,7 +5977,9 @@ std::string ASTReader::getOriginalSourceFile(
}
// Initialize the stream
- BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
+ std::unique_ptr<llvm::MemoryBuffer> ASTBuffer =
+ PCHContainerRdr.ExtractPCH(std::move(*Buffer));
+ BitstreamCursor Stream(ASTBuffer->getBuffer());
// Sniff for the signature.
if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
@@ -6128,12 +6130,12 @@ bool ASTReader::readASTFileControlBlock(
/*IsText=*/false);
if (!BufferOrErr)
return true;
- OwnedBuffer = std::move(*BufferOrErr);
+ OwnedBuffer = PCHContainerRdr.ExtractPCH(std::move(*BufferOrErr));
Buffer = OwnedBuffer.get();
}
// Initialize the stream
- StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
+ StringRef Bytes = Buffer->getBuffer();
BitstreamCursor Stream(Bytes);
// Sniff for the signature.
diff --git a/clang/lib/Serialization/GlobalModuleIndex.cpp b/clang/lib/Serialization/GlobalModuleIndex.cpp
index 7a154898e4b25b..f4b2c49cf2b39b 100644
--- a/clang/lib/Serialization/GlobalModuleIndex.cpp
+++ b/clang/lib/Serialization/GlobalModuleIndex.cpp
@@ -527,8 +527,12 @@ llvm::Error GlobalModuleIndexBuilder::loadModuleFile(FileEntryRef File) {
return llvm::createStringError(Buffer.getError(),
"failed getting buffer for module file");
+ // Extract the AST file from the container.
+ std::unique_ptr<llvm::MemoryBuffer> ASTBuffer =
+ PCHContainerRdr.ExtractPCH(std::move(*Buffer));
+
// Initialize the input stream
- llvm::BitstreamCursor InStream(PCHContainerRdr.ExtractPCH(**Buffer));
+ llvm::BitstreamCursor InStream(ASTBuffer->getBuffer());
// Sniff for the signature.
for (unsigned char C : {'C', 'P', 'C', 'H'})
diff --git a/clang/lib/Serialization/ModuleManager.cpp b/clang/lib/Serialization/ModuleManager.cpp
index cbb9de32f2b15b..1cead306a56583 100644
--- a/clang/lib/Serialization/ModuleManager.cpp
+++ b/clang/lib/Serialization/ModuleManager.cpp
@@ -229,7 +229,8 @@ AddModuleResult ModuleManager::addModule(
return Result;
}
- NewFileBuffer = std::move(*Buf);
+ // Extract the AST file now, so that the readers don't have to.
+ NewFileBuffer = PCHContainerRdr.ExtractPCH(std::move(*Buf));
ModuleBuffer = NewFileBuffer.get();
}
@@ -243,7 +244,7 @@ AddModuleResult ModuleManager::addModule(
NewModule->ModTime = ModTime;
NewModule->Buffer = ModuleBuffer;
// Initialize the stream.
- NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
+ NewModule->Data = NewModule->Buffer->getBuffer();
// Check file properties.
if (isModuleFileOutOfDate(Size, ModTime, ExpectedSize, ExpectedModTime,
diff --git a/clang/lib/Serialization/ObjectFilePCHContainerReader.cpp b/clang/lib/Serialization/ObjectFilePCHContainerReader.cpp
index 59fc46960dc609..552e5b431b5486 100644
--- a/clang/lib/Serialization/ObjectFilePCHContainerReader.cpp
+++ b/clang/lib/Serialization/ObjectFilePCHContainerReader.cpp
@@ -9,16 +9,39 @@
#include "clang/Serialization/ObjectFilePCHContainerReader.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ObjectFile.h"
+#include "llvm/Support/MemoryBuffer.h"
using namespace clang;
+namespace {
+/// A buffer exposing a sub-range of an owned buffer.
+class SubMemoryBuffer : public llvm::MemoryBuffer {
+ std::unique_ptr<llvm::MemoryBuffer> Underlying;
+
+public:
+ SubMemoryBuffer(std::unique_ptr<llvm::MemoryBuffer> Underlying,
+ StringRef Range)
+ : Underlying(std::move(Underlying)) {
+ init(Range.begin(), Range.end(), /*RequiresNullTerminator=*/false);
+ }
+
+ StringRef getBufferIdentifier() const override {
+ return Underlying->getBufferIdentifier();
+ }
+
+ BufferKind getBufferKind() const override {
+ return Underlying->getBufferKind();
+ }
+};
+} // namespace
+
ArrayRef<StringRef> ObjectFilePCHContainerReader::getFormats() const {
static StringRef Formats[] = {"obj", "raw"};
return Formats;
}
-StringRef
-ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
+/// Returns the serialized AST inside the PCH container Buffer.
+static StringRef extractPCH(llvm::MemoryBufferRef Buffer) {
StringRef PCH;
auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
if (OFOrErr) {
@@ -54,3 +77,14 @@ ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
});
return PCH;
}
+
+std::unique_ptr<llvm::MemoryBuffer> ObjectFilePCHContainerReader::ExtractPCH(
+ std::unique_ptr<llvm::MemoryBuffer> Buffer) const {
+ StringRef Extracted = extractPCH(*Buffer);
+ // As a fallback, the buffer is treated as a raw AST (see extractPCH()). Use
+ // it as-is, there's no container to unwrap.
+ if (Extracted.begin() == Buffer->getBufferStart() &&
+ Extracted.end() == Buffer->getBufferEnd())
+ return Buffer;
+ return std::make_unique<SubMemoryBuffer>(std::move(Buffer), Extracted);
+}
diff --git a/clang/lib/Serialization/PCHContainerOperations.cpp b/clang/lib/Serialization/PCHContainerOperations.cpp
index 4aedb7debcff28..496278dce02622 100644
--- a/clang/lib/Serialization/PCHContainerOperations.cpp
+++ b/clang/lib/Serialization/PCHContainerOperations.cpp
@@ -12,6 +12,7 @@
#include "clang/Serialization/PCHContainerOperations.h"
#include "clang/AST/ASTConsumer.h"
+#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include <utility>
@@ -60,9 +61,9 @@ ArrayRef<llvm::StringRef> RawPCHContainerReader::getFormats() const {
return ArrayRef(Raw);
}
-StringRef
-RawPCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
- return Buffer.getBuffer();
+std::unique_ptr<llvm::MemoryBuffer> RawPCHContainerReader::ExtractPCH(
+ std::unique_ptr<llvm::MemoryBuffer> Buffer) const {
+ return Buffer;
}
PCHContainerOperations::PCHContainerOperations() {
>From e00ca07f6adb4f35637e77610e07aa156d4267ea Mon Sep 17 00:00:00 2001
From: Jan Svoboda <jan_svoboda at apple.com>
Date: Thu, 3 Dec 2026 15:52:51 -0800
Subject: [PATCH 2/2] [clang][serialization] Remove unused
`ASTReader::PCHContainerRdr`
Since the AST file is now extracted before it reaches the reader, the
member is no longer used. The constructor parameter is still forwarded to
the module manager.
---
clang/include/clang/Serialization/ASTReader.h | 1 -
clang/lib/Serialization/ASTReader.cpp | 5 ++---
2 files changed, 2 insertions(+), 4 deletions(-)
diff --git a/clang/include/clang/Serialization/ASTReader.h b/clang/include/clang/Serialization/ASTReader.h
index 275383d40cf808..83df0ab880963a 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -488,7 +488,6 @@ class ASTReader : public ExternalPreprocessorSource,
SourceManager &SourceMgr;
FileManager &FileMgr;
- const PCHContainerReader &PCHContainerRdr;
DiagnosticsEngine &Diags;
// Sema has duplicate logic, but SemaObj can sometimes be null so ASTReader
// has its own version.
diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp
index 6c26c3177eac0b..4407a2237c5b6c 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -11584,9 +11584,8 @@ ASTReader::ASTReader(Preprocessor &PP, ModuleCache &ModCache,
? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
: cast<ASTReaderListener>(new PCHValidator(PP, *this))),
SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
- PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
- StackHandler(Diags), PP(PP), ContextObj(Context),
- CodeGenOpts(CodeGenOpts),
+ Diags(PP.getDiagnostics()), StackHandler(Diags), PP(PP),
+ ContextObj(Context), CodeGenOpts(CodeGenOpts),
ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
PP.getHeaderSearchInfo()),
DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
More information about the cfe-commits
mailing list