[clang] [CodeGen] Add CodeGenModule::forgetDecl to discard cached mangled-name state (PR #234493)

via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 24 00:38:16 PST 2026


https://github.com/SahilPatidar updated https://github.com/llvm/llvm-project/pull/234493

>From 119dbe56f5cec568229a48880224e0da2066c49c Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Wed, 21 Oct 2026 14:22:00 +0530
Subject: [PATCH 1/4] [CodeGen] Add CodeGenModule::forgetDecl to discard cached
 mangled-name state

Adds CodeGenModule::forgetDecl(GlobalDecl GD), exposed through CodeGenerator/ModuleBuilder, to clear cached entries in DeferredDecls and Manglings for a declaration.

This is useful for clang-repl, where a failed partial translation unit (PTU) may be rolled back and a new definition emitted with the same mangled name. Without clearing the old state, CodeGen may reuse stale entries from the discarded PTU.

This is also related to #223305 (module contamination after a failed template instantiation), where CodeGen holds onto state from a discarded PTU.
---
 clang/include/clang/CodeGen/ModuleBuilder.h | 5 +++++
 clang/lib/CodeGen/CodeGenModule.cpp         | 6 ++++++
 clang/lib/CodeGen/CodeGenModule.h           | 2 ++
 clang/lib/CodeGen/ModuleBuilder.cpp         | 6 ++++++
 4 files changed, 19 insertions(+)

diff --git a/clang/include/clang/CodeGen/ModuleBuilder.h b/clang/include/clang/CodeGen/ModuleBuilder.h
index 99e3bdf013a8e8..672f97bbae6bdb 100644
--- a/clang/include/clang/CodeGen/ModuleBuilder.h
+++ b/clang/include/clang/CodeGen/ModuleBuilder.h
@@ -113,6 +113,11 @@ class CodeGenerator : public ASTConsumer {
   /// Create a new \c llvm::Module after calling HandleTranslationUnit. This
   /// enable codegen in interactive processing environments.
   llvm::Module* StartModule(llvm::StringRef ModuleName, llvm::LLVMContext &C);
+
+  /// Clear any CodeGen state associated with \p GD’s mangled name so that a
+  /// new declaration using the same name is treated as if CodeGen has
+  /// never seen it before.
+  void forgetDecl(GlobalDecl GD);
 };
 
 /// CreateLLVMCodeGen - Create a CodeGenerator instance.
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index f0ea493e172229..c8869ef0c1f6e5 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -8617,6 +8617,12 @@ bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
   return true;
 }
 
+void CodeGenModule::forgetDecl(GlobalDecl GD) {
+  StringRef MangledName = getMangledName(GD);
+  DeferredDecls.erase(MangledName);
+  Manglings.erase(MangledName);
+}
+
 /// Emits metadata nodes associating all the global values in the
 /// current module with the Decls they came from.  This is useful for
 /// projects using IR gen as a subroutine.
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index c6b13f58817843..da301a2d0ace0e 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -868,6 +868,8 @@ class CodeGenModule : public CodeGenTypeCache {
   bool lookupRepresentativeDecl(StringRef MangledName,
                                 GlobalDecl &Result) const;
 
+  void forgetDecl(GlobalDecl GD);
+
   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
     return AtomicSetterHelperFnMap[Ty];
   }
diff --git a/clang/lib/CodeGen/ModuleBuilder.cpp b/clang/lib/CodeGen/ModuleBuilder.cpp
index 0b00362487d2af..4be2aac9d6e8e2 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -155,6 +155,8 @@ namespace {
       return M.get();
     }
 
+    void forgetDecl(GlobalDecl GD) { Builder->forgetDecl(GD); }
+
     void Initialize(ASTContext &Context) override {
       Ctx = &Context;
 
@@ -394,6 +396,10 @@ llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
   return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
 }
 
+void CodeGenerator::forgetDecl(GlobalDecl GD) {
+  static_cast<CodeGeneratorImpl *>(this)->forgetDecl(GD);
+}
+
 std::unique_ptr<CodeGenerator>
 clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,

>From 8df3ef574f942a99108fcffed3f83d44b223e734 Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Sat, 24 Oct 2026 15:04:40 +0530
Subject: [PATCH 2/4] Apply CodeGenModule::forgetDecl and add test

---
 clang/lib/Interpreter/IncrementalParser.cpp   | 39 ++++++++++++++++---
 .../Interpreter/codegen-stale-entries.cpp     | 25 ++++++++++++
 2 files changed, 59 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/Interpreter/codegen-stale-entries.cpp

diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index ebd949b3d385d4..be31db9da5b2fe 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/DeclContextInternals.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/DeclVisitor.h"
+#include "clang/CodeGen/ModuleBuilder.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Interpreter/PartialTranslationUnit.h"
 #include "clang/Parse/Parser.h"
@@ -199,6 +200,7 @@ void IncrementalParser::withdrawMostRecentTU(
 class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   Sema &S;
   TranslationUnitDecl *DiscardedTU;
+  CodeGenerator *CodeGen;
 
   /// The newest declaration of whatever D redeclares that still lives outside
   /// the DiscardedTU, or null if DiscardedTU introduced the name.
@@ -260,9 +262,17 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
     }
   }
 
+  void forgetMangledNames(std::initializer_list<GlobalDecl> GDs) {
+    if (!CodeGen)
+      return;
+    for (GlobalDecl GD : GDs)
+      CodeGen->forgetDecl(GD);
+  }
+
 public:
-  ASTDeclUnmerger(Sema &S, TranslationUnitDecl *DiscardedTU)
-      : S(S), DiscardedTU(DiscardedTU) {}
+  ASTDeclUnmerger(Sema &S, TranslationUnitDecl *DiscardedTU,
+                  CodeGenerator *CodeGen = nullptr)
+      : S(S), DiscardedTU(DiscardedTU), CodeGen(CodeGen) {}
 
   void VisitDecl(Decl *D) {
     if (auto *DC = dyn_cast<DeclContext>(D))
@@ -301,11 +311,29 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
     return Prev;
   }
 
-  void VisitFunctionDecl(FunctionDecl *D) { VisitRedeclarable(D); }
+  void VisitFunctionDecl(FunctionDecl *D) {
+    forgetMangledNames({GlobalDecl(D)});
+    VisitRedeclarable(D);
+  }
   void VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { VisitRedeclarable(D); }
   void VisitTypedefNameDecl(TypedefNameDecl *D) { VisitRedeclarable(D); }
   void VisitUsingShadowDecl(UsingShadowDecl *D) { VisitRedeclarable(D); }
-  void VisitVarDecl(VarDecl *D) { VisitRedeclarable(D); }
+  void VisitVarDecl(VarDecl *D) {
+    forgetMangledNames({GlobalDecl(D)});
+    VisitRedeclarable(D);
+  }
+
+  void VisitCXXConstructorDecl(CXXConstructorDecl *D) {
+    forgetMangledNames({GlobalDecl(D, Ctor_Complete), GlobalDecl(D, Ctor_Base),
+                        GlobalDecl(D, Ctor_Comdat)});
+    VisitRedeclarable(D);
+  }
+  void VisitCXXDestructorDecl(CXXDestructorDecl *D) {
+    forgetMangledNames({GlobalDecl(D, Dtor_Deleting),
+                        GlobalDecl(D, Dtor_Complete), GlobalDecl(D, Dtor_Base),
+                        GlobalDecl(D, Dtor_Comdat)});
+    VisitRedeclarable(D);
+  }
 
   void VisitTagDecl(TagDecl *D) {
     // Some members of a definition are visible outside of it: the enumerators
@@ -345,7 +373,8 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
 };
 
 void IncrementalParser::CleanUpPTU(TranslationUnitDecl *MostRecentTU) {
-  ASTDeclUnmerger(S, MostRecentTU).Visit(MostRecentTU);
+  ASTDeclUnmerger(S, MostRecentTU, Act ? Act->getCodeGen() : nullptr)
+      .Visit(MostRecentTU);
 
   // Lookup alone is not enough: the redeclaration chain still reaches these.
   withdrawMostRecentTU(MostRecentTU);
diff --git a/clang/test/Interpreter/codegen-stale-entries.cpp b/clang/test/Interpreter/codegen-stale-entries.cpp
new file mode 100644
index 00000000000000..ce54f071f2cf98
--- /dev/null
+++ b/clang/test/Interpreter/codegen-stale-entries.cpp
@@ -0,0 +1,25 @@
+// REQUIRES: host-supports-jit
+// RUN: cat %s | clang-repl 2>&1 | FileCheck %s
+//
+// This test demonstrates that stale entries in CodeGen keep foo and infn
+// reachable after %undo. It motivates removing stale entries from
+// CodeGenModule::DeferredDecls and CodeGenModule::Manglings via
+// CodeGenModule::forgetDecl (PR #234493).
+
+extern "C" int printf(const char *, ...);
+
+static int foo(int x);
+static int foo(int x) { return x + 1; }
+%undo
+auto sfr = printf("foo=%d\n", foo(10));
+// CHECK-NOT: foo=11
+// CHECK: JIT session error: Symbols not found
+
+inline int infn(int x);
+inline int infn(int x) { return x + 1; }
+%undo
+auto infnr = printf("infn=%d\n", infn(10));
+// CHECK-NOT: infn=11
+// CHECK: JIT session error: Symbols not found
+
+%quit

>From d9c1a6e06d0a15bb39d0fe78c1a33f56819de140 Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Sun, 25 Oct 2026 10:47:16 +0530
Subject: [PATCH 3/4] add missing headers

---
 clang/lib/Interpreter/IncrementalParser.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index be31db9da5b2fe..3d82f2f9946b2d 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -19,6 +19,8 @@
 #include "clang/AST/DeclContextInternals.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/DeclVisitor.h"
+#include "clang/AST/GlobalDecl.h"
+#include "clang/Basic/ABI.h"
 #include "clang/CodeGen/ModuleBuilder.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Interpreter/PartialTranslationUnit.h"

>From 1c35a6e78edc181f0abe5b54d90b31c5db9ca76f Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Tue, 24 Nov 2026 14:07:11 +0530
Subject: [PATCH 4/4] Fix windows Dtor_Comdat issue

---
 clang/include/clang/CodeGen/ModuleBuilder.h |  2 +-
 clang/lib/CodeGen/CodeGenModule.cpp         |  3 +--
 clang/lib/CodeGen/CodeGenModule.h           |  2 +-
 clang/lib/CodeGen/ModuleBuilder.cpp         |  6 +++---
 clang/lib/Interpreter/IncrementalParser.cpp | 14 ++++++++++++--
 5 files changed, 18 insertions(+), 9 deletions(-)

diff --git a/clang/include/clang/CodeGen/ModuleBuilder.h b/clang/include/clang/CodeGen/ModuleBuilder.h
index 672f97bbae6bdb..06a6bcceca4b5c 100644
--- a/clang/include/clang/CodeGen/ModuleBuilder.h
+++ b/clang/include/clang/CodeGen/ModuleBuilder.h
@@ -117,7 +117,7 @@ class CodeGenerator : public ASTConsumer {
   /// Clear any CodeGen state associated with \p GD’s mangled name so that a
   /// new declaration using the same name is treated as if CodeGen has
   /// never seen it before.
-  void forgetDecl(GlobalDecl GD);
+  void forgetDecl(StringRef MangleName);
 };
 
 /// CreateLLVMCodeGen - Create a CodeGenerator instance.
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index c8869ef0c1f6e5..76d66c48bbff53 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -8617,8 +8617,7 @@ bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
   return true;
 }
 
-void CodeGenModule::forgetDecl(GlobalDecl GD) {
-  StringRef MangledName = getMangledName(GD);
+void CodeGenModule::forgetDecl(StringRef MangledName) {
   DeferredDecls.erase(MangledName);
   Manglings.erase(MangledName);
 }
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index da301a2d0ace0e..370c041d83de99 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -868,7 +868,7 @@ class CodeGenModule : public CodeGenTypeCache {
   bool lookupRepresentativeDecl(StringRef MangledName,
                                 GlobalDecl &Result) const;
 
-  void forgetDecl(GlobalDecl GD);
+  void forgetDecl(StringRef MangleName);
 
   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
     return AtomicSetterHelperFnMap[Ty];
diff --git a/clang/lib/CodeGen/ModuleBuilder.cpp b/clang/lib/CodeGen/ModuleBuilder.cpp
index 4be2aac9d6e8e2..4da322ef48182d 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -155,7 +155,7 @@ namespace {
       return M.get();
     }
 
-    void forgetDecl(GlobalDecl GD) { Builder->forgetDecl(GD); }
+    void forgetDecl(StringRef MangledName) { Builder->forgetDecl(MangledName); }
 
     void Initialize(ASTContext &Context) override {
       Ctx = &Context;
@@ -396,8 +396,8 @@ llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
   return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
 }
 
-void CodeGenerator::forgetDecl(GlobalDecl GD) {
-  static_cast<CodeGeneratorImpl *>(this)->forgetDecl(GD);
+void CodeGenerator::forgetDecl(StringRef MangledName) {
+  static_cast<CodeGeneratorImpl *>(this)->forgetDecl(MangledName);
 }
 
 std::unique_ptr<CodeGenerator>
diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index 3d82f2f9946b2d..b7a06068281737 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -267,8 +267,18 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   void forgetMangledNames(std::initializer_list<GlobalDecl> GDs) {
     if (!CodeGen)
       return;
-    for (GlobalDecl GD : GDs)
-      CodeGen->forgetDecl(GD);
+    for (GlobalDecl GD : GDs) {
+#if defined(_WIN32)
+      // MicrosoftMangle.cpp:mangleCXXDtorType calls llvm_unreachable when
+      // mangling Dtor_Comdat
+      if (isa<CXXDestructorDecl>(GD.getDecl()) &&
+          GD.getDtorType() == Dtor_Comdat) {
+        if (const IdentifierInfo *II = D->getIdentifier())
+          CodeGen->forgetDecl(II->getName());
+      } else
+#endif
+        CodeGen->forgetDecl(CodeGen->GetMangledName(GD));
+    }
   }
 
 public:



More information about the cfe-commits mailing list