mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-05 22:02:55 +01:00
Export Carbon global variables and static vars to C++ (#7298)
Add `ExportVarToCpp`. This checks the `clang_decls` mapping and returns an existing decl if found. Otherwise, it creates a new `VarDecl` and adds it to the `clang_decls` mapping. When lowering, in `FileContext::BuildGlobalVariableDecl`, the `clang_decls` mapping is used to lookup an existing `llvm::GlobalVariable` for the instruction. If found, use that rather than creating a new one to avoid an unwanted second definition in the llvm IR.
This commit is contained in:
@@ -672,6 +672,21 @@ auto FileContext::BuildDISubprogram(const SemIR::Function& function,
|
||||
|
||||
auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
|
||||
-> llvm::Constant* {
|
||||
// When a Carbon variable is exported and used from C++, code
|
||||
// generation for the C++ code may have already created an
|
||||
// llvm::GlobalVariable. If so, return that global rather than
|
||||
// creating a new one.
|
||||
auto clang_decl_id = sem_ir().clang_decls().Lookup(var_storage.pattern_id);
|
||||
if (clang_decl_id.has_value()) {
|
||||
auto* decl = sem_ir().clang_decls().Get(clang_decl_id).key.decl;
|
||||
auto* constant = cpp_code_generator_->GetAddrOfGlobal(
|
||||
CreateGlobalDecl(cast<clang::NamedDecl>(decl)),
|
||||
/*isForDefinition=*/false);
|
||||
if (constant) {
|
||||
return constant;
|
||||
}
|
||||
}
|
||||
|
||||
auto var_name_id =
|
||||
SemIR::GetFirstBindingNameFromPatternId(sem_ir(), var_storage.pattern_id);
|
||||
if (auto cpp_global_var_id =
|
||||
|
||||
Reference in New Issue
Block a user