diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 3b85b98abdd3..0b4b083ffbda 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -414,9 +414,22 @@ Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, const TemplateArgumentListInfo *TemplateArgs) { DeclContext *DC = getFunctionLevelDeclContext(); - if (!isAddressOfOperand && - isa(DC) && - cast(DC)->isInstance()) { + // C++11 [expr.prim.general]p12: + // An id-expression that denotes a non-static data member or non-static + // member function of a class can only be used: + // (...) + // - if that id-expression denotes a non-static data member and it + // appears in an unevaluated operand. + // + // If this might be the case, form a DependentScopeDeclRefExpr instead of a + // CXXDependentScopeMemberExpr. The former can instantiate to either + // DeclRefExpr or MemberExpr depending on lookup results, while the latter is + // always a MemberExpr. + bool MightBeCxx11UnevalField = + getLangOpts().CPlusPlus11 && isUnevaluatedContext(); + + if (!MightBeCxx11UnevalField && !isAddressOfOperand && + isa(DC) && cast(DC)->isInstance()) { QualType ThisType = cast(DC)->getThisType(Context); // Since the 'this' expression is synthesized, we don't need to diff --git a/clang/test/SemaTemplate/instantiate-sizeof.cpp b/clang/test/SemaTemplate/instantiate-sizeof.cpp index bf66fdc17c65..04793f785e63 100644 --- a/clang/test/SemaTemplate/instantiate-sizeof.cpp +++ b/clang/test/SemaTemplate/instantiate-sizeof.cpp @@ -1,5 +1,4 @@ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s -// expected-no-diagnostics // Make sure we handle contexts correctly with sizeof template void f(T n) { @@ -9,3 +8,29 @@ template void f(T n) { int main() { f(1); } + +// Make sure we handle references to non-static data members in unevaluated +// contexts in class template methods correctly. Previously we assumed these +// would be valid MemberRefExprs, but they have no 'this' so we need to form a +// DeclRefExpr to the FieldDecl instead. +// PR26893 +template +struct M { + M() {}; // expected-note {{in instantiation of default member initializer 'M::m' requested here}} + int m = *T::x; // expected-error {{invalid use of non-static data member 'x'}} + void f() { + // These are valid. + static_assert(sizeof(T::x) == 8, "ptr"); + static_assert(sizeof(*T::x) == 4, "int"); + } +}; +struct S { int *x; }; +template struct M; // expected-note {{in instantiation of member function 'M::M' requested here}} + +// Similar test case for PR26893. +template +struct bar { + struct foo { int array[10]; }; + int baz() { return sizeof(foo::array); } +}; +template struct bar<>;