[clang] [clang][CodeGen] Diagnose deferred definitions with identical mangled names (PR #248930)
via cfe-commits
cfe-commits at lists.llvm.org
Sat Dec 5 07:00:48 PST 2026
https://github.com/MaxBrandtner updated https://github.com/llvm/llvm-project/pull/248930
>From 16f3280d7d4a871038005957066fca37bde5e622 Mon Sep 17 00:00:00 2001
From: Max Brandtner <maximilian.immanuel.brandtner at protonmail.com>
Date: Fri, 4 Dec 2026 20:32:38 +0100
Subject: [PATCH 1/2] [clang-repl] rebase fixup (do not merge)
Signed-off-by: Max Brandtner <maximilian.immanuel.brandtner at protonmail.com>
---
clang/lib/CodeGen/CodeGenModule.cpp | 17 ++
clang/lib/CodeGen/ModuleBuilder.cpp | 1 +
clang/lib/Interpreter/IncrementalAction.cpp | 6 +-
clang/lib/Interpreter/IncrementalAction.h | 1 +
clang/lib/Interpreter/IncrementalParser.cpp | 28 ++--
.../Interpreter/failed-input-drops-ir.cpp | 32 ++++
.../unittests/Interpreter/InterpreterTest.cpp | 151 ++++++++++++++++++
7 files changed, 223 insertions(+), 13 deletions(-)
create mode 100644 clang/test/Interpreter/failed-input-drops-ir.cpp
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 6fe83a03e54c23..23231b8fb3d1fd 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1114,8 +1114,25 @@ void CodeGenModule::checkAliases() {
void CodeGenModule::clear() {
DeferredDeclsToEmit.clear();
+ if (Context.getLangOpts().IncrementalExtensions) {
+ // The next input starts a new module. It can still emit the deferred decls
+ // of the earlier inputs, but not those of the failed unit.
+ DeferredDecls.insert_range(EmittedDeferredDecls);
+ const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
+ auto InFailedUnit = [TU](const Decl *D) {
+ return D->getTranslationUnitDecl() == TU;
+ };
+ SmallVector<StringRef, 8> Dropped;
+ for (const auto &[Name, GD] : DeferredDecls)
+ if (InFailedUnit(GD.getDecl()))
+ Dropped.push_back(Name);
+ for (StringRef Name : Dropped)
+ DeferredDecls.erase(Name);
+ llvm::erase_if(DeferredVTables, InFailedUnit);
+ }
EmittedDeferredDecls.clear();
DeferredAnnotations.clear();
+ GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
if (OpenMPRuntime)
OpenMPRuntime->clear();
}
diff --git a/clang/lib/CodeGen/ModuleBuilder.cpp b/clang/lib/CodeGen/ModuleBuilder.cpp
index 0b00362487d2af..359c9f00b4a781 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -319,6 +319,7 @@ namespace {
if (Diags.hasErrorOccurred()) {
if (Builder)
Builder->clear();
+ DeferredInlineMemberFuncDefs.clear();
M.reset();
}
diff --git a/clang/lib/Interpreter/IncrementalAction.cpp b/clang/lib/Interpreter/IncrementalAction.cpp
index a1f1b51f753ddc..5e393bfda10856 100644
--- a/clang/lib/Interpreter/IncrementalAction.cpp
+++ b/clang/lib/Interpreter/IncrementalAction.cpp
@@ -54,7 +54,8 @@ IncrementalAction::IncrementalAction(CompilerInstance &Instance,
}
return Act;
}()),
- Interp(I), CI(Instance), Consumer(std::move(Consumer)) {}
+ Interp(I), CI(Instance), LLVMCtx(LLVMCtx), Consumer(std::move(Consumer)) {
+}
std::unique_ptr<ASTConsumer>
IncrementalAction::CreateASTConsumer(CompilerInstance & /*CI*/,
@@ -116,8 +117,9 @@ std::unique_ptr<llvm::Module> IncrementalAction::GenModule() {
CachedInCodeGenModule->alias_empty() &&
CachedInCodeGenModule->ifunc_empty())) &&
"CodeGen wrote to a readonly module");
+ // M is null after a failed input: CodeGen dropped that module.
std::unique_ptr<llvm::Module> M(CG->ReleaseModule());
- CG->StartModule("incr_module_" + std::to_string(ID++), M->getContext());
+ CG->StartModule("incr_module_" + std::to_string(ID++), LLVMCtx);
return M;
}
return nullptr;
diff --git a/clang/lib/Interpreter/IncrementalAction.h b/clang/lib/Interpreter/IncrementalAction.h
index a9006f936f5c4a..34b046f6e7e5b0 100644
--- a/clang/lib/Interpreter/IncrementalAction.h
+++ b/clang/lib/Interpreter/IncrementalAction.h
@@ -36,6 +36,7 @@ class IncrementalAction : public WrapperFrontendAction {
bool IsTerminating = false;
Interpreter &Interp;
[[maybe_unused]] CompilerInstance &CI;
+ llvm::LLVMContext &LLVMCtx;
std::unique_ptr<ASTConsumer> Consumer;
/// When CodeGen is created the first llvm::Module gets cached in many places
diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index f5e9873925a8a2..161d68b265467c 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -90,8 +90,25 @@ IncrementalParser::ParseOrWrapTopLevelDecl() {
}
DiagnosticsEngine &Diags = S.getDiagnostics();
+ if (!Diags.hasErrorOccurred()) {
+ // Process synthesized translation unit declarations.
+ for (Decl *D : S.getSynthesizedTopLevelDecls()) {
+ DeclGroupRef DGR(D);
+ Consumer->HandleTopLevelDecl(DGR);
+ }
+
+ LocalInstantiations.perform();
+ GlobalInstantiations.perform();
+ }
+
+ // End the unit as a whole-file compile does. After an error, CodeGen drops
+ // the input's IR and the next input starts a new module. CodeGen can also
+ // report the input's first error here.
+ Consumer->HandleTranslationUnit(C);
+
if (Diags.hasErrorOccurred()) {
CleanUpPTU(C.getTranslationUnitDecl());
+ Act->GenModule();
Diags.Reset(/*soft=*/true);
Diags.getClient()->clear();
@@ -99,17 +116,6 @@ IncrementalParser::ParseOrWrapTopLevelDecl() {
std::error_code());
}
- // Process synthesized translation unit declarations.
- for (Decl *D : S.getSynthesizedTopLevelDecls()) {
- DeclGroupRef DGR(D);
- Consumer->HandleTopLevelDecl(DGR);
- }
-
- LocalInstantiations.perform();
- GlobalInstantiations.perform();
-
- Consumer->HandleTranslationUnit(C);
-
return C.getTranslationUnitDecl();
}
diff --git a/clang/test/Interpreter/failed-input-drops-ir.cpp b/clang/test/Interpreter/failed-input-drops-ir.cpp
new file mode 100644
index 00000000000000..779d6c902feaf2
--- /dev/null
+++ b/clang/test/Interpreter/failed-input-drops-ir.cpp
@@ -0,0 +1,32 @@
+// REQUIRES: host-supports-jit
+// RUN: cat %s | clang-repl 2>&1 | FileCheck %s
+// RUN: cat %s | clang-repl 2>&1 | FileCheck %s --check-prefix=NEG
+
+// A failed input must not leave its IR behind. A definition before the error
+// must not block a later definition, and its initializers must not run.
+
+extern "C" int printf(const char *, ...);
+
+int f() { return 1; } int g() { return no_such_name; }
+// CHECK-DAG: error: use of undeclared identifier 'no_such_name'
+int f() { return 1; }
+// NEG-NOT: error: definition with same mangled name
+printf("f() = %d\n", f());
+// CHECK-DAG: f() = 1
+
+int v = printf("v init\n"); int w = no_such_name;
+printf("stmt\n"); no_such_name;
+int ok = 1;
+// NEG-NOT: {{^}}v init
+// NEG-NOT: {{^}}stmt
+printf("ok = %d\n", ok);
+// CHECK-DAG: ok = 1
+
+// CodeGen reports this error at the end of the unit. The input fails, and the
+// next input works.
+extern "C" int no_target(); extern "C" int ali() __attribute__((alias("no_target")));
+// CHECK-DAG: error: alias must point to a defined variable or function
+printf("after = %d\n", ok + 1);
+// CHECK-DAG: after = 2
+
+%quit
diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp b/clang/unittests/Interpreter/InterpreterTest.cpp
index 9a20e0024919e3..e23f5814c38b9f 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -123,6 +123,157 @@ TEST_F(InterpreterTest, Errors) {
EXPECT_TRUE(!!RecoverErr);
}
+// Collect the diagnostics of an interpreter into a string.
+struct CapturedDiagnostics {
+ std::string Output;
+ llvm::raw_string_ostream OS{Output};
+ DiagnosticOptions Opts;
+ TextDiagnosticPrinter Printer{OS, Opts};
+};
+
+// The error text of ParseAndExecute, or "" on success.
+static std::string ParseAndExecuteError(Interpreter &Interp,
+ llvm::StringRef Code) {
+ return llvm::toString(Interp.ParseAndExecute(Code));
+}
+
+// A failed input drops the IR of the definitions before the error. A later
+// input can define the same names again, and the JIT sees the new definitions.
+TEST_F(InterpreterTest, FailedInputDropsCodeGen) {
+ using ::testing::HasSubstr;
+ using ::testing::Not;
+ CapturedDiagnostics Diags;
+ auto Interp = createInterpreter({}, &Diags.Printer);
+
+ const char *Defs[] = {
+ // A function.
+ "int f() { return 1; }",
+ // A global variable.
+ "int gv = 1;",
+ // An inline function that the input uses.
+ "inline int inl() { return 1; } int useinl() { return inl(); }",
+ // A class with a vtable.
+ "struct V { virtual int k(); }; int V::k() { return 1; }",
+ // A static local.
+ "int sl() { static int s = 1; return s; }",
+ // A string literal.
+ "const char *str = \"s\";",
+ };
+ for (const char *Def : Defs) {
+ std::string Failed = std::string(Def) + " int e = no_such_name;";
+ auto Err = Interp->Parse(Failed).takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err))) << Def;
+ EXPECT_THAT(Diags.Output, HasSubstr("undeclared identifier 'no_such_name'"))
+ << Def;
+ Diags.Output.clear();
+
+ EXPECT_EQ("", ParseAndExecuteError(*Interp, Def));
+ EXPECT_THAT(Diags.Output, Not(HasSubstr("error:"))) << Def;
+ }
+
+ Value V;
+ cantFail(Interp->ParseAndExecute(
+ "f() + gv + useinl() + V().k() + sl() + (str[0] == 's')", &V));
+ EXPECT_EQ(6, V.getInt());
+
+ // A definition after the error never reaches CodeGen.
+ auto Err = Interp->Parse("int e = no_such_name; int after() { return 1; }")
+ .takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+ Diags.Output.clear();
+ EXPECT_EQ("", ParseAndExecuteError(*Interp, "int after() { return 2; }"));
+ EXPECT_THAT(Diags.Output, Not(HasSubstr("error:")));
+}
+
+// The initializers and statements of a failed input must not run later.
+TEST_F(InterpreterTest, FailedInputDoesNotRun) {
+ auto Interp = createInterpreter();
+ cantFail(Interp->ParseAndExecute("void setGlobal(int);"));
+ const int Before = getGlobal();
+
+ auto Err =
+ Interp->Parse("int side = (setGlobal(1), 0); int e = no_such_name;")
+ .takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+ Err = Interp->Parse("setGlobal(2); no_such_name;").takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+
+ cantFail(Interp->ParseAndExecute("int ok = 1;"));
+ EXPECT_EQ(Before, getGlobal());
+}
+
+// A failed input can be the first user of a deferred definition from an
+// earlier input. A later input must still get that definition.
+TEST_F(InterpreterTest, FailedInputKeepsDeferredDecls) {
+ auto Interp = createInterpreter();
+ cantFail(Interp->ParseAndExecute("inline int seven() { return 7; }"));
+
+ auto Err =
+ Interp->Parse("int use = seven(); int e = no_such_name;").takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+
+ Value V;
+ cantFail(Interp->ParseAndExecute("seven()", &V));
+ EXPECT_EQ(7, V.getInt());
+}
+
+// Undo after a failed input removes the last good input. The names of both
+// inputs are then free again.
+TEST_F(InterpreterTest, RedefineAfterUndoPastFailedInput) {
+ using ::testing::HasSubstr;
+ using ::testing::Not;
+ CapturedDiagnostics Diags;
+ auto Interp = createInterpreter({}, &Diags.Printer);
+
+ cantFail(Interp->ParseAndExecute("int u = 1;"));
+ auto Err = Interp->Parse("int u2 = 2; int e = no_such_name;").takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+ Diags.Output.clear();
+ cantFail(Interp->Undo());
+
+ EXPECT_EQ("", ParseAndExecuteError(*Interp, "int u = 3; int u2 = 4;"));
+ EXPECT_THAT(Diags.Output, Not(HasSubstr("error:")));
+ Value V;
+ cantFail(Interp->ParseAndExecute("u + u2", &V));
+ EXPECT_EQ(7, V.getInt());
+}
+
+// An inline definition of a failed input must not stay behind as a deferred
+// decl. A later input has no definition of the name.
+TEST_F(InterpreterTest, FailedInputDropsDeferredDefinitions) {
+ using ::testing::HasSubstr;
+ auto Interp = createInterpreter();
+ auto Err = Interp
+ ->Parse("inline int f() { return 1; }"
+ "int usef() { return f(); } int e = no_such_name;")
+ .takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+
+ // The JIT reports "Symbols not found: [ _Z1fv ]" on stderr.
+ EXPECT_THAT(ParseAndExecuteError(*Interp, "int f(); int r = f();"),
+ HasSubstr("Failed to materialize symbols"));
+}
+
+// CodeGen reports some errors only at the end of the unit. Such an input fails
+// like any other, and the next input works.
+TEST_F(InterpreterTest, ErrorFromCodeGenFailsTheInput) {
+ using ::testing::HasSubstr;
+ CapturedDiagnostics Diags;
+ auto Interp = createInterpreter({}, &Diags.Printer);
+
+ auto Err = Interp
+ ->Parse("extern \"C\" int no_target(); extern \"C\" int ali()"
+ " __attribute__((alias(\"no_target\")));")
+ .takeError();
+ EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+ EXPECT_THAT(Diags.Output,
+ HasSubstr("alias must point to a defined variable or function"));
+
+ Value V;
+ cantFail(Interp->ParseAndExecute("1 + 1", &V));
+ EXPECT_EQ(2, V.getInt());
+}
+
// Here we test whether the user can mix declarations and statements. The
// interpreter should be smart enough to recognize the declarations from the
// statements and wrap the latter into a declaration, producing valid code.
>From d67a086e8cd1149d9290f5211ecfce1447017229 Mon Sep 17 00:00:00 2001
From: Max Brandtner <maximilian.immanuel.brandtner at protonmail.com>
Date: Sun, 29 Nov 2026 03:14:04 +0100
Subject: [PATCH 2/2] [clang][CodeGen] Diagnose deferred definitions with
identical mangled names
In EmitGlobal, definitions can have their code generation deferred
until their first use. If two deferred definitions have an identical
mangled name, which asm labels can produce, only one of them is emitted,
and references to the other silently resolve to it.
Add a diagnostic to detect definitions with identical mangled names.
Unused static definitions sharing a mangled name are now an error.
Depends on: #226285 (for clang-repl execute test)
Fixes: #41179
Signed-off-by: Max Brandtner <maximilian.immanuel.brandtner at protonmail.com>
---
Reproducer:
```c
static int a(void) __asm__("foo");
static int b(void) __asm__("foo");
static int a(void) { return 1; }
static int b(void) { return 2; }
int main(void) { return a() + b(); } // erroneously returns 4
```
---
clang/lib/CodeGen/CodeGenModule.cpp | 24 ++++++++++++++++++-
clang/lib/CodeGen/CodeGenModule.h | 3 +++
.../CodeGen/asm-label-duplicate-definition.c | 22 +++++++++++++++++
.../CodeGenCXX/duplicate-mangled-name.cpp | 4 +---
4 files changed, 49 insertions(+), 4 deletions(-)
create mode 100644 clang/test/CodeGen/asm-label-duplicate-definition.c
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 23231b8fb3d1fd..579eb43ddcf26a 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -5055,6 +5055,29 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
}
}
+ // Diagnose distinct definitions with the same mangled name.
+ StringRef MangledName = getMangledName(GD);
+ auto [It, Inserted] = ClaimedDefinitions.try_emplace(MangledName, GD);
+
+ if (!Inserted &&
+ !getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver23)) {
+ const Decl *PrevD = It->second.getCanonicalDecl().getDecl();
+ const Decl *CurD = GD.getCanonicalDecl().getDecl();
+ const auto *PrevFD = dyn_cast<FunctionDecl>(PrevD);
+ const auto *CurFD = dyn_cast<FunctionDecl>(CurD);
+
+ if (PrevD != CurD && (!PrevFD || !PrevFD->isMultiVersion()) &&
+ (!CurFD || !CurFD->isMultiVersion())) {
+ if (DiagnosedConflictingDefinitions.insert(GD).second) {
+ Diags.Report(Global->getLocation(), diag::err_duplicate_mangled_name)
+ << MangledName;
+ Diags.Report(It->second.getDecl()->getLocation(),
+ diag::note_previous_definition);
+ }
+ return;
+ }
+ }
+
// Defer code generation to first use when possible, e.g. if this is an inline
// function. If the global must always be emitted, do it eagerly if possible
// to benefit from cache locality.
@@ -5073,7 +5096,6 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
CXXGlobalInits.push_back(nullptr);
}
- StringRef MangledName = getMangledName(GD);
if (GetGlobalValue(MangledName) != nullptr) {
// The value has already been used and should therefore be emitted.
addDeferredDeclToEmit(GD);
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index 3f477aa93fcd04..965c08c6ebce55 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -420,6 +420,9 @@ class CodeGenModule : public CodeGenTypeCache {
/// yet.
llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls;
+ /// Mangled definitions seen so far to diagnose duplicates.
+ llvm::DenseMap<StringRef, GlobalDecl> ClaimedDefinitions;
+
llvm::StringSet<llvm::BumpPtrAllocator> DeferredResolversToEmit;
/// This is a list of deferred decls which we have seen that *are* actually
diff --git a/clang/test/CodeGen/asm-label-duplicate-definition.c b/clang/test/CodeGen/asm-label-duplicate-definition.c
new file mode 100644
index 00000000000000..fb5b77233e766f
--- /dev/null
+++ b/clang/test/CodeGen/asm-label-duplicate-definition.c
@@ -0,0 +1,22 @@
+// Check that conflicting asm-label definitions are diagnosed.
+//
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm-only -verify=expected,linux -DFUNC %s
+// RUN: %clang_cc1 -triple x86_64-apple-macosx -emit-llvm-only -verify=expected,darwin -DFUNC %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm-only -verify=expected,linux -DVAR %s
+// RUN: %clang_cc1 -triple x86_64-apple-macosx -emit-llvm-only -verify=expected,darwin -DVAR %s
+
+#ifdef FUNC
+// Deferred (static) functions.
+static void a(void) asm("foo");
+static void b(void) asm("foo");
+static void a(void) {} // expected-note {{previous definition is here}}
+static void b(void) {} // linux-error {{definition with same mangled name 'foo' as another definition}}
+ // darwin-error at -1 {{definition with same mangled name '<U+0001>foo' as another definition}}
+#endif
+
+#ifdef VAR
+// Deferred (static) variables.
+static int x asm("v") = 1; // expected-note {{previous definition is here}}
+static int y asm("v") = 2; // linux-error {{definition with same mangled name 'v' as another definition}}
+ // darwin-error at -1 {{definition with same mangled name '<U+0001>v' as another definition}}
+#endif
diff --git a/clang/test/CodeGenCXX/duplicate-mangled-name.cpp b/clang/test/CodeGenCXX/duplicate-mangled-name.cpp
index 04e6fee506ebd7..656ceb637fabf6 100644
--- a/clang/test/CodeGenCXX/duplicate-mangled-name.cpp
+++ b/clang/test/CodeGenCXX/duplicate-mangled-name.cpp
@@ -26,9 +26,7 @@ struct T {
// We expect no warnings here, as there is only declaration of _ZN2nm3abcE
// global, no definitions.
-extern "C" {
- int _ZN2nm3abcE;
-}
+extern "C" int _ZN2nm3abcE;
namespace nm {
float abc = 2;
More information about the cfe-commits
mailing list