[HLSL] Implement RWBuffer::operator[] via __builtin_hlsl_resource_getpointer (#117017)
[llvm-project.git] / clang / lib / Sema / SemaExprMember.cpp
blob85d5dfcb3db6de579f87173a7e12412d64bef9cd
1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis member access expressions.
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/DeclCXX.h"
13 #include "clang/AST/DeclObjC.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/Overload.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/Sema/ScopeInfo.h"
22 #include "clang/Sema/SemaObjC.h"
23 #include "clang/Sema/SemaOpenMP.h"
25 using namespace clang;
26 using namespace sema;
28 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
30 /// Determines if the given class is provably not derived from all of
31 /// the prospective base classes.
32 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
33 const BaseSet &Bases) {
34 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
35 return !Bases.count(Base->getCanonicalDecl());
37 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
40 enum IMAKind {
41 /// The reference is definitely not an instance member access.
42 IMA_Static,
44 /// The reference may be an implicit instance member access.
45 IMA_Mixed,
47 /// The reference may be to an instance member, but it might be invalid if
48 /// so, because the context is not an instance method.
49 IMA_Mixed_StaticOrExplicitContext,
51 /// The reference may be to an instance member, but it is invalid if
52 /// so, because the context is from an unrelated class.
53 IMA_Mixed_Unrelated,
55 /// The reference is definitely an implicit instance member access.
56 IMA_Instance,
58 /// The reference may be to an unresolved using declaration.
59 IMA_Unresolved,
61 /// The reference is a contextually-permitted abstract member reference.
62 IMA_Abstract,
64 /// Whether the context is static is dependent on the enclosing template (i.e.
65 /// in a dependent class scope explicit specialization).
66 IMA_Dependent,
68 /// The reference may be to an unresolved using declaration and the
69 /// context is not an instance method.
70 IMA_Unresolved_StaticOrExplicitContext,
72 // The reference refers to a field which is not a member of the containing
73 // class, which is allowed because we're in C++11 mode and the context is
74 // unevaluated.
75 IMA_Field_Uneval_Context,
77 /// All possible referrents are instance members and the current
78 /// context is not an instance method.
79 IMA_Error_StaticOrExplicitContext,
81 /// All possible referrents are instance members of an unrelated
82 /// class.
83 IMA_Error_Unrelated
86 /// The given lookup names class member(s) and is not being used for
87 /// an address-of-member expression. Classify the type of access
88 /// according to whether it's possible that this reference names an
89 /// instance member. This is best-effort in dependent contexts; it is okay to
90 /// conservatively answer "yes", in which case some errors will simply
91 /// not be caught until template-instantiation.
92 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
93 const LookupResult &R) {
94 assert(!R.empty() && (*R.begin())->isCXXClassMember());
96 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
98 bool couldInstantiateToStatic = false;
99 bool isStaticOrExplicitContext = SemaRef.CXXThisTypeOverride.isNull();
101 if (auto *MD = dyn_cast<CXXMethodDecl>(DC)) {
102 if (MD->isImplicitObjectMemberFunction()) {
103 isStaticOrExplicitContext = false;
104 // A dependent class scope function template explicit specialization
105 // that is neither declared 'static' nor with an explicit object
106 // parameter could instantiate to a static or non-static member function.
107 couldInstantiateToStatic = MD->getDependentSpecializationInfo();
111 if (R.isUnresolvableResult()) {
112 if (couldInstantiateToStatic)
113 return IMA_Dependent;
114 return isStaticOrExplicitContext ? IMA_Unresolved_StaticOrExplicitContext
115 : IMA_Unresolved;
118 // Collect all the declaring classes of instance members we find.
119 bool hasNonInstance = false;
120 bool isField = false;
121 BaseSet Classes;
122 for (NamedDecl *D : R) {
123 // Look through any using decls.
124 D = D->getUnderlyingDecl();
126 if (D->isCXXInstanceMember()) {
127 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
128 isa<IndirectFieldDecl>(D);
130 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
131 Classes.insert(R->getCanonicalDecl());
132 } else
133 hasNonInstance = true;
136 // If we didn't find any instance members, it can't be an implicit
137 // member reference.
138 if (Classes.empty())
139 return IMA_Static;
141 if (couldInstantiateToStatic)
142 return IMA_Dependent;
144 // C++11 [expr.prim.general]p12:
145 // An id-expression that denotes a non-static data member or non-static
146 // member function of a class can only be used:
147 // (...)
148 // - if that id-expression denotes a non-static data member and it
149 // appears in an unevaluated operand.
151 // This rule is specific to C++11. However, we also permit this form
152 // in unevaluated inline assembly operands, like the operand to a SIZE.
153 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
154 assert(!AbstractInstanceResult);
155 switch (SemaRef.ExprEvalContexts.back().Context) {
156 case Sema::ExpressionEvaluationContext::Unevaluated:
157 case Sema::ExpressionEvaluationContext::UnevaluatedList:
158 if (isField && SemaRef.getLangOpts().CPlusPlus11)
159 AbstractInstanceResult = IMA_Field_Uneval_Context;
160 break;
162 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
163 AbstractInstanceResult = IMA_Abstract;
164 break;
166 case Sema::ExpressionEvaluationContext::DiscardedStatement:
167 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
168 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
169 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
170 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
171 break;
174 // If the current context is not an instance method, it can't be
175 // an implicit member reference.
176 if (isStaticOrExplicitContext) {
177 if (hasNonInstance)
178 return IMA_Mixed_StaticOrExplicitContext;
180 return AbstractInstanceResult ? AbstractInstanceResult
181 : IMA_Error_StaticOrExplicitContext;
184 CXXRecordDecl *contextClass;
185 if (auto *MD = dyn_cast<CXXMethodDecl>(DC))
186 contextClass = MD->getParent()->getCanonicalDecl();
187 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
188 contextClass = RD;
189 else
190 return AbstractInstanceResult ? AbstractInstanceResult
191 : IMA_Error_StaticOrExplicitContext;
193 // [class.mfct.non-static]p3:
194 // ...is used in the body of a non-static member function of class X,
195 // if name lookup (3.4.1) resolves the name in the id-expression to a
196 // non-static non-type member of some class C [...]
197 // ...if C is not X or a base class of X, the class member access expression
198 // is ill-formed.
199 if (R.getNamingClass() &&
200 contextClass->getCanonicalDecl() !=
201 R.getNamingClass()->getCanonicalDecl()) {
202 // If the naming class is not the current context, this was a qualified
203 // member name lookup, and it's sufficient to check that we have the naming
204 // class as a base class.
205 Classes.clear();
206 Classes.insert(R.getNamingClass()->getCanonicalDecl());
209 // If we can prove that the current context is unrelated to all the
210 // declaring classes, it can't be an implicit member reference (in
211 // which case it's an error if any of those members are selected).
212 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
213 return hasNonInstance ? IMA_Mixed_Unrelated :
214 AbstractInstanceResult ? AbstractInstanceResult :
215 IMA_Error_Unrelated;
217 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
220 /// Diagnose a reference to a field with no object available.
221 static void diagnoseInstanceReference(Sema &SemaRef,
222 const CXXScopeSpec &SS,
223 NamedDecl *Rep,
224 const DeclarationNameInfo &nameInfo) {
225 SourceLocation Loc = nameInfo.getLoc();
226 SourceRange Range(Loc);
227 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
229 // Look through using shadow decls and aliases.
230 Rep = Rep->getUnderlyingDecl();
232 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
233 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
234 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
235 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
237 bool InStaticMethod = Method && Method->isStatic();
238 bool InExplicitObjectMethod =
239 Method && Method->isExplicitObjectMemberFunction();
240 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
242 std::string Replacement;
243 if (InExplicitObjectMethod) {
244 DeclarationName N = Method->getParamDecl(0)->getDeclName();
245 if (!N.isEmpty()) {
246 Replacement.append(N.getAsString());
247 Replacement.append(".");
250 if (IsField && InStaticMethod)
251 // "invalid use of member 'x' in static member function"
252 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_method)
253 << Range << nameInfo.getName() << /*static*/ 0;
254 else if (IsField && InExplicitObjectMethod) {
255 auto Diag = SemaRef.Diag(Loc, diag::err_invalid_member_use_in_method)
256 << Range << nameInfo.getName() << /*explicit*/ 1;
257 if (!Replacement.empty())
258 Diag << FixItHint::CreateInsertion(Loc, Replacement);
259 } else if (ContextClass && RepClass && SS.isEmpty() &&
260 !InExplicitObjectMethod && !InStaticMethod &&
261 !RepClass->Equals(ContextClass) &&
262 RepClass->Encloses(ContextClass))
263 // Unqualified lookup in a non-static member function found a member of an
264 // enclosing class.
265 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
266 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
267 else if (IsField)
268 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
269 << nameInfo.getName() << Range;
270 else if (!InExplicitObjectMethod)
271 SemaRef.Diag(Loc, diag::err_member_call_without_object)
272 << Range << /*static*/ 0;
273 else {
274 if (const auto *Tpl = dyn_cast<FunctionTemplateDecl>(Rep))
275 Rep = Tpl->getTemplatedDecl();
276 const auto *Callee = cast<CXXMethodDecl>(Rep);
277 auto Diag = SemaRef.Diag(Loc, diag::err_member_call_without_object)
278 << Range << Callee->isExplicitObjectMemberFunction();
279 if (!Replacement.empty())
280 Diag << FixItHint::CreateInsertion(Loc, Replacement);
284 bool Sema::isPotentialImplicitMemberAccess(const CXXScopeSpec &SS,
285 LookupResult &R,
286 bool IsAddressOfOperand) {
287 if (!getLangOpts().CPlusPlus)
288 return false;
289 else if (R.empty() || !R.begin()->isCXXClassMember())
290 return false;
291 else if (!IsAddressOfOperand)
292 return true;
293 else if (!SS.isEmpty())
294 return false;
295 else if (R.isOverloadedResult())
296 return false;
297 else if (R.isUnresolvableResult())
298 return true;
299 else
300 return isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(R.getFoundDecl());
303 ExprResult Sema::BuildPossibleImplicitMemberExpr(
304 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
305 const TemplateArgumentListInfo *TemplateArgs, const Scope *S) {
306 switch (IMAKind Classification = ClassifyImplicitMemberAccess(*this, R)) {
307 case IMA_Instance:
308 case IMA_Mixed:
309 case IMA_Mixed_Unrelated:
310 case IMA_Unresolved:
311 return BuildImplicitMemberExpr(
312 SS, TemplateKWLoc, R, TemplateArgs,
313 /*IsKnownInstance=*/Classification == IMA_Instance, S);
314 case IMA_Field_Uneval_Context:
315 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
316 << R.getLookupNameInfo().getName();
317 [[fallthrough]];
318 case IMA_Static:
319 case IMA_Abstract:
320 case IMA_Mixed_StaticOrExplicitContext:
321 case IMA_Unresolved_StaticOrExplicitContext:
322 if (TemplateArgs || TemplateKWLoc.isValid())
323 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*RequiresADL=*/false,
324 TemplateArgs);
325 return BuildDeclarationNameExpr(SS, R, /*NeedsADL=*/false,
326 /*AcceptInvalidDecl=*/false);
327 case IMA_Dependent:
328 R.suppressDiagnostics();
329 return UnresolvedLookupExpr::Create(
330 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
331 TemplateKWLoc, R.getLookupNameInfo(), /*RequiresADL=*/false,
332 TemplateArgs, R.begin(), R.end(), /*KnownDependent=*/true,
333 /*KnownInstantiationDependent=*/true);
335 case IMA_Error_StaticOrExplicitContext:
336 case IMA_Error_Unrelated:
337 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
338 R.getLookupNameInfo());
339 return ExprError();
342 llvm_unreachable("unexpected instance member access kind");
345 /// Determine whether input char is from rgba component set.
346 static bool
347 IsRGBA(char c) {
348 switch (c) {
349 case 'r':
350 case 'g':
351 case 'b':
352 case 'a':
353 return true;
354 default:
355 return false;
359 // OpenCL v1.1, s6.1.7
360 // The component swizzle length must be in accordance with the acceptable
361 // vector sizes.
362 static bool IsValidOpenCLComponentSwizzleLength(unsigned len)
364 return (len >= 1 && len <= 4) || len == 8 || len == 16;
367 /// Check an ext-vector component access expression.
369 /// VK should be set in advance to the value kind of the base
370 /// expression.
371 static QualType
372 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
373 SourceLocation OpLoc, const IdentifierInfo *CompName,
374 SourceLocation CompLoc) {
375 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
376 // see FIXME there.
378 // FIXME: This logic can be greatly simplified by splitting it along
379 // halving/not halving and reworking the component checking.
380 const ExtVectorType *vecType = baseType->castAs<ExtVectorType>();
382 // The vector accessor can't exceed the number of elements.
383 const char *compStr = CompName->getNameStart();
385 // This flag determines whether or not the component is one of the four
386 // special names that indicate a subset of exactly half the elements are
387 // to be selected.
388 bool HalvingSwizzle = false;
390 // This flag determines whether or not CompName has an 's' char prefix,
391 // indicating that it is a string of hex values to be used as vector indices.
392 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
394 bool HasRepeated = false;
395 bool HasIndex[16] = {};
397 int Idx;
399 // Check that we've found one of the special components, or that the component
400 // names must come from the same set.
401 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
402 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
403 HalvingSwizzle = true;
404 } else if (!HexSwizzle &&
405 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
406 bool HasRGBA = IsRGBA(*compStr);
407 do {
408 // Ensure that xyzw and rgba components don't intermingle.
409 if (HasRGBA != IsRGBA(*compStr))
410 break;
411 if (HasIndex[Idx]) HasRepeated = true;
412 HasIndex[Idx] = true;
413 compStr++;
414 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
416 // Emit a warning if an rgba selector is used earlier than OpenCL C 3.0.
417 if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
418 if (S.getLangOpts().OpenCL &&
419 S.getLangOpts().getOpenCLCompatibleVersion() < 300) {
420 const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
421 S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
422 << StringRef(DiagBegin, 1) << SourceRange(CompLoc);
425 } else {
426 if (HexSwizzle) compStr++;
427 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
428 if (HasIndex[Idx]) HasRepeated = true;
429 HasIndex[Idx] = true;
430 compStr++;
434 if (!HalvingSwizzle && *compStr) {
435 // We didn't get to the end of the string. This means the component names
436 // didn't come from the same set *or* we encountered an illegal name.
437 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
438 << StringRef(compStr, 1) << SourceRange(CompLoc);
439 return QualType();
442 // Ensure no component accessor exceeds the width of the vector type it
443 // operates on.
444 if (!HalvingSwizzle) {
445 compStr = CompName->getNameStart();
447 if (HexSwizzle)
448 compStr++;
450 while (*compStr) {
451 if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
452 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
453 << baseType << SourceRange(CompLoc);
454 return QualType();
459 // OpenCL mode requires swizzle length to be in accordance with accepted
460 // sizes. Clang however supports arbitrary lengths for other languages.
461 if (S.getLangOpts().OpenCL && !HalvingSwizzle) {
462 unsigned SwizzleLength = CompName->getLength();
464 if (HexSwizzle)
465 SwizzleLength--;
467 if (IsValidOpenCLComponentSwizzleLength(SwizzleLength) == false) {
468 S.Diag(OpLoc, diag::err_opencl_ext_vector_component_invalid_length)
469 << SwizzleLength << SourceRange(CompLoc);
470 return QualType();
474 // The component accessor looks fine - now we need to compute the actual type.
475 // The vector type is implied by the component accessor. For example,
476 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
477 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
478 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
479 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
480 : CompName->getLength();
481 if (HexSwizzle)
482 CompSize--;
484 if (CompSize == 1)
485 return vecType->getElementType();
487 if (HasRepeated)
488 VK = VK_PRValue;
490 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
491 // Now look up the TypeDefDecl from the vector type. Without this,
492 // diagostics look bad. We want extended vector types to appear built-in.
493 for (Sema::ExtVectorDeclsType::iterator
494 I = S.ExtVectorDecls.begin(S.getExternalSource()),
495 E = S.ExtVectorDecls.end();
496 I != E; ++I) {
497 if ((*I)->getUnderlyingType() == VT)
498 return S.Context.getTypedefType(*I);
501 return VT; // should never get here (a typedef type should always be found).
504 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
505 IdentifierInfo *Member,
506 const Selector &Sel,
507 ASTContext &Context) {
508 if (Member)
509 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
510 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
511 return PD;
512 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
513 return OMD;
515 for (const auto *I : PDecl->protocols()) {
516 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
517 Context))
518 return D;
520 return nullptr;
523 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
524 IdentifierInfo *Member,
525 const Selector &Sel,
526 ASTContext &Context) {
527 // Check protocols on qualified interfaces.
528 Decl *GDecl = nullptr;
529 for (const auto *I : QIdTy->quals()) {
530 if (Member)
531 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
532 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
533 GDecl = PD;
534 break;
536 // Also must look for a getter or setter name which uses property syntax.
537 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
538 GDecl = OMD;
539 break;
542 if (!GDecl) {
543 for (const auto *I : QIdTy->quals()) {
544 // Search in the protocol-qualifier list of current protocol.
545 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
546 if (GDecl)
547 return GDecl;
550 return GDecl;
553 ExprResult
554 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
555 bool IsArrow, SourceLocation OpLoc,
556 const CXXScopeSpec &SS,
557 SourceLocation TemplateKWLoc,
558 NamedDecl *FirstQualifierInScope,
559 const DeclarationNameInfo &NameInfo,
560 const TemplateArgumentListInfo *TemplateArgs) {
561 // Even in dependent contexts, try to diagnose base expressions with
562 // obviously wrong types, e.g.:
564 // T* t;
565 // t.f;
567 // In Obj-C++, however, the above expression is valid, since it could be
568 // accessing the 'f' property if T is an Obj-C interface. The extra check
569 // allows this, while still reporting an error if T is a struct pointer.
570 if (!IsArrow) {
571 const PointerType *PT = BaseType->getAs<PointerType>();
572 if (PT && (!getLangOpts().ObjC ||
573 PT->getPointeeType()->isRecordType())) {
574 assert(BaseExpr && "cannot happen with implicit member accesses");
575 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
576 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
577 return ExprError();
581 assert(BaseType->isDependentType() || NameInfo.getName().isDependentName() ||
582 isDependentScopeSpecifier(SS) ||
583 (TemplateArgs && llvm::any_of(TemplateArgs->arguments(),
584 [](const TemplateArgumentLoc &Arg) {
585 return Arg.getArgument().isDependent();
586 })));
588 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
589 // must have pointer type, and the accessed type is the pointee.
590 return CXXDependentScopeMemberExpr::Create(
591 Context, BaseExpr, BaseType, IsArrow, OpLoc,
592 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
593 NameInfo, TemplateArgs);
596 /// We know that the given qualified member reference points only to
597 /// declarations which do not belong to the static type of the base
598 /// expression. Diagnose the problem.
599 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
600 Expr *BaseExpr,
601 QualType BaseType,
602 const CXXScopeSpec &SS,
603 NamedDecl *rep,
604 const DeclarationNameInfo &nameInfo) {
605 // If this is an implicit member access, use a different set of
606 // diagnostics.
607 if (!BaseExpr)
608 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
610 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
611 << SS.getRange() << rep << BaseType;
614 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
615 QualType BaseType,
616 const CXXScopeSpec &SS,
617 const LookupResult &R) {
618 CXXRecordDecl *BaseRecord =
619 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
620 if (!BaseRecord) {
621 // We can't check this yet because the base type is still
622 // dependent.
623 assert(BaseType->isDependentType());
624 return false;
627 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
628 // If this is an implicit member reference and we find a
629 // non-instance member, it's not an error.
630 if (!BaseExpr && !(*I)->isCXXInstanceMember())
631 return false;
633 // Note that we use the DC of the decl, not the underlying decl.
634 DeclContext *DC = (*I)->getDeclContext()->getNonTransparentContext();
635 if (!DC->isRecord())
636 continue;
638 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
639 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
640 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
641 return false;
644 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
645 R.getRepresentativeDecl(),
646 R.getLookupNameInfo());
647 return true;
650 namespace {
652 // Callback to only accept typo corrections that are either a ValueDecl or a
653 // FunctionTemplateDecl and are declared in the current record or, for a C++
654 // classes, one of its base classes.
655 class RecordMemberExprValidatorCCC final : public CorrectionCandidateCallback {
656 public:
657 explicit RecordMemberExprValidatorCCC(QualType RTy)
658 : Record(RTy->getAsRecordDecl()) {
659 // Don't add bare keywords to the consumer since they will always fail
660 // validation by virtue of not being associated with any decls.
661 WantTypeSpecifiers = false;
662 WantExpressionKeywords = false;
663 WantCXXNamedCasts = false;
664 WantFunctionLikeCasts = false;
665 WantRemainingKeywords = false;
668 bool ValidateCandidate(const TypoCorrection &candidate) override {
669 NamedDecl *ND = candidate.getCorrectionDecl();
670 // Don't accept candidates that cannot be member functions, constants,
671 // variables, or templates.
672 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
673 return false;
675 // Accept candidates that occur in the current record.
676 if (Record->containsDecl(ND))
677 return true;
679 if (const auto *RD = dyn_cast<CXXRecordDecl>(Record)) {
680 // Accept candidates that occur in any of the current class' base classes.
681 for (const auto &BS : RD->bases()) {
682 if (const auto *BSTy = BS.getType()->getAs<RecordType>()) {
683 if (BSTy->getDecl()->containsDecl(ND))
684 return true;
689 return false;
692 std::unique_ptr<CorrectionCandidateCallback> clone() override {
693 return std::make_unique<RecordMemberExprValidatorCCC>(*this);
696 private:
697 const RecordDecl *const Record;
702 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
703 Expr *BaseExpr, QualType RTy,
704 SourceLocation OpLoc, bool IsArrow,
705 CXXScopeSpec &SS, bool HasTemplateArgs,
706 SourceLocation TemplateKWLoc,
707 TypoExpr *&TE) {
708 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
709 if (!RTy->isDependentType() &&
710 !SemaRef.isThisOutsideMemberFunctionBody(RTy) &&
711 SemaRef.RequireCompleteType(
712 OpLoc, RTy, diag::err_typecheck_incomplete_tag, BaseRange))
713 return true;
715 // LookupTemplateName/LookupParsedName don't expect these both to exist
716 // simultaneously.
717 QualType ObjectType = SS.isSet() ? QualType() : RTy;
718 if (HasTemplateArgs || TemplateKWLoc.isValid())
719 return SemaRef.LookupTemplateName(R,
720 /*S=*/nullptr, SS, ObjectType,
721 /*EnteringContext=*/false, TemplateKWLoc);
723 SemaRef.LookupParsedName(R, /*S=*/nullptr, &SS, ObjectType);
725 if (!R.empty() || R.wasNotFoundInCurrentInstantiation())
726 return false;
728 DeclarationName Typo = R.getLookupName();
729 SourceLocation TypoLoc = R.getNameLoc();
730 // Recompute the lookup context.
731 DeclContext *DC = SS.isSet() ? SemaRef.computeDeclContext(SS)
732 : SemaRef.computeDeclContext(RTy);
734 struct QueryState {
735 Sema &SemaRef;
736 DeclarationNameInfo NameInfo;
737 Sema::LookupNameKind LookupKind;
738 RedeclarationKind Redecl;
740 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
741 R.redeclarationKind()};
742 RecordMemberExprValidatorCCC CCC(RTy);
743 TE = SemaRef.CorrectTypoDelayed(
744 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS, CCC,
745 [=, &SemaRef](const TypoCorrection &TC) {
746 if (TC) {
747 assert(!TC.isKeyword() &&
748 "Got a keyword as a correction for a member!");
749 bool DroppedSpecifier =
750 TC.WillReplaceSpecifier() &&
751 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
752 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
753 << Typo << DC << DroppedSpecifier
754 << SS.getRange());
755 } else {
756 SemaRef.Diag(TypoLoc, diag::err_no_member)
757 << Typo << DC << (SS.isSet() ? SS.getRange() : BaseRange);
760 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
761 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
762 R.clear(); // Ensure there's no decls lingering in the shared state.
763 R.suppressDiagnostics();
764 R.setLookupName(TC.getCorrection());
765 for (NamedDecl *ND : TC)
766 R.addDecl(ND);
767 R.resolveKind();
768 return SemaRef.BuildMemberReferenceExpr(
769 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
770 nullptr, R, nullptr, nullptr);
772 Sema::CTK_ErrorRecovery, DC);
774 return false;
777 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
778 ExprResult &BaseExpr, bool &IsArrow,
779 SourceLocation OpLoc, CXXScopeSpec &SS,
780 Decl *ObjCImpDecl, bool HasTemplateArgs,
781 SourceLocation TemplateKWLoc);
783 ExprResult Sema::BuildMemberReferenceExpr(
784 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
785 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
786 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
787 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
788 ActOnMemberAccessExtraArgs *ExtraArgs) {
789 LookupResult R(*this, NameInfo, LookupMemberName);
791 // Implicit member accesses.
792 if (!Base) {
793 TypoExpr *TE = nullptr;
794 QualType RecordTy = BaseType;
795 if (IsArrow) RecordTy = RecordTy->castAs<PointerType>()->getPointeeType();
796 if (LookupMemberExprInRecord(*this, R, nullptr, RecordTy, OpLoc, IsArrow,
797 SS, TemplateArgs != nullptr, TemplateKWLoc,
798 TE))
799 return ExprError();
800 if (TE)
801 return TE;
803 // Explicit member accesses.
804 } else {
805 ExprResult BaseResult = Base;
806 ExprResult Result =
807 LookupMemberExpr(*this, R, BaseResult, IsArrow, OpLoc, SS,
808 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
809 TemplateArgs != nullptr, TemplateKWLoc);
811 if (BaseResult.isInvalid())
812 return ExprError();
813 Base = BaseResult.get();
815 if (Result.isInvalid())
816 return ExprError();
818 if (Result.get())
819 return Result;
821 // LookupMemberExpr can modify Base, and thus change BaseType
822 BaseType = Base->getType();
825 // BuildMemberReferenceExpr expects the nested-name-specifier, if any, to be
826 // valid.
827 if (SS.isInvalid())
828 return ExprError();
830 return BuildMemberReferenceExpr(Base, BaseType,
831 OpLoc, IsArrow, SS, TemplateKWLoc,
832 FirstQualifierInScope, R, TemplateArgs, S,
833 false, ExtraArgs);
836 ExprResult
837 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
838 SourceLocation loc,
839 IndirectFieldDecl *indirectField,
840 DeclAccessPair foundDecl,
841 Expr *baseObjectExpr,
842 SourceLocation opLoc) {
843 // First, build the expression that refers to the base object.
845 // Case 1: the base of the indirect field is not a field.
846 VarDecl *baseVariable = indirectField->getVarDecl();
847 CXXScopeSpec EmptySS;
848 if (baseVariable) {
849 assert(baseVariable->getType()->isRecordType());
851 // In principle we could have a member access expression that
852 // accesses an anonymous struct/union that's a static member of
853 // the base object's class. However, under the current standard,
854 // static data members cannot be anonymous structs or unions.
855 // Supporting this is as easy as building a MemberExpr here.
856 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
858 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
860 ExprResult result
861 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
862 if (result.isInvalid()) return ExprError();
864 baseObjectExpr = result.get();
867 assert((baseVariable || baseObjectExpr) &&
868 "referencing anonymous struct/union without a base variable or "
869 "expression");
871 // Build the implicit member references to the field of the
872 // anonymous struct/union.
873 Expr *result = baseObjectExpr;
874 IndirectFieldDecl::chain_iterator
875 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
877 // Case 2: the base of the indirect field is a field and the user
878 // wrote a member expression.
879 if (!baseVariable) {
880 FieldDecl *field = cast<FieldDecl>(*FI);
882 bool baseObjectIsPointer = baseObjectExpr->getType()->isPointerType();
884 // Make a nameInfo that properly uses the anonymous name.
885 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
887 // Build the first member access in the chain with full information.
888 result =
889 BuildFieldReferenceExpr(result, baseObjectIsPointer, SourceLocation(),
890 SS, field, foundDecl, memberNameInfo)
891 .get();
892 if (!result)
893 return ExprError();
896 // In all cases, we should now skip the first declaration in the chain.
897 ++FI;
899 while (FI != FEnd) {
900 FieldDecl *field = cast<FieldDecl>(*FI++);
902 // FIXME: these are somewhat meaningless
903 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
904 DeclAccessPair fakeFoundDecl =
905 DeclAccessPair::make(field, field->getAccess());
907 result =
908 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
909 (FI == FEnd ? SS : EmptySS), field,
910 fakeFoundDecl, memberNameInfo)
911 .get();
914 return result;
917 static ExprResult
918 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
919 const CXXScopeSpec &SS,
920 MSPropertyDecl *PD,
921 const DeclarationNameInfo &NameInfo) {
922 // Property names are always simple identifiers and therefore never
923 // require any interesting additional storage.
924 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
925 S.Context.PseudoObjectTy, VK_LValue,
926 SS.getWithLocInContext(S.Context),
927 NameInfo.getLoc());
930 MemberExpr *Sema::BuildMemberExpr(
931 Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS,
932 SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl,
933 bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo,
934 QualType Ty, ExprValueKind VK, ExprObjectKind OK,
935 const TemplateArgumentListInfo *TemplateArgs) {
936 assert((!IsArrow || Base->isPRValue()) &&
937 "-> base must be a pointer prvalue");
938 MemberExpr *E =
939 MemberExpr::Create(Context, Base, IsArrow, OpLoc, NNS, TemplateKWLoc,
940 Member, FoundDecl, MemberNameInfo, TemplateArgs, Ty,
941 VK, OK, getNonOdrUseReasonInCurrentContext(Member));
942 E->setHadMultipleCandidates(HadMultipleCandidates);
943 MarkMemberReferenced(E);
945 // C++ [except.spec]p17:
946 // An exception-specification is considered to be needed when:
947 // - in an expression the function is the unique lookup result or the
948 // selected member of a set of overloaded functions
949 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
950 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
951 if (auto *NewFPT = ResolveExceptionSpec(MemberNameInfo.getLoc(), FPT))
952 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
956 return E;
959 /// Determine if the given scope is within a function-try-block handler.
960 static bool IsInFnTryBlockHandler(const Scope *S) {
961 // Walk the scope stack until finding a FnTryCatchScope, or leave the
962 // function scope. If a FnTryCatchScope is found, check whether the TryScope
963 // flag is set. If it is not, it's a function-try-block handler.
964 for (; S != S->getFnParent(); S = S->getParent()) {
965 if (S->isFnTryCatchScope())
966 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
968 return false;
971 ExprResult
972 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
973 SourceLocation OpLoc, bool IsArrow,
974 const CXXScopeSpec &SS,
975 SourceLocation TemplateKWLoc,
976 NamedDecl *FirstQualifierInScope,
977 LookupResult &R,
978 const TemplateArgumentListInfo *TemplateArgs,
979 const Scope *S,
980 bool SuppressQualifierCheck,
981 ActOnMemberAccessExtraArgs *ExtraArgs) {
982 assert(!SS.isInvalid() && "nested-name-specifier cannot be invalid");
983 // If the member wasn't found in the current instantiation, or if the
984 // arrow operator was used with a dependent non-pointer object expression,
985 // build a CXXDependentScopeMemberExpr.
986 if (R.wasNotFoundInCurrentInstantiation() ||
987 (R.getLookupName().getCXXOverloadedOperator() == OO_Equal &&
988 (SS.isSet() ? SS.getScopeRep()->isDependent()
989 : BaseExprType->isDependentType())))
990 return ActOnDependentMemberExpr(BaseExpr, BaseExprType, IsArrow, OpLoc, SS,
991 TemplateKWLoc, FirstQualifierInScope,
992 R.getLookupNameInfo(), TemplateArgs);
994 QualType BaseType = BaseExprType;
995 if (IsArrow) {
996 assert(BaseType->isPointerType());
997 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
999 R.setBaseObjectType(BaseType);
1001 assert((SS.isEmpty()
1002 ? !BaseType->isDependentType() || computeDeclContext(BaseType)
1003 : !isDependentScopeSpecifier(SS) || computeDeclContext(SS)) &&
1004 "dependent lookup context that isn't the current instantiation?");
1006 // C++1z [expr.ref]p2:
1007 // For the first option (dot) the first expression shall be a glvalue [...]
1008 if (!IsArrow && BaseExpr && BaseExpr->isPRValue()) {
1009 ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
1010 if (Converted.isInvalid())
1011 return ExprError();
1012 BaseExpr = Converted.get();
1015 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
1016 DeclarationName MemberName = MemberNameInfo.getName();
1017 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1019 if (R.isAmbiguous())
1020 return ExprError();
1022 // [except.handle]p10: Referring to any non-static member or base class of an
1023 // object in the handler for a function-try-block of a constructor or
1024 // destructor for that object results in undefined behavior.
1025 const auto *FD = getCurFunctionDecl();
1026 if (S && BaseExpr && FD &&
1027 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1028 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1029 IsInFnTryBlockHandler(S))
1030 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1031 << isa<CXXDestructorDecl>(FD);
1033 if (R.empty()) {
1034 ExprResult RetryExpr = ExprError();
1035 if (ExtraArgs && !IsArrow && BaseExpr && !BaseExpr->isTypeDependent()) {
1036 SFINAETrap Trap(*this, true);
1037 ParsedType ObjectType;
1038 bool MayBePseudoDestructor = false;
1039 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr, OpLoc,
1040 tok::arrow, ObjectType,
1041 MayBePseudoDestructor);
1042 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1043 CXXScopeSpec TempSS(SS);
1044 RetryExpr = ActOnMemberAccessExpr(
1045 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
1046 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
1048 if (Trap.hasErrorOccurred())
1049 RetryExpr = ExprError();
1052 // Rederive where we looked up.
1053 DeclContext *DC =
1054 (SS.isSet() ? computeDeclContext(SS) : computeDeclContext(BaseType));
1055 assert(DC);
1057 if (RetryExpr.isUsable())
1058 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1059 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1060 else
1061 Diag(R.getNameLoc(), diag::err_no_member)
1062 << MemberName << DC
1063 << (SS.isSet()
1064 ? SS.getRange()
1065 : (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()));
1066 return RetryExpr;
1069 // Diagnose lookups that find only declarations from a non-base
1070 // type. This is possible for either qualified lookups (which may
1071 // have been qualified with an unrelated type) or implicit member
1072 // expressions (which were found with unqualified lookup and thus
1073 // may have come from an enclosing scope). Note that it's okay for
1074 // lookup to find declarations from a non-base type as long as those
1075 // aren't the ones picked by overload resolution.
1076 if ((SS.isSet() || !BaseExpr ||
1077 (isa<CXXThisExpr>(BaseExpr) &&
1078 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1079 !SuppressQualifierCheck &&
1080 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1081 return ExprError();
1083 // Construct an unresolved result if we in fact got an unresolved
1084 // result.
1085 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1086 // Suppress any lookup-related diagnostics; we'll do these when we
1087 // pick a member.
1088 R.suppressDiagnostics();
1090 UnresolvedMemberExpr *MemExpr
1091 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1092 BaseExpr, BaseExprType,
1093 IsArrow, OpLoc,
1094 SS.getWithLocInContext(Context),
1095 TemplateKWLoc, MemberNameInfo,
1096 TemplateArgs, R.begin(), R.end());
1098 return MemExpr;
1101 assert(R.isSingleResult());
1102 DeclAccessPair FoundDecl = R.begin().getPair();
1103 NamedDecl *MemberDecl = R.getFoundDecl();
1105 // FIXME: diagnose the presence of template arguments now.
1107 // If the decl being referenced had an error, return an error for this
1108 // sub-expr without emitting another error, in order to avoid cascading
1109 // error cases.
1110 if (MemberDecl->isInvalidDecl())
1111 return ExprError();
1113 // Handle the implicit-member-access case.
1114 if (!BaseExpr) {
1115 // If this is not an instance member, convert to a non-member access.
1116 if (!MemberDecl->isCXXInstanceMember()) {
1117 // We might have a variable template specialization (or maybe one day a
1118 // member concept-id).
1119 if (TemplateArgs || TemplateKWLoc.isValid())
1120 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/false, TemplateArgs);
1122 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1123 FoundDecl, TemplateArgs);
1125 SourceLocation Loc = R.getNameLoc();
1126 if (SS.getRange().isValid())
1127 Loc = SS.getRange().getBegin();
1128 BaseExpr = BuildCXXThisExpr(Loc, BaseExprType, /*IsImplicit=*/true);
1131 // Check the use of this member.
1132 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1133 return ExprError();
1135 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1136 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1137 MemberNameInfo);
1139 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1140 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1141 MemberNameInfo);
1143 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1144 // We may have found a field within an anonymous union or struct
1145 // (C++ [class.union]).
1146 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
1147 FoundDecl, BaseExpr,
1148 OpLoc);
1150 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
1151 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc,
1152 SS.getWithLocInContext(Context), TemplateKWLoc, Var,
1153 FoundDecl, /*HadMultipleCandidates=*/false,
1154 MemberNameInfo, Var->getType().getNonReferenceType(),
1155 VK_LValue, OK_Ordinary);
1158 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1159 ExprValueKind valueKind;
1160 QualType type;
1161 if (MemberFn->isInstance()) {
1162 valueKind = VK_PRValue;
1163 type = Context.BoundMemberTy;
1164 } else {
1165 valueKind = VK_LValue;
1166 type = MemberFn->getType();
1169 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc,
1170 SS.getWithLocInContext(Context), TemplateKWLoc,
1171 MemberFn, FoundDecl, /*HadMultipleCandidates=*/false,
1172 MemberNameInfo, type, valueKind, OK_Ordinary);
1174 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1176 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1177 return BuildMemberExpr(
1178 BaseExpr, IsArrow, OpLoc, SS.getWithLocInContext(Context),
1179 TemplateKWLoc, Enum, FoundDecl, /*HadMultipleCandidates=*/false,
1180 MemberNameInfo, Enum->getType(), VK_PRValue, OK_Ordinary);
1183 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1184 if (!TemplateArgs) {
1185 diagnoseMissingTemplateArguments(
1186 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), VarTempl, MemberLoc);
1187 return ExprError();
1190 DeclResult VDecl = CheckVarTemplateId(VarTempl, TemplateKWLoc,
1191 MemberNameInfo.getLoc(), *TemplateArgs);
1192 if (VDecl.isInvalid())
1193 return ExprError();
1195 // Non-dependent member, but dependent template arguments.
1196 if (!VDecl.get())
1197 return ActOnDependentMemberExpr(
1198 BaseExpr, BaseExpr->getType(), IsArrow, OpLoc, SS, TemplateKWLoc,
1199 FirstQualifierInScope, MemberNameInfo, TemplateArgs);
1201 VarDecl *Var = cast<VarDecl>(VDecl.get());
1202 if (!Var->getTemplateSpecializationKind())
1203 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, MemberLoc);
1205 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc,
1206 SS.getWithLocInContext(Context), TemplateKWLoc, Var,
1207 FoundDecl, /*HadMultipleCandidates=*/false,
1208 MemberNameInfo, Var->getType().getNonReferenceType(),
1209 VK_LValue, OK_Ordinary, TemplateArgs);
1212 // We found something that we didn't expect. Complain.
1213 if (isa<TypeDecl>(MemberDecl))
1214 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1215 << MemberName << BaseType << int(IsArrow);
1216 else
1217 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1218 << MemberName << BaseType << int(IsArrow);
1220 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1221 << MemberName;
1222 R.suppressDiagnostics();
1223 return ExprError();
1226 /// Given that normal member access failed on the given expression,
1227 /// and given that the expression's type involves builtin-id or
1228 /// builtin-Class, decide whether substituting in the redefinition
1229 /// types would be profitable. The redefinition type is whatever
1230 /// this translation unit tried to typedef to id/Class; we store
1231 /// it to the side and then re-use it in places like this.
1232 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1233 const ObjCObjectPointerType *opty
1234 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1235 if (!opty) return false;
1237 const ObjCObjectType *ty = opty->getObjectType();
1239 QualType redef;
1240 if (ty->isObjCId()) {
1241 redef = S.Context.getObjCIdRedefinitionType();
1242 } else if (ty->isObjCClass()) {
1243 redef = S.Context.getObjCClassRedefinitionType();
1244 } else {
1245 return false;
1248 // Do the substitution as long as the redefinition type isn't just a
1249 // possibly-qualified pointer to builtin-id or builtin-Class again.
1250 opty = redef->getAs<ObjCObjectPointerType>();
1251 if (opty && !opty->getObjectType()->getInterface())
1252 return false;
1254 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1255 return true;
1258 static bool isRecordType(QualType T) {
1259 return T->isRecordType();
1261 static bool isPointerToRecordType(QualType T) {
1262 if (const PointerType *PT = T->getAs<PointerType>())
1263 return PT->getPointeeType()->isRecordType();
1264 return false;
1267 ExprResult
1268 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1269 if (IsArrow && !Base->getType()->isFunctionType())
1270 return DefaultFunctionArrayLvalueConversion(Base);
1272 return CheckPlaceholderExpr(Base);
1275 /// Look up the given member of the given non-type-dependent
1276 /// expression. This can return in one of two ways:
1277 /// * If it returns a sentinel null-but-valid result, the caller will
1278 /// assume that lookup was performed and the results written into
1279 /// the provided structure. It will take over from there.
1280 /// * Otherwise, the returned expression will be produced in place of
1281 /// an ordinary member expression.
1283 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1284 /// fixed for ObjC++.
1285 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1286 ExprResult &BaseExpr, bool &IsArrow,
1287 SourceLocation OpLoc, CXXScopeSpec &SS,
1288 Decl *ObjCImpDecl, bool HasTemplateArgs,
1289 SourceLocation TemplateKWLoc) {
1290 assert(BaseExpr.get() && "no base expression");
1292 // Perform default conversions.
1293 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1294 if (BaseExpr.isInvalid())
1295 return ExprError();
1297 QualType BaseType = BaseExpr.get()->getType();
1299 DeclarationName MemberName = R.getLookupName();
1300 SourceLocation MemberLoc = R.getNameLoc();
1302 // For later type-checking purposes, turn arrow accesses into dot
1303 // accesses. The only access type we support that doesn't follow
1304 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1305 // and those never use arrows, so this is unaffected.
1306 if (IsArrow) {
1307 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1308 BaseType = Ptr->getPointeeType();
1309 else if (const ObjCObjectPointerType *Ptr =
1310 BaseType->getAs<ObjCObjectPointerType>())
1311 BaseType = Ptr->getPointeeType();
1312 else if (BaseType->isFunctionType())
1313 goto fail;
1314 else if (BaseType->isDependentType())
1315 BaseType = S.Context.DependentTy;
1316 else if (BaseType->isRecordType()) {
1317 // Recover from arrow accesses to records, e.g.:
1318 // struct MyRecord foo;
1319 // foo->bar
1320 // This is actually well-formed in C++ if MyRecord has an
1321 // overloaded operator->, but that should have been dealt with
1322 // by now--or a diagnostic message already issued if a problem
1323 // was encountered while looking for the overloaded operator->.
1324 if (!S.getLangOpts().CPlusPlus) {
1325 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1326 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1327 << FixItHint::CreateReplacement(OpLoc, ".");
1329 IsArrow = false;
1330 } else {
1331 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1332 << BaseType << BaseExpr.get()->getSourceRange();
1333 return ExprError();
1337 // If the base type is an atomic type, this access is undefined behavior per
1338 // C11 6.5.2.3p5. Instead of giving a typecheck error, we'll warn the user
1339 // about the UB and recover by converting the atomic lvalue into a non-atomic
1340 // lvalue. Because this is inherently unsafe as an atomic operation, the
1341 // warning defaults to an error.
1342 if (const auto *ATy = BaseType->getAs<AtomicType>()) {
1343 S.DiagRuntimeBehavior(OpLoc, nullptr,
1344 S.PDiag(diag::warn_atomic_member_access));
1345 BaseType = ATy->getValueType().getUnqualifiedType();
1346 BaseExpr = ImplicitCastExpr::Create(
1347 S.Context, IsArrow ? S.Context.getPointerType(BaseType) : BaseType,
1348 CK_AtomicToNonAtomic, BaseExpr.get(), nullptr,
1349 BaseExpr.get()->getValueKind(), FPOptionsOverride());
1352 // Handle field access to simple records.
1353 if (BaseType->getAsRecordDecl()) {
1354 TypoExpr *TE = nullptr;
1355 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), BaseType, OpLoc, IsArrow,
1356 SS, HasTemplateArgs, TemplateKWLoc, TE))
1357 return ExprError();
1359 // Returning valid-but-null is how we indicate to the caller that
1360 // the lookup result was filled in. If typo correction was attempted and
1361 // failed, the lookup result will have been cleared--that combined with the
1362 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1363 return ExprResult(TE);
1364 } else if (BaseType->isDependentType()) {
1365 R.setNotFoundInCurrentInstantiation();
1366 return ExprEmpty();
1369 // Handle ivar access to Objective-C objects.
1370 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1371 if (!SS.isEmpty() && !SS.isInvalid()) {
1372 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1373 << 1 << SS.getScopeRep()
1374 << FixItHint::CreateRemoval(SS.getRange());
1375 SS.clear();
1378 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1380 // There are three cases for the base type:
1381 // - builtin id (qualified or unqualified)
1382 // - builtin Class (qualified or unqualified)
1383 // - an interface
1384 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1385 if (!IDecl) {
1386 if (S.getLangOpts().ObjCAutoRefCount &&
1387 (OTy->isObjCId() || OTy->isObjCClass()))
1388 goto fail;
1389 // There's an implicit 'isa' ivar on all objects.
1390 // But we only actually find it this way on objects of type 'id',
1391 // apparently.
1392 if (OTy->isObjCId() && Member->isStr("isa"))
1393 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1394 OpLoc, S.Context.getObjCClassType());
1395 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1396 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1397 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1398 goto fail;
1401 if (S.RequireCompleteType(OpLoc, BaseType,
1402 diag::err_typecheck_incomplete_tag,
1403 BaseExpr.get()))
1404 return ExprError();
1406 ObjCInterfaceDecl *ClassDeclared = nullptr;
1407 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1409 if (!IV) {
1410 // Attempt to correct for typos in ivar names.
1411 DeclFilterCCC<ObjCIvarDecl> Validator{};
1412 Validator.IsObjCIvarLookup = IsArrow;
1413 if (TypoCorrection Corrected = S.CorrectTypo(
1414 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
1415 Validator, Sema::CTK_ErrorRecovery, IDecl)) {
1416 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1417 S.diagnoseTypo(
1418 Corrected,
1419 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1420 << IDecl->getDeclName() << MemberName);
1422 // Figure out the class that declares the ivar.
1423 assert(!ClassDeclared);
1425 Decl *D = cast<Decl>(IV->getDeclContext());
1426 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1427 D = Category->getClassInterface();
1429 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1430 ClassDeclared = Implementation->getClassInterface();
1431 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1432 ClassDeclared = Interface;
1434 assert(ClassDeclared && "cannot query interface");
1435 } else {
1436 if (IsArrow &&
1437 IDecl->FindPropertyDeclaration(
1438 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1439 S.Diag(MemberLoc, diag::err_property_found_suggest)
1440 << Member << BaseExpr.get()->getType()
1441 << FixItHint::CreateReplacement(OpLoc, ".");
1442 return ExprError();
1445 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1446 << IDecl->getDeclName() << MemberName
1447 << BaseExpr.get()->getSourceRange();
1448 return ExprError();
1452 assert(ClassDeclared);
1454 // If the decl being referenced had an error, return an error for this
1455 // sub-expr without emitting another error, in order to avoid cascading
1456 // error cases.
1457 if (IV->isInvalidDecl())
1458 return ExprError();
1460 // Check whether we can reference this field.
1461 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
1462 return ExprError();
1463 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1464 IV->getAccessControl() != ObjCIvarDecl::Package) {
1465 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1466 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1467 ClassOfMethodDecl = MD->getClassInterface();
1468 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1469 // Case of a c-function declared inside an objc implementation.
1470 // FIXME: For a c-style function nested inside an objc implementation
1471 // class, there is no implementation context available, so we pass
1472 // down the context as argument to this routine. Ideally, this context
1473 // need be passed down in the AST node and somehow calculated from the
1474 // AST for a function decl.
1475 if (ObjCImplementationDecl *IMPD =
1476 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1477 ClassOfMethodDecl = IMPD->getClassInterface();
1478 else if (ObjCCategoryImplDecl* CatImplClass =
1479 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1480 ClassOfMethodDecl = CatImplClass->getClassInterface();
1482 if (!S.getLangOpts().DebuggerSupport) {
1483 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1484 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1485 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1486 S.Diag(MemberLoc, diag::err_private_ivar_access)
1487 << IV->getDeclName();
1488 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1489 // @protected
1490 S.Diag(MemberLoc, diag::err_protected_ivar_access)
1491 << IV->getDeclName();
1494 bool warn = true;
1495 if (S.getLangOpts().ObjCWeak) {
1496 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1497 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1498 if (UO->getOpcode() == UO_Deref)
1499 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1501 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1502 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1503 S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
1504 warn = false;
1507 if (warn) {
1508 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1509 ObjCMethodFamily MF = MD->getMethodFamily();
1510 warn = (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
1511 !S.ObjC().IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1513 if (warn)
1514 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1517 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1518 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1519 IsArrow);
1521 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1522 if (!S.isUnevaluatedContext() &&
1523 !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1524 S.getCurFunction()->recordUseOfWeak(Result);
1527 return Result;
1530 // Objective-C property access.
1531 const ObjCObjectPointerType *OPT;
1532 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1533 if (!SS.isEmpty() && !SS.isInvalid()) {
1534 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1535 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
1536 SS.clear();
1539 // This actually uses the base as an r-value.
1540 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1541 if (BaseExpr.isInvalid())
1542 return ExprError();
1544 assert(S.Context.hasSameUnqualifiedType(BaseType,
1545 BaseExpr.get()->getType()));
1547 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1549 const ObjCObjectType *OT = OPT->getObjectType();
1551 // id, with and without qualifiers.
1552 if (OT->isObjCId()) {
1553 // Check protocols on qualified interfaces.
1554 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1555 if (Decl *PMDecl =
1556 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
1557 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1558 // Check the use of this declaration
1559 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
1560 return ExprError();
1562 return new (S.Context)
1563 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1564 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1567 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1568 Selector SetterSel =
1569 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1570 S.PP.getSelectorTable(),
1571 Member);
1572 ObjCMethodDecl *SMD = nullptr;
1573 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1574 /*Property id*/ nullptr,
1575 SetterSel, S.Context))
1576 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1578 return new (S.Context)
1579 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1580 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1583 // Use of id.member can only be for a property reference. Do not
1584 // use the 'id' redefinition in this case.
1585 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1586 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1587 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1589 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1590 << MemberName << BaseType);
1593 // 'Class', unqualified only.
1594 if (OT->isObjCClass()) {
1595 // Only works in a method declaration (??!).
1596 ObjCMethodDecl *MD = S.getCurMethodDecl();
1597 if (!MD) {
1598 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1599 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1600 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1602 goto fail;
1605 // Also must look for a getter name which uses property syntax.
1606 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1607 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1608 if (!IFace)
1609 goto fail;
1611 ObjCMethodDecl *Getter;
1612 if ((Getter = IFace->lookupClassMethod(Sel))) {
1613 // Check the use of this method.
1614 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
1615 return ExprError();
1616 } else
1617 Getter = IFace->lookupPrivateMethod(Sel, false);
1618 // If we found a getter then this may be a valid dot-reference, we
1619 // will look for the matching setter, in case it is needed.
1620 Selector SetterSel =
1621 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1622 S.PP.getSelectorTable(),
1623 Member);
1624 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1625 if (!Setter) {
1626 // If this reference is in an @implementation, also check for 'private'
1627 // methods.
1628 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1631 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1632 return ExprError();
1634 if (Getter || Setter) {
1635 return new (S.Context) ObjCPropertyRefExpr(
1636 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1637 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1640 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1641 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1642 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1644 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1645 << MemberName << BaseType);
1648 // Normal property access.
1649 return S.ObjC().HandleExprPropertyRefExpr(
1650 OPT, BaseExpr.get(), OpLoc, MemberName, MemberLoc, SourceLocation(),
1651 QualType(), false);
1654 if (BaseType->isExtVectorBoolType()) {
1655 // We disallow element access for ext_vector_type bool. There is no way to
1656 // materialize a reference to a vector element as a pointer (each element is
1657 // one bit in the vector).
1658 S.Diag(R.getNameLoc(), diag::err_ext_vector_component_name_illegal)
1659 << MemberName
1660 << (BaseExpr.get() ? BaseExpr.get()->getSourceRange() : SourceRange());
1661 return ExprError();
1664 // Handle 'field access' to vectors, such as 'V.xx'.
1665 if (BaseType->isExtVectorType()) {
1666 // FIXME: this expr should store IsArrow.
1667 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1668 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1669 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1670 Member, MemberLoc);
1671 if (ret.isNull())
1672 return ExprError();
1673 Qualifiers BaseQ =
1674 S.Context.getCanonicalType(BaseExpr.get()->getType()).getQualifiers();
1675 ret = S.Context.getQualifiedType(ret, BaseQ);
1677 return new (S.Context)
1678 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1681 // Adjust builtin-sel to the appropriate redefinition type if that's
1682 // not just a pointer to builtin-sel again.
1683 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1684 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1685 BaseExpr = S.ImpCastExprToType(
1686 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1687 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1688 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1691 // Failure cases.
1692 fail:
1694 // Recover from dot accesses to pointers, e.g.:
1695 // type *foo;
1696 // foo.bar
1697 // This is actually well-formed in two cases:
1698 // - 'type' is an Objective C type
1699 // - 'bar' is a pseudo-destructor name which happens to refer to
1700 // the appropriate pointer type
1701 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1702 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1703 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1704 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1705 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1706 << FixItHint::CreateReplacement(OpLoc, "->");
1708 if (S.isSFINAEContext())
1709 return ExprError();
1711 // Recurse as an -> access.
1712 IsArrow = true;
1713 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1714 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1718 // If the user is trying to apply -> or . to a function name, it's probably
1719 // because they forgot parentheses to call that function.
1720 if (S.tryToRecoverWithCall(
1721 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1722 /*complain*/ false,
1723 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1724 if (BaseExpr.isInvalid())
1725 return ExprError();
1726 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1727 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1728 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1731 // HLSL supports implicit conversion of scalar types to single element vector
1732 // rvalues in member expressions.
1733 if (S.getLangOpts().HLSL && BaseType->isScalarType()) {
1734 QualType VectorTy = S.Context.getExtVectorType(BaseType, 1);
1735 BaseExpr = S.ImpCastExprToType(BaseExpr.get(), VectorTy, CK_VectorSplat,
1736 BaseExpr.get()->getValueKind());
1737 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, ObjCImpDecl,
1738 HasTemplateArgs, TemplateKWLoc);
1741 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1742 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1744 return ExprError();
1747 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1748 SourceLocation OpLoc,
1749 tok::TokenKind OpKind, CXXScopeSpec &SS,
1750 SourceLocation TemplateKWLoc,
1751 UnqualifiedId &Id, Decl *ObjCImpDecl) {
1752 // Warn about the explicit constructor calls Microsoft extension.
1753 if (getLangOpts().MicrosoftExt &&
1754 Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
1755 Diag(Id.getSourceRange().getBegin(),
1756 diag::ext_ms_explicit_constructor_call);
1758 TemplateArgumentListInfo TemplateArgsBuffer;
1760 // Decompose the name into its component parts.
1761 DeclarationNameInfo NameInfo;
1762 const TemplateArgumentListInfo *TemplateArgs;
1763 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1764 NameInfo, TemplateArgs);
1766 bool IsArrow = (OpKind == tok::arrow);
1768 if (getLangOpts().HLSL && IsArrow)
1769 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 2);
1771 NamedDecl *FirstQualifierInScope
1772 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
1774 // This is a postfix expression, so get rid of ParenListExprs.
1775 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1776 if (Result.isInvalid()) return ExprError();
1777 Base = Result.get();
1779 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1780 ExprResult Res = BuildMemberReferenceExpr(
1781 Base, Base->getType(), OpLoc, IsArrow, SS, TemplateKWLoc,
1782 FirstQualifierInScope, NameInfo, TemplateArgs, S, &ExtraArgs);
1784 if (!Res.isInvalid() && isa<MemberExpr>(Res.get()))
1785 CheckMemberAccessOfNoDeref(cast<MemberExpr>(Res.get()));
1787 return Res;
1790 void Sema::CheckMemberAccessOfNoDeref(const MemberExpr *E) {
1791 if (isUnevaluatedContext())
1792 return;
1794 QualType ResultTy = E->getType();
1796 // Member accesses have four cases:
1797 // 1: non-array member via "->": dereferences
1798 // 2: non-array member via ".": nothing interesting happens
1799 // 3: array member access via "->": nothing interesting happens
1800 // (this returns an array lvalue and does not actually dereference memory)
1801 // 4: array member access via ".": *adds* a layer of indirection
1802 if (ResultTy->isArrayType()) {
1803 if (!E->isArrow()) {
1804 // This might be something like:
1805 // (*structPtr).arrayMember
1806 // which behaves roughly like:
1807 // &(*structPtr).pointerMember
1808 // in that the apparent dereference in the base expression does not
1809 // actually happen.
1810 CheckAddressOfNoDeref(E->getBase());
1812 } else if (E->isArrow()) {
1813 if (const auto *Ptr = dyn_cast<PointerType>(
1814 E->getBase()->getType().getDesugaredType(Context))) {
1815 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
1816 ExprEvalContexts.back().PossibleDerefs.insert(E);
1821 ExprResult
1822 Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1823 SourceLocation OpLoc, const CXXScopeSpec &SS,
1824 FieldDecl *Field, DeclAccessPair FoundDecl,
1825 const DeclarationNameInfo &MemberNameInfo) {
1826 // x.a is an l-value if 'a' has a reference type. Otherwise:
1827 // x.a is an l-value/x-value/pr-value if the base is (and note
1828 // that *x is always an l-value), except that if the base isn't
1829 // an ordinary object then we must have an rvalue.
1830 ExprValueKind VK = VK_LValue;
1831 ExprObjectKind OK = OK_Ordinary;
1832 if (!IsArrow) {
1833 if (BaseExpr->getObjectKind() == OK_Ordinary)
1834 VK = BaseExpr->getValueKind();
1835 else
1836 VK = VK_PRValue;
1838 if (VK != VK_PRValue && Field->isBitField())
1839 OK = OK_BitField;
1841 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1842 QualType MemberType = Field->getType();
1843 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1844 MemberType = Ref->getPointeeType();
1845 VK = VK_LValue;
1846 } else {
1847 QualType BaseType = BaseExpr->getType();
1848 if (IsArrow) BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1850 Qualifiers BaseQuals = BaseType.getQualifiers();
1852 // GC attributes are never picked up by members.
1853 BaseQuals.removeObjCGCAttr();
1855 // CVR attributes from the base are picked up by members,
1856 // except that 'mutable' members don't pick up 'const'.
1857 if (Field->isMutable()) BaseQuals.removeConst();
1859 Qualifiers MemberQuals =
1860 Context.getCanonicalType(MemberType).getQualifiers();
1862 assert(!MemberQuals.hasAddressSpace());
1864 Qualifiers Combined = BaseQuals + MemberQuals;
1865 if (Combined != MemberQuals)
1866 MemberType = Context.getQualifiedType(MemberType, Combined);
1868 // Pick up NoDeref from the base in case we end up using AddrOf on the
1869 // result. E.g. the expression
1870 // &someNoDerefPtr->pointerMember
1871 // should be a noderef pointer again.
1872 if (BaseType->hasAttr(attr::NoDeref))
1873 MemberType =
1874 Context.getAttributedType(attr::NoDeref, MemberType, MemberType);
1877 auto isDefaultedSpecialMember = [this](const DeclContext *Ctx) {
1878 auto *Method = dyn_cast<CXXMethodDecl>(CurContext);
1879 if (!Method || !Method->isDefaulted())
1880 return false;
1882 return getDefaultedFunctionKind(Method).isSpecialMember();
1885 // Implicit special members should not mark fields as used.
1886 if (!isDefaultedSpecialMember(CurContext))
1887 UnusedPrivateFields.remove(Field);
1889 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1890 FoundDecl, Field);
1891 if (Base.isInvalid())
1892 return ExprError();
1894 // Build a reference to a private copy for non-static data members in
1895 // non-static member functions, privatized by OpenMP constructs.
1896 if (getLangOpts().OpenMP && IsArrow &&
1897 !CurContext->isDependentContext() &&
1898 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
1899 if (auto *PrivateCopy = OpenMP().isOpenMPCapturedDecl(Field)) {
1900 return OpenMP().getOpenMPCapturedExpr(PrivateCopy, VK, OK,
1901 MemberNameInfo.getLoc());
1905 return BuildMemberExpr(
1906 Base.get(), IsArrow, OpLoc, SS.getWithLocInContext(Context),
1907 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1908 /*HadMultipleCandidates=*/false, MemberNameInfo, MemberType, VK, OK);
1911 ExprResult
1912 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1913 SourceLocation TemplateKWLoc,
1914 LookupResult &R,
1915 const TemplateArgumentListInfo *TemplateArgs,
1916 bool IsKnownInstance, const Scope *S) {
1917 assert(!R.empty() && !R.isAmbiguous());
1919 SourceLocation loc = R.getNameLoc();
1921 // If this is known to be an instance access, go ahead and build an
1922 // implicit 'this' expression now.
1923 QualType ThisTy = getCurrentThisType();
1924 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1926 Expr *baseExpr = nullptr; // null signifies implicit access
1927 if (IsKnownInstance) {
1928 SourceLocation Loc = R.getNameLoc();
1929 if (SS.getRange().isValid())
1930 Loc = SS.getRange().getBegin();
1931 baseExpr = BuildCXXThisExpr(loc, ThisTy, /*IsImplicit=*/true);
1934 return BuildMemberReferenceExpr(
1935 baseExpr, ThisTy,
1936 /*OpLoc=*/SourceLocation(),
1937 /*IsArrow=*/!getLangOpts().HLSL, SS, TemplateKWLoc,
1938 /*FirstQualifierInScope=*/nullptr, R, TemplateArgs, S);