[clang] [clang-repl] Re-emit implicitly instantiated templates on subsequent uses (PR #192588)

via cfe-commits cfe-commits at lists.llvm.org
Mon May 25 03:15:12 PDT 2026


https://github.com/voyager-jhk updated https://github.com/llvm/llvm-project/pull/192588

>From 8633bd03ff2447e5b13afea238b99da66bf6d542 Mon Sep 17 00:00:00 2001
From: voyager-jhk <voyager.lpq at gmail.com>
Date: Fri, 17 Apr 2026 11:39:28 +0800
Subject: [PATCH] [clang-repl] Re-emit implicitly instantiated templates on
 subsequent uses

Parsing failures in incremental mode cause CodeGen to discard the current module. However, Sema retains implicitly instantiated function bodies. On subsequent valid references, Sema skips emission, leading to unresolved JIT symbols.

This patch forces re-emission of valid implicit instantiations in IncrementalExtensions mode. CodeGen's GlobalDeclMap naturally deduplicates redundant emissions.

Fixes #146770
---
 clang/lib/Sema/SemaExpr.cpp                  |  9 +++++++++
 clang/test/Interpreter/template-recovery.cpp | 14 ++++++++++++++
 2 files changed, 23 insertions(+)
 create mode 100644 clang/test/Interpreter/template-recovery.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 521a8516ac179..a6bc94789a1b4 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -19061,6 +19061,15 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
         }
       }
     });
+} else if (NeedDefinition && getLangOpts().IncrementalExtensions &&
+             !Diags.hasErrorOccurred()) {
+    const FunctionDecl *Def = nullptr;
+    if (Func->getBody(Def) &&
+        Def->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
+        !Def->isInvalidDecl()) {
+      Consumer.HandleTopLevelDecl(
+          DeclGroupRef(const_cast<FunctionDecl *>(Def)));
+    }
   }
 
   // If a constructor was defined in the context of a default parameter
diff --git a/clang/test/Interpreter/template-recovery.cpp b/clang/test/Interpreter/template-recovery.cpp
new file mode 100644
index 0000000000000..0050928a617a4
--- /dev/null
+++ b/clang/test/Interpreter/template-recovery.cpp
@@ -0,0 +1,14 @@
+// REQUIRES: host-supports-jit
+// RUN: clang-repl -Xcc -fno-color-diagnostics < %s 2>&1 | FileCheck %s
+
+template <typename T> T my_pow(T a, T b) { return a * b; }
+
+(10-)*my_pow(2, 2);
+// CHECK: error: expected expression
+// CHECK: error: Parsing failed.
+
+int x = my_pow(2, 2);
+// CHECK-NOT: JIT session error
+// CHECK-NOT: Failed to materialize symbols
+
+%quit



More information about the cfe-commits mailing list