[PATCH] [clang] Enforce instantiation of constexpr template functions during non...
authorserge-sans-paille <sguelton@redhat.com>
Sat, 18 Jun 2022 11:48:41 +0000 (13:48 +0200)
committerGianfranco Costamagna <locutusofborg@debian.org>
Fri, 17 Feb 2023 11:57:29 +0000 (11:57 +0000)
Otherwise these functions are not instantiated and we end up with an undefined
symbol.

Fix #55560

Differential Revision: https://reviews.llvm.org/D128119

Gbp-Pq: Name basic_string.patch

clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/CodeGenCXX/constexpr-late-instantiation.cpp [new file with mode: 0644]
clang/test/SemaCXX/constexpr-late-instantiation.cpp [new file with mode: 0644]

index 467372c71496a11bfff3d363263daf3f844b0ec0..293782822e8397be1b4062147596f832f965b1f6 100644 (file)
@@ -4826,7 +4826,8 @@ void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
                                      /*Complain*/DefinitionRequired)) {
     if (DefinitionRequired)
       Function->setInvalidDecl();
-    else if (TSK == TSK_ExplicitInstantiationDefinition) {
+    else if (TSK == TSK_ExplicitInstantiationDefinition ||
+             (Function->isConstexpr() && !Recursive)) {
       // Try again at the end of the translation unit (at which point a
       // definition will be required).
       assert(!Recursive);
@@ -4841,7 +4842,7 @@ void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
         if (getLangOpts().CPlusPlus11)
           Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
-            << Function;
+              << Function;
       }
     }
 
diff --git a/clang/test/CodeGenCXX/constexpr-late-instantiation.cpp b/clang/test/CodeGenCXX/constexpr-late-instantiation.cpp
new file mode 100644 (file)
index 0000000..1c8eef7
--- /dev/null
@@ -0,0 +1,17 @@
+// Make sure foo is instantiated and we don't get a link error
+// RUN: %clang_cc1 -S -emit-llvm -triple %itanium_abi_triple %s -o- | FileCheck %s
+
+template <typename T>
+constexpr T foo(T a);
+
+// CHECK-LABEL: define {{.*}} @main
+int main() {
+  // CHECK: call {{.*}} @_Z3fooIiET_S0_
+  int k = foo<int>(5);
+}
+// CHECK: }
+
+template <typename T>
+constexpr T foo(T a) {
+  return a;
+}
diff --git a/clang/test/SemaCXX/constexpr-late-instantiation.cpp b/clang/test/SemaCXX/constexpr-late-instantiation.cpp
new file mode 100644 (file)
index 0000000..ec8e071
--- /dev/null
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 %s -fsyntax-only -verify
+
+template <typename T>
+constexpr T foo(T a);   // expected-note {{declared here}}
+
+int main() {
+  int k = foo<int>(5);  // Ok
+  constexpr int j =     // expected-error {{constexpr variable 'j' must be initialized by a constant expression}}
+          foo<int>(5);  // expected-note {{undefined function 'foo<int>' cannot be used in a constant expression}}
+}
+
+template <typename T>
+constexpr T foo(T a) {
+  return a;
+}