Name lookup does not find defining declaration of templated variable of primary template if it is not the first
Consider the following:
template<typename T>
extern T const p;
template<typename T>
extern constexpr T p{};
static_assert(!p<int>, "");
static_assert(!p<void*>, "");
Currently, the second assert fails complaining that "initializer of 'p<void *>' is unknown" so it's not a constant expression.
This issue also happens with static data members with out-of-line initializers:
template<typename T>
struct A {
static const T value;
template<typename U>
static const T templated_value;
};
template<typename T>
constexpr T A<T>::value{};
template<typename T>
template<typename U>
constexpr T A<T>::templated_value{};
static_assert(!A<int>::value, ""); // passes
static_assert(!A<int>::templated_value<void>, ""); // passes
static_assert(!A<void*>::value, ""); // unexpectedly fails
static_assert(!A<void*>::templated_value<void>, ""); // unexpectedly fails
The problem is that at this point in the code:
https://github.com/llvm/llvm-project/blob/0776c48f9b7e69fa447bee57c7c0985caa856be9/clang/lib/Sema/SemaExpr.cpp#L19277-L19278
Var refers to the first declaration of the templated variable, which is not constexpr since it is initialized later, so this is false for a non integral-or-enumeration type, meaning that here:
https://github.com/llvm/llvm-project/blob/0776c48f9b7e69fa447bee57c7c0985caa856be9/clang/lib/Sema/SemaExpr.cpp#L19330-L19335
The instantiation of the initializer is deferred so it ultimately cannot be found.
This is fixed by not deferring the instantiation (e.g., by removing the check for UsableInConstantExpr), but diagnostics only ever point at the initial declaration.
For example:
template<typename T>
extern T const p;
template<typename T> T not_constexpr();
template<typename T>
extern T const p = not_constexpr<T>();
static_assert(!p<int>, "");
The diagnostic note points to the declaration and does not show the non-constexpr definition which would be more helpful
@llvm/issue-subscribers-clang-frontend