1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis member access expressions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/ScopeInfo.h"
24 #include "clang/Sema/SemaInternal.h"
26 using namespace clang;
29 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
31 /// Determines if the given class is provably not derived from all of
32 /// the prospective base classes.
33 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
34 const BaseSet &Bases) {
35 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
36 return !Bases.count(Base->getCanonicalDecl());
38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
42 /// The reference is definitely not an instance member access.
45 /// The reference may be an implicit instance member access.
48 /// The reference may be to an instance member, but it might be invalid if
49 /// so, because the context is not an instance method.
50 IMA_Mixed_StaticContext,
52 /// The reference may be to an instance member, but it is invalid if
53 /// so, because the context is from an unrelated class.
56 /// The reference is definitely an implicit instance member access.
59 /// The reference may be to an unresolved using declaration.
62 /// The reference is a contextually-permitted abstract member reference.
65 /// The reference may be to an unresolved using declaration and the
66 /// context is not an instance method.
67 IMA_Unresolved_StaticContext,
69 // The reference refers to a field which is not a member of the containing
70 // class, which is allowed because we're in C++11 mode and the context is
72 IMA_Field_Uneval_Context,
74 /// All possible referrents are instance members and the current
75 /// context is not an instance method.
76 IMA_Error_StaticContext,
78 /// All possible referrents are instance members of an unrelated
83 /// The given lookup names class member(s) and is not being used for
84 /// an address-of-member expression. Classify the type of access
85 /// according to whether it's possible that this reference names an
86 /// instance member. This is best-effort in dependent contexts; it is okay to
87 /// conservatively answer "yes", in which case some errors will simply
88 /// not be caught until template-instantiation.
89 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
90 const LookupResult &R) {
91 assert(!R.empty() && (*R.begin())->isCXXClassMember());
93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
95 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
98 if (R.isUnresolvableResult())
99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
101 // Collect all the declaring classes of instance members we find.
102 bool hasNonInstance = false;
103 bool isField = false;
105 for (NamedDecl *D : R) {
106 // Look through any using decls.
107 D = D->getUnderlyingDecl();
109 if (D->isCXXInstanceMember()) {
110 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
111 isa<IndirectFieldDecl>(D);
113 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
114 Classes.insert(R->getCanonicalDecl());
116 hasNonInstance = true;
119 // If we didn't find any instance members, it can't be an implicit
124 // C++11 [expr.prim.general]p12:
125 // An id-expression that denotes a non-static data member or non-static
126 // member function of a class can only be used:
128 // - if that id-expression denotes a non-static data member and it
129 // appears in an unevaluated operand.
131 // This rule is specific to C++11. However, we also permit this form
132 // in unevaluated inline assembly operands, like the operand to a SIZE.
133 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
134 assert(!AbstractInstanceResult);
135 switch (SemaRef.ExprEvalContexts.back().Context) {
136 case Sema::Unevaluated:
137 if (isField && SemaRef.getLangOpts().CPlusPlus11)
138 AbstractInstanceResult = IMA_Field_Uneval_Context;
141 case Sema::UnevaluatedAbstract:
142 AbstractInstanceResult = IMA_Abstract;
145 case Sema::DiscardedStatement:
146 case Sema::ConstantEvaluated:
147 case Sema::PotentiallyEvaluated:
148 case Sema::PotentiallyEvaluatedIfUsed:
152 // If the current context is not an instance method, it can't be
153 // an implicit member reference.
154 if (isStaticContext) {
156 return IMA_Mixed_StaticContext;
158 return AbstractInstanceResult ? AbstractInstanceResult
159 : IMA_Error_StaticContext;
162 CXXRecordDecl *contextClass;
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
164 contextClass = MD->getParent()->getCanonicalDecl();
166 contextClass = cast<CXXRecordDecl>(DC);
168 // [class.mfct.non-static]p3:
169 // ...is used in the body of a non-static member function of class X,
170 // if name lookup (3.4.1) resolves the name in the id-expression to a
171 // non-static non-type member of some class C [...]
172 // ...if C is not X or a base class of X, the class member access expression
174 if (R.getNamingClass() &&
175 contextClass->getCanonicalDecl() !=
176 R.getNamingClass()->getCanonicalDecl()) {
177 // If the naming class is not the current context, this was a qualified
178 // member name lookup, and it's sufficient to check that we have the naming
179 // class as a base class.
181 Classes.insert(R.getNamingClass()->getCanonicalDecl());
184 // If we can prove that the current context is unrelated to all the
185 // declaring classes, it can't be an implicit member reference (in
186 // which case it's an error if any of those members are selected).
187 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
188 return hasNonInstance ? IMA_Mixed_Unrelated :
189 AbstractInstanceResult ? AbstractInstanceResult :
192 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
195 /// Diagnose a reference to a field with no object available.
196 static void diagnoseInstanceReference(Sema &SemaRef,
197 const CXXScopeSpec &SS,
199 const DeclarationNameInfo &nameInfo) {
200 SourceLocation Loc = nameInfo.getLoc();
201 SourceRange Range(Loc);
202 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
204 // Look through using shadow decls and aliases.
205 Rep = Rep->getUnderlyingDecl();
207 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
209 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
210 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
212 bool InStaticMethod = Method && Method->isStatic();
213 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
215 if (IsField && InStaticMethod)
216 // "invalid use of member 'x' in static member function"
217 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
218 << Range << nameInfo.getName();
219 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
220 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
221 // Unqualified lookup in a non-static member function found a member of an
223 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
224 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
226 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
227 << nameInfo.getName() << Range;
229 SemaRef.Diag(Loc, diag::err_member_call_without_object)
233 /// Builds an expression which might be an implicit member expression.
235 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
236 SourceLocation TemplateKWLoc,
238 const TemplateArgumentListInfo *TemplateArgs,
240 switch (ClassifyImplicitMemberAccess(*this, R)) {
242 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
245 case IMA_Mixed_Unrelated:
247 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
256 case IMA_Mixed_StaticContext:
257 case IMA_Unresolved_StaticContext:
258 if (TemplateArgs || TemplateKWLoc.isValid())
259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
260 return BuildDeclarationNameExpr(SS, R, false);
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
265 R.getLookupNameInfo());
269 llvm_unreachable("unexpected instance member access kind");
272 /// Check an ext-vector component access expression.
274 /// VK should be set in advance to the value kind of the base
277 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
278 SourceLocation OpLoc, const IdentifierInfo *CompName,
279 SourceLocation CompLoc) {
280 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
283 // FIXME: This logic can be greatly simplified by splitting it along
284 // halving/not halving and reworking the component checking.
285 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
287 // The vector accessor can't exceed the number of elements.
288 const char *compStr = CompName->getNameStart();
290 // This flag determines whether or not the component is one of the four
291 // special names that indicate a subset of exactly half the elements are
293 bool HalvingSwizzle = false;
295 // This flag determines whether or not CompName has an 's' char prefix,
296 // indicating that it is a string of hex values to be used as vector indices.
297 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
299 bool HasRepeated = false;
300 bool HasIndex[16] = {};
304 // Check that we've found one of the special components, or that the component
305 // names must come from the same set.
306 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
307 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
308 HalvingSwizzle = true;
309 } else if (!HexSwizzle &&
310 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
312 if (HasIndex[Idx]) HasRepeated = true;
313 HasIndex[Idx] = true;
315 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
317 if (HexSwizzle) compStr++;
318 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
319 if (HasIndex[Idx]) HasRepeated = true;
320 HasIndex[Idx] = true;
325 if (!HalvingSwizzle && *compStr) {
326 // We didn't get to the end of the string. This means the component names
327 // didn't come from the same set *or* we encountered an illegal name.
328 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
329 << StringRef(compStr, 1) << SourceRange(CompLoc);
333 // Ensure no component accessor exceeds the width of the vector type it
335 if (!HalvingSwizzle) {
336 compStr = CompName->getNameStart();
342 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
343 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
344 << baseType << SourceRange(CompLoc);
350 // The component accessor looks fine - now we need to compute the actual type.
351 // The vector type is implied by the component accessor. For example,
352 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
353 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
354 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
355 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
356 : CompName->getLength();
361 return vecType->getElementType();
363 if (HasRepeated) VK = VK_RValue;
365 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
366 // Now look up the TypeDefDecl from the vector type. Without this,
367 // diagostics look bad. We want extended vector types to appear built-in.
368 for (Sema::ExtVectorDeclsType::iterator
369 I = S.ExtVectorDecls.begin(S.getExternalSource()),
370 E = S.ExtVectorDecls.end();
372 if ((*I)->getUnderlyingType() == VT)
373 return S.Context.getTypedefType(*I);
376 return VT; // should never get here (a typedef type should always be found).
379 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
380 IdentifierInfo *Member,
382 ASTContext &Context) {
384 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
385 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
387 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
390 for (const auto *I : PDecl->protocols()) {
391 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
398 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
399 IdentifierInfo *Member,
401 ASTContext &Context) {
402 // Check protocols on qualified interfaces.
403 Decl *GDecl = nullptr;
404 for (const auto *I : QIdTy->quals()) {
406 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
407 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
411 // Also must look for a getter or setter name which uses property syntax.
412 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
418 for (const auto *I : QIdTy->quals()) {
419 // Search in the protocol-qualifier list of current protocol.
420 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
429 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
430 bool IsArrow, SourceLocation OpLoc,
431 const CXXScopeSpec &SS,
432 SourceLocation TemplateKWLoc,
433 NamedDecl *FirstQualifierInScope,
434 const DeclarationNameInfo &NameInfo,
435 const TemplateArgumentListInfo *TemplateArgs) {
436 // Even in dependent contexts, try to diagnose base expressions with
437 // obviously wrong types, e.g.:
442 // In Obj-C++, however, the above expression is valid, since it could be
443 // accessing the 'f' property if T is an Obj-C interface. The extra check
444 // allows this, while still reporting an error if T is a struct pointer.
446 const PointerType *PT = BaseType->getAs<PointerType>();
447 if (PT && (!getLangOpts().ObjC1 ||
448 PT->getPointeeType()->isRecordType())) {
449 assert(BaseExpr && "cannot happen with implicit member accesses");
450 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
451 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
456 assert(BaseType->isDependentType() ||
457 NameInfo.getName().isDependentName() ||
458 isDependentScopeSpecifier(SS));
460 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
461 // must have pointer type, and the accessed type is the pointee.
462 return CXXDependentScopeMemberExpr::Create(
463 Context, BaseExpr, BaseType, IsArrow, OpLoc,
464 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
465 NameInfo, TemplateArgs);
468 /// We know that the given qualified member reference points only to
469 /// declarations which do not belong to the static type of the base
470 /// expression. Diagnose the problem.
471 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
474 const CXXScopeSpec &SS,
476 const DeclarationNameInfo &nameInfo) {
477 // If this is an implicit member access, use a different set of
480 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
482 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
483 << SS.getRange() << rep << BaseType;
486 // Check whether the declarations we found through a nested-name
487 // specifier in a member expression are actually members of the base
488 // type. The restriction here is:
491 // ... In these cases, the id-expression shall name a
492 // member of the class or of one of its base classes.
494 // So it's perfectly legitimate for the nested-name specifier to name
495 // an unrelated class, and for us to find an overload set including
496 // decls from classes which are not superclasses, as long as the decl
497 // we actually pick through overload resolution is from a superclass.
498 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
500 const CXXScopeSpec &SS,
501 const LookupResult &R) {
502 CXXRecordDecl *BaseRecord =
503 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
505 // We can't check this yet because the base type is still
507 assert(BaseType->isDependentType());
511 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
512 // If this is an implicit member reference and we find a
513 // non-instance member, it's not an error.
514 if (!BaseExpr && !(*I)->isCXXInstanceMember())
517 // Note that we use the DC of the decl, not the underlying decl.
518 DeclContext *DC = (*I)->getDeclContext();
519 while (DC->isTransparentContext())
520 DC = DC->getParent();
525 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
526 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
527 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
531 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
532 R.getRepresentativeDecl(),
533 R.getLookupNameInfo());
539 // Callback to only accept typo corrections that are either a ValueDecl or a
540 // FunctionTemplateDecl and are declared in the current record or, for a C++
541 // classes, one of its base classes.
542 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
544 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
545 : Record(RTy->getDecl()) {
546 // Don't add bare keywords to the consumer since they will always fail
547 // validation by virtue of not being associated with any decls.
548 WantTypeSpecifiers = false;
549 WantExpressionKeywords = false;
550 WantCXXNamedCasts = false;
551 WantFunctionLikeCasts = false;
552 WantRemainingKeywords = false;
555 bool ValidateCandidate(const TypoCorrection &candidate) override {
556 NamedDecl *ND = candidate.getCorrectionDecl();
557 // Don't accept candidates that cannot be member functions, constants,
558 // variables, or templates.
559 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
562 // Accept candidates that occur in the current record.
563 if (Record->containsDecl(ND))
566 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
567 // Accept candidates that occur in any of the current class' base classes.
568 for (const auto &BS : RD->bases()) {
569 if (const RecordType *BSTy =
570 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
571 if (BSTy->getDecl()->containsDecl(ND))
581 const RecordDecl *const Record;
586 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
588 const RecordType *RTy,
589 SourceLocation OpLoc, bool IsArrow,
590 CXXScopeSpec &SS, bool HasTemplateArgs,
592 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
593 RecordDecl *RDecl = RTy->getDecl();
594 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
595 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
596 diag::err_typecheck_incomplete_tag,
600 if (HasTemplateArgs) {
601 // LookupTemplateName doesn't expect these both to exist simultaneously.
602 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
605 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
609 DeclContext *DC = RDecl;
611 // If the member name was a qualified-id, look into the
612 // nested-name-specifier.
613 DC = SemaRef.computeDeclContext(SS, false);
615 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
616 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
617 << SS.getRange() << DC;
621 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
623 if (!isa<TypeDecl>(DC)) {
624 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
625 << DC << SS.getRange();
630 // The record definition is complete, now look up the member.
631 SemaRef.LookupQualifiedName(R, DC, SS);
636 DeclarationName Typo = R.getLookupName();
637 SourceLocation TypoLoc = R.getNameLoc();
641 DeclarationNameInfo NameInfo;
642 Sema::LookupNameKind LookupKind;
643 Sema::RedeclarationKind Redecl;
645 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
646 R.isForRedeclaration() ? Sema::ForRedeclaration
647 : Sema::NotForRedeclaration};
648 TE = SemaRef.CorrectTypoDelayed(
649 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
650 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
651 [=, &SemaRef](const TypoCorrection &TC) {
653 assert(!TC.isKeyword() &&
654 "Got a keyword as a correction for a member!");
655 bool DroppedSpecifier =
656 TC.WillReplaceSpecifier() &&
657 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
658 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
659 << Typo << DC << DroppedSpecifier
662 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
665 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
666 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
667 R.clear(); // Ensure there's no decls lingering in the shared state.
668 R.suppressDiagnostics();
669 R.setLookupName(TC.getCorrection());
670 for (NamedDecl *ND : TC)
673 return SemaRef.BuildMemberReferenceExpr(
674 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
675 nullptr, R, nullptr, nullptr);
677 Sema::CTK_ErrorRecovery, DC);
682 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
683 ExprResult &BaseExpr, bool &IsArrow,
684 SourceLocation OpLoc, CXXScopeSpec &SS,
685 Decl *ObjCImpDecl, bool HasTemplateArgs);
688 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
689 SourceLocation OpLoc, bool IsArrow,
691 SourceLocation TemplateKWLoc,
692 NamedDecl *FirstQualifierInScope,
693 const DeclarationNameInfo &NameInfo,
694 const TemplateArgumentListInfo *TemplateArgs,
696 ActOnMemberAccessExtraArgs *ExtraArgs) {
697 if (BaseType->isDependentType() ||
698 (SS.isSet() && isDependentScopeSpecifier(SS)))
699 return ActOnDependentMemberExpr(Base, BaseType,
701 SS, TemplateKWLoc, FirstQualifierInScope,
702 NameInfo, TemplateArgs);
704 LookupResult R(*this, NameInfo, LookupMemberName);
706 // Implicit member accesses.
708 TypoExpr *TE = nullptr;
709 QualType RecordTy = BaseType;
710 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
711 if (LookupMemberExprInRecord(*this, R, nullptr,
712 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
713 SS, TemplateArgs != nullptr, TE))
718 // Explicit member accesses.
720 ExprResult BaseResult = Base;
721 ExprResult Result = LookupMemberExpr(
722 *this, R, BaseResult, IsArrow, OpLoc, SS,
723 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
724 TemplateArgs != nullptr);
726 if (BaseResult.isInvalid())
728 Base = BaseResult.get();
730 if (Result.isInvalid())
736 // LookupMemberExpr can modify Base, and thus change BaseType
737 BaseType = Base->getType();
740 return BuildMemberReferenceExpr(Base, BaseType,
741 OpLoc, IsArrow, SS, TemplateKWLoc,
742 FirstQualifierInScope, R, TemplateArgs, S,
747 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
748 SourceLocation OpLoc, const CXXScopeSpec &SS,
749 FieldDecl *Field, DeclAccessPair FoundDecl,
750 const DeclarationNameInfo &MemberNameInfo);
753 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
755 IndirectFieldDecl *indirectField,
756 DeclAccessPair foundDecl,
757 Expr *baseObjectExpr,
758 SourceLocation opLoc) {
759 // First, build the expression that refers to the base object.
761 bool baseObjectIsPointer = false;
762 Qualifiers baseQuals;
764 // Case 1: the base of the indirect field is not a field.
765 VarDecl *baseVariable = indirectField->getVarDecl();
766 CXXScopeSpec EmptySS;
768 assert(baseVariable->getType()->isRecordType());
770 // In principle we could have a member access expression that
771 // accesses an anonymous struct/union that's a static member of
772 // the base object's class. However, under the current standard,
773 // static data members cannot be anonymous structs or unions.
774 // Supporting this is as easy as building a MemberExpr here.
775 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
777 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
780 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
781 if (result.isInvalid()) return ExprError();
783 baseObjectExpr = result.get();
784 baseObjectIsPointer = false;
785 baseQuals = baseObjectExpr->getType().getQualifiers();
787 // Case 2: the base of the indirect field is a field and the user
788 // wrote a member expression.
789 } else if (baseObjectExpr) {
790 // The caller provided the base object expression. Determine
791 // whether its a pointer and whether it adds any qualifiers to the
792 // anonymous struct/union fields we're looking into.
793 QualType objectType = baseObjectExpr->getType();
795 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
796 baseObjectIsPointer = true;
797 objectType = ptr->getPointeeType();
799 baseObjectIsPointer = false;
801 baseQuals = objectType.getQualifiers();
803 // Case 3: the base of the indirect field is a field and we should
804 // build an implicit member access.
806 // We've found a member of an anonymous struct/union that is
807 // inside a non-anonymous struct/union, so in a well-formed
808 // program our base object expression is "this".
809 QualType ThisTy = getCurrentThisType();
810 if (ThisTy.isNull()) {
811 Diag(loc, diag::err_invalid_member_use_in_static_method)
812 << indirectField->getDeclName();
816 // Our base object expression is "this".
817 CheckCXXThisCapture(loc);
819 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
820 baseObjectIsPointer = true;
821 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
824 // Build the implicit member references to the field of the
825 // anonymous struct/union.
826 Expr *result = baseObjectExpr;
827 IndirectFieldDecl::chain_iterator
828 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
830 // Build the first member access in the chain with full information.
832 FieldDecl *field = cast<FieldDecl>(*FI);
834 // Make a nameInfo that properly uses the anonymous name.
835 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
837 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
838 SourceLocation(), EmptySS, field,
839 foundDecl, memberNameInfo).get();
843 // FIXME: check qualified member access
846 // In all cases, we should now skip the first declaration in the chain.
850 FieldDecl *field = cast<FieldDecl>(*FI++);
852 // FIXME: these are somewhat meaningless
853 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
854 DeclAccessPair fakeFoundDecl =
855 DeclAccessPair::make(field, field->getAccess());
858 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
859 SourceLocation(), (FI == FEnd ? SS : EmptySS),
860 field, fakeFoundDecl, memberNameInfo).get();
867 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
868 const CXXScopeSpec &SS,
870 const DeclarationNameInfo &NameInfo) {
871 // Property names are always simple identifiers and therefore never
872 // require any interesting additional storage.
873 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
874 S.Context.PseudoObjectTy, VK_LValue,
875 SS.getWithLocInContext(S.Context),
879 /// \brief Build a MemberExpr AST node.
880 static MemberExpr *BuildMemberExpr(
881 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
882 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
883 ValueDecl *Member, DeclAccessPair FoundDecl,
884 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
885 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
886 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
887 MemberExpr *E = MemberExpr::Create(
888 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
889 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
890 SemaRef.MarkMemberReferenced(E);
894 /// \brief Determine if the given scope is within a function-try-block handler.
895 static bool IsInFnTryBlockHandler(const Scope *S) {
896 // Walk the scope stack until finding a FnTryCatchScope, or leave the
897 // function scope. If a FnTryCatchScope is found, check whether the TryScope
898 // flag is set. If it is not, it's a function-try-block handler.
899 for (; S != S->getFnParent(); S = S->getParent()) {
900 if (S->getFlags() & Scope::FnTryCatchScope)
901 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
907 getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
908 const TemplateArgumentListInfo *TemplateArgs,
909 const DeclarationNameInfo &MemberNameInfo,
910 SourceLocation TemplateKWLoc) {
913 S.Diag(MemberNameInfo.getBeginLoc(), diag::err_template_decl_ref)
914 << /*Variable template*/ 1 << MemberNameInfo.getName()
915 << MemberNameInfo.getSourceRange();
917 S.Diag(VarTempl->getLocation(), diag::note_template_decl_here);
921 DeclResult VDecl = S.CheckVarTemplateId(
922 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
923 if (VDecl.isInvalid())
925 VarDecl *Var = cast<VarDecl>(VDecl.get());
926 if (!Var->getTemplateSpecializationKind())
927 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
928 MemberNameInfo.getLoc());
933 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
934 SourceLocation OpLoc, bool IsArrow,
935 const CXXScopeSpec &SS,
936 SourceLocation TemplateKWLoc,
937 NamedDecl *FirstQualifierInScope,
939 const TemplateArgumentListInfo *TemplateArgs,
941 bool SuppressQualifierCheck,
942 ActOnMemberAccessExtraArgs *ExtraArgs) {
943 QualType BaseType = BaseExprType;
945 assert(BaseType->isPointerType());
946 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
948 R.setBaseObjectType(BaseType);
950 LambdaScopeInfo *const CurLSI = getCurLambda();
951 // If this is an implicit member reference and the overloaded
952 // name refers to both static and non-static member functions
953 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
954 // check if we should/can capture 'this'...
955 // Keep this example in mind:
958 // static void f(double) { }
961 // auto L = [=](auto a) {
962 // return [](int i) {
963 // return [=](auto b) {
965 // //f(decltype(a){});
971 // N(5.32); // OK, must not error.
976 if (!BaseExpr && CurLSI) {
977 SourceLocation Loc = R.getNameLoc();
978 if (SS.getRange().isValid())
979 Loc = SS.getRange().getBegin();
980 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
981 // If the enclosing function is not dependent, then this lambda is
982 // capture ready, so if we can capture this, do so.
983 if (!EnclosingFunctionCtx->isDependentContext()) {
984 // If the current lambda and all enclosing lambdas can capture 'this' -
985 // then go ahead and capture 'this' (since our unresolved overload set
986 // contains both static and non-static member functions).
987 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
988 CheckCXXThisCapture(Loc);
989 } else if (CurContext->isDependentContext()) {
990 // ... since this is an implicit member reference, that might potentially
991 // involve a 'this' capture, mark 'this' for potential capture in
992 // enclosing lambdas.
993 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
994 CurLSI->addPotentialThisCapture(Loc);
997 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
998 DeclarationName MemberName = MemberNameInfo.getName();
999 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1001 if (R.isAmbiguous())
1004 // [except.handle]p10: Referring to any non-static member or base class of an
1005 // object in the handler for a function-try-block of a constructor or
1006 // destructor for that object results in undefined behavior.
1007 const auto *FD = getCurFunctionDecl();
1008 if (S && BaseExpr && FD &&
1009 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1010 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1011 IsInFnTryBlockHandler(S))
1012 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1013 << isa<CXXDestructorDecl>(FD);
1016 // Rederive where we looked up.
1017 DeclContext *DC = (SS.isSet()
1018 ? computeDeclContext(SS, false)
1019 : BaseType->getAs<RecordType>()->getDecl());
1022 ExprResult RetryExpr;
1023 if (!IsArrow && BaseExpr) {
1024 SFINAETrap Trap(*this, true);
1025 ParsedType ObjectType;
1026 bool MayBePseudoDestructor = false;
1027 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1028 OpLoc, tok::arrow, ObjectType,
1029 MayBePseudoDestructor);
1030 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1031 CXXScopeSpec TempSS(SS);
1032 RetryExpr = ActOnMemberAccessExpr(
1033 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
1034 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
1036 if (Trap.hasErrorOccurred())
1037 RetryExpr = ExprError();
1039 if (RetryExpr.isUsable()) {
1040 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1041 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1046 Diag(R.getNameLoc(), diag::err_no_member)
1048 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1052 // Diagnose lookups that find only declarations from a non-base
1053 // type. This is possible for either qualified lookups (which may
1054 // have been qualified with an unrelated type) or implicit member
1055 // expressions (which were found with unqualified lookup and thus
1056 // may have come from an enclosing scope). Note that it's okay for
1057 // lookup to find declarations from a non-base type as long as those
1058 // aren't the ones picked by overload resolution.
1059 if ((SS.isSet() || !BaseExpr ||
1060 (isa<CXXThisExpr>(BaseExpr) &&
1061 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1062 !SuppressQualifierCheck &&
1063 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1066 // Construct an unresolved result if we in fact got an unresolved
1068 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1069 // Suppress any lookup-related diagnostics; we'll do these when we
1071 R.suppressDiagnostics();
1073 UnresolvedMemberExpr *MemExpr
1074 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1075 BaseExpr, BaseExprType,
1077 SS.getWithLocInContext(Context),
1078 TemplateKWLoc, MemberNameInfo,
1079 TemplateArgs, R.begin(), R.end());
1084 assert(R.isSingleResult());
1085 DeclAccessPair FoundDecl = R.begin().getPair();
1086 NamedDecl *MemberDecl = R.getFoundDecl();
1088 // FIXME: diagnose the presence of template arguments now.
1090 // If the decl being referenced had an error, return an error for this
1091 // sub-expr without emitting another error, in order to avoid cascading
1093 if (MemberDecl->isInvalidDecl())
1096 // Handle the implicit-member-access case.
1098 // If this is not an instance member, convert to a non-member access.
1099 if (!MemberDecl->isCXXInstanceMember()) {
1100 // If this is a variable template, get the instantiated variable
1101 // declaration corresponding to the supplied template arguments
1102 // (while emitting diagnostics as necessary) that will be referenced
1103 // by this expression.
1104 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1105 "How did we get template arguments here sans a variable template");
1106 if (isa<VarTemplateDecl>(MemberDecl)) {
1107 MemberDecl = getVarTemplateSpecialization(
1108 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1109 R.getLookupNameInfo(), TemplateKWLoc);
1113 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1114 FoundDecl, TemplateArgs);
1116 SourceLocation Loc = R.getNameLoc();
1117 if (SS.getRange().isValid())
1118 Loc = SS.getRange().getBegin();
1119 CheckCXXThisCapture(Loc);
1120 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1123 // Check the use of this member.
1124 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1127 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1128 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1129 FoundDecl, MemberNameInfo);
1131 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1132 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1135 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1136 // We may have found a field within an anonymous union or struct
1137 // (C++ [class.union]).
1138 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
1139 FoundDecl, BaseExpr,
1142 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
1143 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1144 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1145 Var->getType().getNonReferenceType(), VK_LValue,
1149 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1150 ExprValueKind valueKind;
1152 if (MemberFn->isInstance()) {
1153 valueKind = VK_RValue;
1154 type = Context.BoundMemberTy;
1156 valueKind = VK_LValue;
1157 type = MemberFn->getType();
1160 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1161 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1162 type, valueKind, OK_Ordinary);
1164 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1166 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1167 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1168 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1169 Enum->getType(), VK_RValue, OK_Ordinary);
1171 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1172 if (VarDecl *Var = getVarTemplateSpecialization(
1173 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1174 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1175 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1176 Var->getType().getNonReferenceType(), VK_LValue,
1181 // We found something that we didn't expect. Complain.
1182 if (isa<TypeDecl>(MemberDecl))
1183 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1184 << MemberName << BaseType << int(IsArrow);
1186 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1187 << MemberName << BaseType << int(IsArrow);
1189 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1191 R.suppressDiagnostics();
1195 /// Given that normal member access failed on the given expression,
1196 /// and given that the expression's type involves builtin-id or
1197 /// builtin-Class, decide whether substituting in the redefinition
1198 /// types would be profitable. The redefinition type is whatever
1199 /// this translation unit tried to typedef to id/Class; we store
1200 /// it to the side and then re-use it in places like this.
1201 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1202 const ObjCObjectPointerType *opty
1203 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1204 if (!opty) return false;
1206 const ObjCObjectType *ty = opty->getObjectType();
1209 if (ty->isObjCId()) {
1210 redef = S.Context.getObjCIdRedefinitionType();
1211 } else if (ty->isObjCClass()) {
1212 redef = S.Context.getObjCClassRedefinitionType();
1217 // Do the substitution as long as the redefinition type isn't just a
1218 // possibly-qualified pointer to builtin-id or builtin-Class again.
1219 opty = redef->getAs<ObjCObjectPointerType>();
1220 if (opty && !opty->getObjectType()->getInterface())
1223 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1227 static bool isRecordType(QualType T) {
1228 return T->isRecordType();
1230 static bool isPointerToRecordType(QualType T) {
1231 if (const PointerType *PT = T->getAs<PointerType>())
1232 return PT->getPointeeType()->isRecordType();
1236 /// Perform conversions on the LHS of a member access expression.
1238 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1239 if (IsArrow && !Base->getType()->isFunctionType())
1240 return DefaultFunctionArrayLvalueConversion(Base);
1242 return CheckPlaceholderExpr(Base);
1245 /// Look up the given member of the given non-type-dependent
1246 /// expression. This can return in one of two ways:
1247 /// * If it returns a sentinel null-but-valid result, the caller will
1248 /// assume that lookup was performed and the results written into
1249 /// the provided structure. It will take over from there.
1250 /// * Otherwise, the returned expression will be produced in place of
1251 /// an ordinary member expression.
1253 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1254 /// fixed for ObjC++.
1255 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1256 ExprResult &BaseExpr, bool &IsArrow,
1257 SourceLocation OpLoc, CXXScopeSpec &SS,
1258 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1259 assert(BaseExpr.get() && "no base expression");
1261 // Perform default conversions.
1262 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1263 if (BaseExpr.isInvalid())
1266 QualType BaseType = BaseExpr.get()->getType();
1267 assert(!BaseType->isDependentType());
1269 DeclarationName MemberName = R.getLookupName();
1270 SourceLocation MemberLoc = R.getNameLoc();
1272 // For later type-checking purposes, turn arrow accesses into dot
1273 // accesses. The only access type we support that doesn't follow
1274 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1275 // and those never use arrows, so this is unaffected.
1277 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1278 BaseType = Ptr->getPointeeType();
1279 else if (const ObjCObjectPointerType *Ptr
1280 = BaseType->getAs<ObjCObjectPointerType>())
1281 BaseType = Ptr->getPointeeType();
1282 else if (BaseType->isRecordType()) {
1283 // Recover from arrow accesses to records, e.g.:
1284 // struct MyRecord foo;
1286 // This is actually well-formed in C++ if MyRecord has an
1287 // overloaded operator->, but that should have been dealt with
1288 // by now--or a diagnostic message already issued if a problem
1289 // was encountered while looking for the overloaded operator->.
1290 if (!S.getLangOpts().CPlusPlus) {
1291 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1292 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1293 << FixItHint::CreateReplacement(OpLoc, ".");
1296 } else if (BaseType->isFunctionType()) {
1299 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1300 << BaseType << BaseExpr.get()->getSourceRange();
1305 // Handle field access to simple records.
1306 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1307 TypoExpr *TE = nullptr;
1308 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
1309 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
1312 // Returning valid-but-null is how we indicate to the caller that
1313 // the lookup result was filled in. If typo correction was attempted and
1314 // failed, the lookup result will have been cleared--that combined with the
1315 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1316 return ExprResult(TE);
1319 // Handle ivar access to Objective-C objects.
1320 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1321 if (!SS.isEmpty() && !SS.isInvalid()) {
1322 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1323 << 1 << SS.getScopeRep()
1324 << FixItHint::CreateRemoval(SS.getRange());
1328 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1330 // There are three cases for the base type:
1331 // - builtin id (qualified or unqualified)
1332 // - builtin Class (qualified or unqualified)
1334 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1336 if (S.getLangOpts().ObjCAutoRefCount &&
1337 (OTy->isObjCId() || OTy->isObjCClass()))
1339 // There's an implicit 'isa' ivar on all objects.
1340 // But we only actually find it this way on objects of type 'id',
1342 if (OTy->isObjCId() && Member->isStr("isa"))
1343 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1344 OpLoc, S.Context.getObjCClassType());
1345 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1346 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1347 ObjCImpDecl, HasTemplateArgs);
1351 if (S.RequireCompleteType(OpLoc, BaseType,
1352 diag::err_typecheck_incomplete_tag,
1356 ObjCInterfaceDecl *ClassDeclared = nullptr;
1357 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1360 // Attempt to correct for typos in ivar names.
1361 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1362 Validator->IsObjCIvarLookup = IsArrow;
1363 if (TypoCorrection Corrected = S.CorrectTypo(
1364 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
1365 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
1366 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1369 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1370 << IDecl->getDeclName() << MemberName);
1372 // Figure out the class that declares the ivar.
1373 assert(!ClassDeclared);
1374 Decl *D = cast<Decl>(IV->getDeclContext());
1375 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1376 D = CAT->getClassInterface();
1377 ClassDeclared = cast<ObjCInterfaceDecl>(D);
1380 IDecl->FindPropertyDeclaration(
1381 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1382 S.Diag(MemberLoc, diag::err_property_found_suggest)
1383 << Member << BaseExpr.get()->getType()
1384 << FixItHint::CreateReplacement(OpLoc, ".");
1388 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1389 << IDecl->getDeclName() << MemberName
1390 << BaseExpr.get()->getSourceRange();
1395 assert(ClassDeclared);
1397 // If the decl being referenced had an error, return an error for this
1398 // sub-expr without emitting another error, in order to avoid cascading
1400 if (IV->isInvalidDecl())
1403 // Check whether we can reference this field.
1404 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
1406 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1407 IV->getAccessControl() != ObjCIvarDecl::Package) {
1408 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1409 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1410 ClassOfMethodDecl = MD->getClassInterface();
1411 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1412 // Case of a c-function declared inside an objc implementation.
1413 // FIXME: For a c-style function nested inside an objc implementation
1414 // class, there is no implementation context available, so we pass
1415 // down the context as argument to this routine. Ideally, this context
1416 // need be passed down in the AST node and somehow calculated from the
1417 // AST for a function decl.
1418 if (ObjCImplementationDecl *IMPD =
1419 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1420 ClassOfMethodDecl = IMPD->getClassInterface();
1421 else if (ObjCCategoryImplDecl* CatImplClass =
1422 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1423 ClassOfMethodDecl = CatImplClass->getClassInterface();
1425 if (!S.getLangOpts().DebuggerSupport) {
1426 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1427 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1428 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1429 S.Diag(MemberLoc, diag::error_private_ivar_access)
1430 << IV->getDeclName();
1431 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1433 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1434 << IV->getDeclName();
1438 if (S.getLangOpts().ObjCAutoRefCount) {
1439 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1440 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1441 if (UO->getOpcode() == UO_Deref)
1442 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1444 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1445 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1446 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1451 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1452 ObjCMethodFamily MF = MD->getMethodFamily();
1453 warn = (MF != OMF_init && MF != OMF_dealloc &&
1454 MF != OMF_finalize &&
1455 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1458 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1461 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1462 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1465 if (S.getLangOpts().ObjCAutoRefCount) {
1466 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1467 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1468 S.recordUseOfEvaluatedWeak(Result);
1475 // Objective-C property access.
1476 const ObjCObjectPointerType *OPT;
1477 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1478 if (!SS.isEmpty() && !SS.isInvalid()) {
1479 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1480 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
1484 // This actually uses the base as an r-value.
1485 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1486 if (BaseExpr.isInvalid())
1489 assert(S.Context.hasSameUnqualifiedType(BaseType,
1490 BaseExpr.get()->getType()));
1492 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1494 const ObjCObjectType *OT = OPT->getObjectType();
1496 // id, with and without qualifiers.
1497 if (OT->isObjCId()) {
1498 // Check protocols on qualified interfaces.
1499 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1501 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
1502 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1503 // Check the use of this declaration
1504 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
1507 return new (S.Context)
1508 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1509 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1512 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1513 // Check the use of this method.
1514 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
1516 Selector SetterSel =
1517 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1518 S.PP.getSelectorTable(),
1520 ObjCMethodDecl *SMD = nullptr;
1521 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1522 /*Property id*/ nullptr,
1523 SetterSel, S.Context))
1524 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1526 return new (S.Context)
1527 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1528 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1531 // Use of id.member can only be for a property reference. Do not
1532 // use the 'id' redefinition in this case.
1533 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1534 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1535 ObjCImpDecl, HasTemplateArgs);
1537 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1538 << MemberName << BaseType);
1541 // 'Class', unqualified only.
1542 if (OT->isObjCClass()) {
1543 // Only works in a method declaration (??!).
1544 ObjCMethodDecl *MD = S.getCurMethodDecl();
1546 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1547 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1548 ObjCImpDecl, HasTemplateArgs);
1553 // Also must look for a getter name which uses property syntax.
1554 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1555 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1556 ObjCMethodDecl *Getter;
1557 if ((Getter = IFace->lookupClassMethod(Sel))) {
1558 // Check the use of this method.
1559 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
1562 Getter = IFace->lookupPrivateMethod(Sel, false);
1563 // If we found a getter then this may be a valid dot-reference, we
1564 // will look for the matching setter, in case it is needed.
1565 Selector SetterSel =
1566 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1567 S.PP.getSelectorTable(),
1569 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1571 // If this reference is in an @implementation, also check for 'private'
1573 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1576 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1579 if (Getter || Setter) {
1580 return new (S.Context) ObjCPropertyRefExpr(
1581 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1582 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1585 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1586 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1587 ObjCImpDecl, HasTemplateArgs);
1589 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1590 << MemberName << BaseType);
1593 // Normal property access.
1594 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1595 MemberLoc, SourceLocation(), QualType(),
1599 // Handle 'field access' to vectors, such as 'V.xx'.
1600 if (BaseType->isExtVectorType()) {
1601 // FIXME: this expr should store IsArrow.
1602 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1607 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1608 VK = POE->getSyntacticForm()->getValueKind();
1610 VK = BaseExpr.get()->getValueKind();
1612 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1617 return new (S.Context)
1618 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1621 // Adjust builtin-sel to the appropriate redefinition type if that's
1622 // not just a pointer to builtin-sel again.
1623 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1624 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1625 BaseExpr = S.ImpCastExprToType(
1626 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1627 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1628 ObjCImpDecl, HasTemplateArgs);
1634 // Recover from dot accesses to pointers, e.g.:
1637 // This is actually well-formed in two cases:
1638 // - 'type' is an Objective C type
1639 // - 'bar' is a pseudo-destructor name which happens to refer to
1640 // the appropriate pointer type
1641 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1642 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1643 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1644 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1645 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1646 << FixItHint::CreateReplacement(OpLoc, "->");
1648 // Recurse as an -> access.
1650 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1651 ObjCImpDecl, HasTemplateArgs);
1655 // If the user is trying to apply -> or . to a function name, it's probably
1656 // because they forgot parentheses to call that function.
1657 if (S.tryToRecoverWithCall(
1658 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1660 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1661 if (BaseExpr.isInvalid())
1663 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1664 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1665 ObjCImpDecl, HasTemplateArgs);
1668 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1669 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1674 /// The main callback when the parser finds something like
1675 /// expression . [nested-name-specifier] identifier
1676 /// expression -> [nested-name-specifier] identifier
1677 /// where 'identifier' encompasses a fairly broad spectrum of
1678 /// possibilities, including destructor and operator references.
1680 /// \param OpKind either tok::arrow or tok::period
1681 /// \param ObjCImpDecl the current Objective-C \@implementation
1682 /// decl; this is an ugly hack around the fact that Objective-C
1683 /// \@implementations aren't properly put in the context chain
1684 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1685 SourceLocation OpLoc,
1686 tok::TokenKind OpKind,
1688 SourceLocation TemplateKWLoc,
1690 Decl *ObjCImpDecl) {
1691 if (SS.isSet() && SS.isInvalid())
1694 // Warn about the explicit constructor calls Microsoft extension.
1695 if (getLangOpts().MicrosoftExt &&
1696 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1697 Diag(Id.getSourceRange().getBegin(),
1698 diag::ext_ms_explicit_constructor_call);
1700 TemplateArgumentListInfo TemplateArgsBuffer;
1702 // Decompose the name into its component parts.
1703 DeclarationNameInfo NameInfo;
1704 const TemplateArgumentListInfo *TemplateArgs;
1705 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1706 NameInfo, TemplateArgs);
1708 DeclarationName Name = NameInfo.getName();
1709 bool IsArrow = (OpKind == tok::arrow);
1711 NamedDecl *FirstQualifierInScope
1712 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
1714 // This is a postfix expression, so get rid of ParenListExprs.
1715 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1716 if (Result.isInvalid()) return ExprError();
1717 Base = Result.get();
1719 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1720 isDependentScopeSpecifier(SS)) {
1721 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1722 TemplateKWLoc, FirstQualifierInScope,
1723 NameInfo, TemplateArgs);
1726 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1727 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1728 TemplateKWLoc, FirstQualifierInScope,
1729 NameInfo, TemplateArgs, S, &ExtraArgs);
1733 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1734 SourceLocation OpLoc, const CXXScopeSpec &SS,
1735 FieldDecl *Field, DeclAccessPair FoundDecl,
1736 const DeclarationNameInfo &MemberNameInfo) {
1737 // x.a is an l-value if 'a' has a reference type. Otherwise:
1738 // x.a is an l-value/x-value/pr-value if the base is (and note
1739 // that *x is always an l-value), except that if the base isn't
1740 // an ordinary object then we must have an rvalue.
1741 ExprValueKind VK = VK_LValue;
1742 ExprObjectKind OK = OK_Ordinary;
1744 if (BaseExpr->getObjectKind() == OK_Ordinary)
1745 VK = BaseExpr->getValueKind();
1749 if (VK != VK_RValue && Field->isBitField())
1752 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1753 QualType MemberType = Field->getType();
1754 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1755 MemberType = Ref->getPointeeType();
1758 QualType BaseType = BaseExpr->getType();
1759 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1761 Qualifiers BaseQuals = BaseType.getQualifiers();
1763 // GC attributes are never picked up by members.
1764 BaseQuals.removeObjCGCAttr();
1766 // CVR attributes from the base are picked up by members,
1767 // except that 'mutable' members don't pick up 'const'.
1768 if (Field->isMutable()) BaseQuals.removeConst();
1770 Qualifiers MemberQuals
1771 = S.Context.getCanonicalType(MemberType).getQualifiers();
1773 assert(!MemberQuals.hasAddressSpace());
1776 Qualifiers Combined = BaseQuals + MemberQuals;
1777 if (Combined != MemberQuals)
1778 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1781 S.UnusedPrivateFields.remove(Field);
1784 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1786 if (Base.isInvalid())
1789 BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
1790 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1791 MemberNameInfo, MemberType, VK, OK);
1793 // Build a reference to a private copy for non-static data members in
1794 // non-static member functions, privatized by OpenMP constructs.
1795 if (S.getLangOpts().OpenMP && IsArrow &&
1796 !S.CurContext->isDependentContext() &&
1797 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
1798 if (auto *PrivateCopy = S.IsOpenMPCapturedDecl(Field))
1799 return S.getOpenMPCapturedExpr(PrivateCopy, VK, OK, OpLoc);
1804 /// Builds an implicit member access expression. The current context
1805 /// is known to be an instance method, and the given unqualified lookup
1806 /// set is known to contain only instance members, at least one of which
1807 /// is from an appropriate type.
1809 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1810 SourceLocation TemplateKWLoc,
1812 const TemplateArgumentListInfo *TemplateArgs,
1813 bool IsKnownInstance, const Scope *S) {
1814 assert(!R.empty() && !R.isAmbiguous());
1816 SourceLocation loc = R.getNameLoc();
1818 // If this is known to be an instance access, go ahead and build an
1819 // implicit 'this' expression now.
1820 // 'this' expression now.
1821 QualType ThisTy = getCurrentThisType();
1822 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1824 Expr *baseExpr = nullptr; // null signifies implicit access
1825 if (IsKnownInstance) {
1826 SourceLocation Loc = R.getNameLoc();
1827 if (SS.getRange().isValid())
1828 Loc = SS.getRange().getBegin();
1829 CheckCXXThisCapture(Loc);
1830 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1833 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1834 /*OpLoc*/ SourceLocation(),
1837 /*FirstQualifierInScope*/ nullptr,
1838 R, TemplateArgs, S);