Fix C++ code generation in --share-cpp-ast mode (#7605)

Instead of creating a CodeGenerator per CppDomain, and then crashing in
lowering when we try to consume the same llvm Module multiple times,
create a CodeGenerator for each CppFile within the domain.

For now, we mulitplex all of Clang's ASTConsumer output to all code
generators, which means that any strong external definitions within a
Carbon file (for example, in an inline `Cpp` fragment) will be emitted
to all output files in the same `CppDomain`, resulting in link errors
due to symbol redefinitions. This will be addressed later. But this
should be sufficient for Carbon compilations in which such symbols are
not defined.

We also don't yet attempt to classify which compilations will need C++
code generation, and instead create a clang `CodeGenerator` for every
Carbon file that has C++ imports. For `carbom compile`, only one Carbon
file will need code generation, and yet we still build multiple
`CodeGenerator` objects in general. Fixing this requires more plumbing
from the driver, and this will also be handled in a follow-up.

Assisted-by: Gemini via Antigravity
This commit is contained in:
Richard Smith
2026-08-04 17:59:06 +00:00
committed by GitHub
parent a9cc7bf490
commit 34a2e270f4
32 changed files with 641 additions and 232 deletions
+9 -10
View File
@@ -34,17 +34,16 @@ Context::Context(
llvm::LLVMContext* llvm_context,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs, bool want_debug_info,
const Parse::GetTreeAndSubtreesStore* tree_and_subtrees_getters,
clang::CodeGenerator* clang_code_generator, llvm::StringRef module_name,
clang::CodeGenerator* cpp_code_generator, llvm::StringRef module_name,
int total_ir_count, Lower::OptimizationLevel opt_level,
bool mangle_string_fingerprint, llvm::raw_ostream* vlog_stream)
: llvm_context_(llvm_context),
clang_code_generator_(clang_code_generator),
llvm_module_owner_(
clang_code_generator_
? nullptr
: std::make_unique<llvm::Module>(module_name, *llvm_context)),
cpp_code_generator_(cpp_code_generator),
llvm_module_owner_(cpp_code_generator_ ? nullptr
: std::make_unique<llvm::Module>(
module_name, *llvm_context)),
llvm_module_(llvm_module_owner_ ? llvm_module_owner_.get()
: clang_code_generator_->GetModule()),
: cpp_code_generator_->GetModule()),
file_system_(std::move(fs)),
opt_level_(opt_level),
di_builder_(*llvm_module_),
@@ -95,9 +94,9 @@ auto Context::Finalize() && -> std::unique_ptr<llvm::Module> {
"Debug Info Version", llvm::DEBUG_METADATA_VERSION);
}
return clang_code_generator_ ? std::unique_ptr<llvm::Module>(
clang_code_generator_->ReleaseModule())
: std::move(llvm_module_owner_);
return cpp_code_generator_ ? std::unique_ptr<llvm::Module>(
cpp_code_generator_->ReleaseModule())
: std::move(llvm_module_owner_);
}
auto Context::BuildDICompileUnit(llvm::StringRef module_name,