diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -1587,6 +1587,17 @@ // Check the well-formedness of the default template argument, if provided. if (Default) { + // Local variables may not be used as default template arguments. + if (auto *DRE = dyn_cast(Default)) { + if (VarDecl *VD = dyn_cast(DRE->getDecl())) { + if (VD->isLocalVarDecl() && !DRE->isNonOdrUse()) { + Diag(DRE->getLocation(), + diag::err_param_default_argument_references_local) + << VD->getNameAsString(); + } + } + } + // Check for unexpanded parameter packs. if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) return Param; diff --git a/clang/test/SemaTemplate/default-template-arguments.cpp b/clang/test/SemaTemplate/default-template-arguments.cpp new file mode 100644 --- /dev/null +++ b/clang/test/SemaTemplate/default-template-arguments.cpp @@ -0,0 +1,21 @@ +// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s + +namespace GH48755 { +constexpr int z = 2; + +auto f() { + constexpr int x_constexpr = 1; + const int x_const = 1; + static int x_static = 1; + + auto lambda1 = [] {}; // expected-error {{default argument references local variable x_constexpr of enclosing function}} + auto lambda2 = [] {}; // expected-error {{default argument references local variable x_static of enclosing function}} + auto lambda3 = [] {}; // expected-error {{default argument references local variable x_const of enclosing function}} + auto lambda4 = [] {}; + auto lambda5 = [] {}; + auto lambda6 = [] {}; + + const int x_int_const = 1; + auto lambda7 = [] {}; // expected-error {{default argument references local variable x_int_const of enclosing function}} +} +}