Просмотр исходного кода

Ask Clang to mangle names, don't try to do it ourselves. (#5764)

Fixes mangling for `extern "C"` functions, as well as some other
uncommon cases like multi-version functions.
Richard Smith 10 месяцев назад
Родитель
Сommit
c7886f4336

+ 4 - 0
toolchain/lower/file_context.h

@@ -92,6 +92,10 @@ class FileContext {
   auto context() -> Context& { return *context_; }
   auto llvm_context() -> llvm::LLVMContext& { return context().llvm_context(); }
   auto llvm_module() -> llvm::Module& { return context().llvm_module(); }
+  auto cpp_code_generator() -> clang::CodeGenerator& {
+    CARBON_CHECK(cpp_code_generator_);
+    return *cpp_code_generator_;
+  }
   auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
   auto cpp_ast() -> const clang::ASTUnit* { return sem_ir().cpp_ast(); }
   auto inst_namer() -> const SemIR::InstNamer* { return inst_namer_; }

+ 3 - 8
toolchain/lower/mangler.cpp

@@ -210,14 +210,9 @@ auto Mangler::MangleGlobalVariable(SemIR::InstId pattern_id) -> std::string {
 }
 
 auto Mangler::MangleCppClang(const clang::NamedDecl* decl) -> std::string {
-  CARBON_CHECK(
-      cpp_mangle_context_,
-      "Mangling of a C++ imported declaration without a Clang `MangleContext`");
-
-  RawStringOstream cpp_mangled_name;
-  cpp_mangle_context_->mangleName(decl, cpp_mangled_name);
-
-  return cpp_mangled_name.TakeStr();
+  return file_context_.cpp_code_generator()
+      .GetMangledName(clang::GlobalDecl(decl))
+      .str();
 }
 
 auto Mangler::MangleVTable(const SemIR::Class& class_info) -> std::string {

+ 1 - 14
toolchain/lower/mangler.h

@@ -22,15 +22,7 @@ class Mangler {
  public:
   // Initialize a new Mangler instance for mangling entities within the
   // specified `FileContext`.
-  explicit Mangler(FileContext& file_context)
-      : file_context_(file_context),
-        cpp_mangle_context_(file_context.cpp_ast()
-                                // Clang's createMangleContext is not
-                                // const-correct, but doesn't modify the AST.
-                                ? const_cast<clang::ASTContext&>(
-                                      file_context.cpp_ast()->getASTContext())
-                                      .createMangleContext()
-                                : nullptr) {}
+  explicit Mangler(FileContext& file_context) : file_context_(file_context) {}
 
   // Produce a deterministically unique mangled name for the function specified
   // by `function_id` and `specific_id`.
@@ -79,11 +71,6 @@ class Mangler {
   // TODO: If `file_context_` has an `InstNamer`, we could share its
   // fingerprinter.
   SemIR::InstFingerprinter fingerprinter_;
-
-  // Clang Mangler lazily initialized when necessary. We create it once under
-  // the assumption all declarations we need to mangle can use the same Mangler
-  // (same AST Context).
-  std::unique_ptr<clang::MangleContext> cpp_mangle_context_;
 };
 
 }  // namespace Carbon::Lower

+ 104 - 0
toolchain/lower/testdata/interop/cpp/extern_c.carbon

@@ -0,0 +1,104 @@
+// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+// Exceptions. See /LICENSE for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/none.carbon
+//
+// AUTOUPDATE
+// TIP: To test this file alone, run:
+// TIP:   bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/lower/testdata/interop/cpp/extern_c.carbon
+// TIP: To dump output, run:
+// TIP:   bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/lower/testdata/interop/cpp/extern_c.carbon
+
+// ============================================================================
+// extern "C" function
+// ============================================================================
+
+// --- extern_c_function.h
+
+extern "C" void foo();
+
+// --- import_extern_c_function.carbon
+
+library "[[@TEST_NAME]]";
+
+import Cpp library "extern_c_function.h";
+
+fn MyF() {
+  Cpp.foo();
+}
+
+// ============================================================================
+// extern "C" function with asm label
+// ============================================================================
+
+// --- extern_c_with_asm_label.h
+
+extern "C" void foo() __asm__("bar");
+
+// --- import_extern_c_with_asm_label.carbon
+
+library "[[@TEST_NAME]]";
+
+import Cpp library "extern_c_with_asm_label.h";
+
+fn MyF() {
+  Cpp.foo();
+}
+
+// CHECK:STDOUT: ; ModuleID = 'import_extern_c_function.carbon'
+// CHECK:STDOUT: source_filename = "import_extern_c_function.carbon"
+// CHECK:STDOUT: target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+// CHECK:STDOUT: target triple = "x86_64-unknown-linux-gnu"
+// CHECK:STDOUT:
+// CHECK:STDOUT: define void @_CMyF.Main() !dbg !7 {
+// CHECK:STDOUT: entry:
+// CHECK:STDOUT:   call void @foo(), !dbg !10
+// CHECK:STDOUT:   ret void, !dbg !11
+// CHECK:STDOUT: }
+// CHECK:STDOUT:
+// CHECK:STDOUT: declare void @foo()
+// CHECK:STDOUT:
+// CHECK:STDOUT: !llvm.module.flags = !{!0, !1, !2, !3, !4}
+// CHECK:STDOUT: !llvm.dbg.cu = !{!5}
+// CHECK:STDOUT:
+// CHECK:STDOUT: !0 = !{i32 7, !"Dwarf Version", i32 5}
+// CHECK:STDOUT: !1 = !{i32 2, !"Debug Info Version", i32 3}
+// CHECK:STDOUT: !2 = !{i32 1, !"wchar_size", i32 4}
+// CHECK:STDOUT: !3 = !{i32 8, !"PIC Level", i32 0}
+// CHECK:STDOUT: !4 = !{i32 7, !"PIE Level", i32 2}
+// CHECK:STDOUT: !5 = distinct !DICompileUnit(language: DW_LANG_C, file: !6, producer: "carbon", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
+// CHECK:STDOUT: !6 = !DIFile(filename: "import_extern_c_function.carbon", directory: "")
+// CHECK:STDOUT: !7 = distinct !DISubprogram(name: "MyF", linkageName: "_CMyF.Main", scope: null, file: !6, line: 6, type: !8, spFlags: DISPFlagDefinition, unit: !5)
+// CHECK:STDOUT: !8 = !DISubroutineType(types: !9)
+// CHECK:STDOUT: !9 = !{}
+// CHECK:STDOUT: !10 = !DILocation(line: 7, column: 3, scope: !7)
+// CHECK:STDOUT: !11 = !DILocation(line: 6, column: 1, scope: !7)
+// CHECK:STDOUT: ; ModuleID = 'import_extern_c_with_asm_label.carbon'
+// CHECK:STDOUT: source_filename = "import_extern_c_with_asm_label.carbon"
+// CHECK:STDOUT: target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+// CHECK:STDOUT: target triple = "x86_64-unknown-linux-gnu"
+// CHECK:STDOUT:
+// CHECK:STDOUT: define void @_CMyF.Main() !dbg !7 {
+// CHECK:STDOUT: entry:
+// CHECK:STDOUT:   call void @bar(), !dbg !10
+// CHECK:STDOUT:   ret void, !dbg !11
+// CHECK:STDOUT: }
+// CHECK:STDOUT:
+// CHECK:STDOUT: declare void @bar()
+// CHECK:STDOUT:
+// CHECK:STDOUT: !llvm.module.flags = !{!0, !1, !2, !3, !4}
+// CHECK:STDOUT: !llvm.dbg.cu = !{!5}
+// CHECK:STDOUT:
+// CHECK:STDOUT: !0 = !{i32 7, !"Dwarf Version", i32 5}
+// CHECK:STDOUT: !1 = !{i32 2, !"Debug Info Version", i32 3}
+// CHECK:STDOUT: !2 = !{i32 1, !"wchar_size", i32 4}
+// CHECK:STDOUT: !3 = !{i32 8, !"PIC Level", i32 0}
+// CHECK:STDOUT: !4 = !{i32 7, !"PIE Level", i32 2}
+// CHECK:STDOUT: !5 = distinct !DICompileUnit(language: DW_LANG_C, file: !6, producer: "carbon", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
+// CHECK:STDOUT: !6 = !DIFile(filename: "import_extern_c_with_asm_label.carbon", directory: "")
+// CHECK:STDOUT: !7 = distinct !DISubprogram(name: "MyF", linkageName: "_CMyF.Main", scope: null, file: !6, line: 6, type: !8, spFlags: DISPFlagDefinition, unit: !5)
+// CHECK:STDOUT: !8 = !DISubroutineType(types: !9)
+// CHECK:STDOUT: !9 = !{}
+// CHECK:STDOUT: !10 = !DILocation(line: 7, column: 3, scope: !7)
+// CHECK:STDOUT: !11 = !DILocation(line: 6, column: 1, scope: !7)

+ 68 - 0
toolchain/lower/testdata/interop/cpp/fail_extern_c.carbon

@@ -0,0 +1,68 @@
+// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+// Exceptions. See /LICENSE for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/full.carbon
+//
+// AUTOUPDATE
+// TIP: To test this file alone, run:
+// TIP:   bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/lower/testdata/interop/cpp/fail_extern_c.carbon
+// TIP: To dump output, run:
+// TIP:   bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/lower/testdata/interop/cpp/fail_extern_c.carbon
+
+// These tests were factored out of `extern_c.carbon` because we do not generate
+// LLVM IR if any test contains errors. They should be moved back once they can
+// successfully compile.
+
+// ============================================================================
+// extern "C" variable
+// ============================================================================
+
+// --- extern_c_variable.h
+
+extern "C" int foo;
+
+// --- fail_todo_import_extern_c_variable.carbon
+
+library "[[@TEST_NAME]]";
+
+import Cpp library "extern_c_variable.h";
+
+fn MyF() -> i32 {
+  // CHECK:STDERR: fail_todo_import_extern_c_variable.carbon:[[@LINE+11]]:10: error: semantics TODO: `Unsupported: Declaration type Var` [SemanticsTodo]
+  // CHECK:STDERR:   return Cpp.foo;
+  // CHECK:STDERR:          ^~~~~~~
+  // CHECK:STDERR: fail_todo_import_extern_c_variable.carbon:[[@LINE+8]]:10: note: in `Cpp` name lookup for `foo` [InCppNameLookup]
+  // CHECK:STDERR:   return Cpp.foo;
+  // CHECK:STDERR:          ^~~~~~~
+  // CHECK:STDERR:
+  // CHECK:STDERR: fail_todo_import_extern_c_variable.carbon:[[@LINE+4]]:10: error: member name `foo` not found in `Cpp` [MemberNameNotFoundInInstScope]
+  // CHECK:STDERR:   return Cpp.foo;
+  // CHECK:STDERR:          ^~~~~~~
+  // CHECK:STDERR:
+  return Cpp.foo;
+}
+
+// ============================================================================
+// extern "C" function with C++ special name
+// ============================================================================
+
+// --- extern_c_with_special_name.h
+
+struct X {};
+
+extern "C" X operator+(X, X);
+
+// --- fail_todo_import_extern_c_with_special_name.carbon
+
+library "[[@TEST_NAME]]";
+
+import Cpp library "extern_c_with_special_name.h";
+
+fn MyF(a: Cpp.X, b: Cpp.X) -> Cpp.X {
+  // CHECK:STDERR: fail_todo_import_extern_c_with_special_name.carbon:[[@LINE+4]]:10: error: cannot access member of interface `Core.AddWith(Cpp.X)` in type `Cpp.X` that does not implement that interface [MissingImplInMemberAccess]
+  // CHECK:STDERR:   return a + b;
+  // CHECK:STDERR:          ^~~~~
+  // CHECK:STDERR:
+  return a + b;
+}