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;
30 static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
31 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
32 return !Bases.count(Base->getCanonicalDecl());
35 /// Determines if the given class is provably not derived from all of
36 /// the prospective base classes.
37 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
38 const BaseSet &Bases) {
39 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
40 return BaseIsNotInSet(Record, BasesPtr) &&
41 Record->forallBases(BaseIsNotInSet, BasesPtr);
45 /// The reference is definitely not an instance member access.
48 /// The reference may be an implicit instance member access.
51 /// The reference may be to an instance member, but it might be invalid if
52 /// so, because the context is not an instance method.
53 IMA_Mixed_StaticContext,
55 /// The reference may be to an instance member, but it is invalid if
56 /// so, because the context is from an unrelated class.
59 /// The reference is definitely an implicit instance member access.
62 /// The reference may be to an unresolved using declaration.
65 /// The reference is a contextually-permitted abstract member reference.
68 /// The reference may be to an unresolved using declaration and the
69 /// context is not an instance method.
70 IMA_Unresolved_StaticContext,
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
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_StaticContext,
81 /// All possible referrents are instance members of an 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 isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
99 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
101 if (R.isUnresolvableResult())
102 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
104 // Collect all the declaring classes of instance members we find.
105 bool hasNonInstance = false;
106 bool isField = false;
108 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
111 if (D->isCXXInstanceMember()) {
112 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
113 isa<IndirectFieldDecl>(D);
115 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
116 Classes.insert(R->getCanonicalDecl());
119 hasNonInstance = true;
122 // If we didn't find any instance members, it can't be an implicit
127 // C++11 [expr.prim.general]p12:
128 // An id-expression that denotes a non-static data member or non-static
129 // member function of a class can only be used:
131 // - if that id-expression denotes a non-static data member and it
132 // appears in an unevaluated operand.
134 // This rule is specific to C++11. However, we also permit this form
135 // in unevaluated inline assembly operands, like the operand to a SIZE.
136 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
137 assert(!AbstractInstanceResult);
138 switch (SemaRef.ExprEvalContexts.back().Context) {
139 case Sema::Unevaluated:
140 if (isField && SemaRef.getLangOpts().CPlusPlus11)
141 AbstractInstanceResult = IMA_Field_Uneval_Context;
144 case Sema::UnevaluatedAbstract:
145 AbstractInstanceResult = IMA_Abstract;
148 case Sema::ConstantEvaluated:
149 case Sema::PotentiallyEvaluated:
150 case Sema::PotentiallyEvaluatedIfUsed:
154 // If the current context is not an instance method, it can't be
155 // an implicit member reference.
156 if (isStaticContext) {
158 return IMA_Mixed_StaticContext;
160 return AbstractInstanceResult ? AbstractInstanceResult
161 : IMA_Error_StaticContext;
164 CXXRecordDecl *contextClass;
165 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
166 contextClass = MD->getParent()->getCanonicalDecl();
168 contextClass = cast<CXXRecordDecl>(DC);
170 // [class.mfct.non-static]p3:
171 // ...is used in the body of a non-static member function of class X,
172 // if name lookup (3.4.1) resolves the name in the id-expression to a
173 // non-static non-type member of some class C [...]
174 // ...if C is not X or a base class of X, the class member access expression
176 if (R.getNamingClass() &&
177 contextClass->getCanonicalDecl() !=
178 R.getNamingClass()->getCanonicalDecl()) {
179 // If the naming class is not the current context, this was a qualified
180 // member name lookup, and it's sufficient to check that we have the naming
181 // class as a base class.
183 Classes.insert(R.getNamingClass()->getCanonicalDecl());
186 // If we can prove that the current context is unrelated to all the
187 // declaring classes, it can't be an implicit member reference (in
188 // which case it's an error if any of those members are selected).
189 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
190 return hasNonInstance ? IMA_Mixed_Unrelated :
191 AbstractInstanceResult ? AbstractInstanceResult :
194 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
197 /// Diagnose a reference to a field with no object available.
198 static void diagnoseInstanceReference(Sema &SemaRef,
199 const CXXScopeSpec &SS,
201 const DeclarationNameInfo &nameInfo) {
202 SourceLocation Loc = nameInfo.getLoc();
203 SourceRange Range(Loc);
204 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
206 // Look through using shadow decls and aliases.
207 Rep = Rep->getUnderlyingDecl();
209 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
210 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
211 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
212 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
214 bool InStaticMethod = Method && Method->isStatic();
215 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
217 if (IsField && InStaticMethod)
218 // "invalid use of member 'x' in static member function"
219 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
220 << Range << nameInfo.getName();
221 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
222 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
223 // Unqualified lookup in a non-static member function found a member of an
225 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
226 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
228 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
229 << nameInfo.getName() << Range;
231 SemaRef.Diag(Loc, diag::err_member_call_without_object)
235 /// Builds an expression which might be an implicit member expression.
237 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
238 SourceLocation TemplateKWLoc,
240 const TemplateArgumentListInfo *TemplateArgs) {
241 switch (ClassifyImplicitMemberAccess(*this, R)) {
243 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
246 case IMA_Mixed_Unrelated:
248 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(Member))
386 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
389 for (const auto *I : PDecl->protocols()) {
390 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
397 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
398 IdentifierInfo *Member,
400 ASTContext &Context) {
401 // Check protocols on qualified interfaces.
402 Decl *GDecl = nullptr;
403 for (const auto *I : QIdTy->quals()) {
405 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
409 // Also must look for a getter or setter name which uses property syntax.
410 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
416 for (const auto *I : QIdTy->quals()) {
417 // Search in the protocol-qualifier list of current protocol.
418 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
427 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
428 bool IsArrow, SourceLocation OpLoc,
429 const CXXScopeSpec &SS,
430 SourceLocation TemplateKWLoc,
431 NamedDecl *FirstQualifierInScope,
432 const DeclarationNameInfo &NameInfo,
433 const TemplateArgumentListInfo *TemplateArgs) {
434 // Even in dependent contexts, try to diagnose base expressions with
435 // obviously wrong types, e.g.:
440 // In Obj-C++, however, the above expression is valid, since it could be
441 // accessing the 'f' property if T is an Obj-C interface. The extra check
442 // allows this, while still reporting an error if T is a struct pointer.
444 const PointerType *PT = BaseType->getAs<PointerType>();
445 if (PT && (!getLangOpts().ObjC1 ||
446 PT->getPointeeType()->isRecordType())) {
447 assert(BaseExpr && "cannot happen with implicit member accesses");
448 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
449 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
454 assert(BaseType->isDependentType() ||
455 NameInfo.getName().isDependentName() ||
456 isDependentScopeSpecifier(SS));
458 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
459 // must have pointer type, and the accessed type is the pointee.
460 return CXXDependentScopeMemberExpr::Create(
461 Context, BaseExpr, BaseType, IsArrow, OpLoc,
462 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
463 NameInfo, TemplateArgs);
466 /// We know that the given qualified member reference points only to
467 /// declarations which do not belong to the static type of the base
468 /// expression. Diagnose the problem.
469 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
472 const CXXScopeSpec &SS,
474 const DeclarationNameInfo &nameInfo) {
475 // If this is an implicit member access, use a different set of
478 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
480 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
481 << SS.getRange() << rep << BaseType;
484 // Check whether the declarations we found through a nested-name
485 // specifier in a member expression are actually members of the base
486 // type. The restriction here is:
489 // ... In these cases, the id-expression shall name a
490 // member of the class or of one of its base classes.
492 // So it's perfectly legitimate for the nested-name specifier to name
493 // an unrelated class, and for us to find an overload set including
494 // decls from classes which are not superclasses, as long as the decl
495 // we actually pick through overload resolution is from a superclass.
496 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
498 const CXXScopeSpec &SS,
499 const LookupResult &R) {
500 CXXRecordDecl *BaseRecord =
501 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
503 // We can't check this yet because the base type is still
505 assert(BaseType->isDependentType());
509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
510 // If this is an implicit member reference and we find a
511 // non-instance member, it's not an error.
512 if (!BaseExpr && !(*I)->isCXXInstanceMember())
515 // Note that we use the DC of the decl, not the underlying decl.
516 DeclContext *DC = (*I)->getDeclContext();
517 while (DC->isTransparentContext())
518 DC = DC->getParent();
523 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
524 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
525 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
529 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
530 R.getRepresentativeDecl(),
531 R.getLookupNameInfo());
537 // Callback to only accept typo corrections that are either a ValueDecl or a
538 // FunctionTemplateDecl and are declared in the current record or, for a C++
539 // classes, one of its base classes.
540 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
542 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
543 : Record(RTy->getDecl()) {
544 // Don't add bare keywords to the consumer since they will always fail
545 // validation by virtue of not being associated with any decls.
546 WantTypeSpecifiers = false;
547 WantExpressionKeywords = false;
548 WantCXXNamedCasts = false;
549 WantFunctionLikeCasts = false;
550 WantRemainingKeywords = false;
553 bool ValidateCandidate(const TypoCorrection &candidate) override {
554 NamedDecl *ND = candidate.getCorrectionDecl();
555 // Don't accept candidates that cannot be member functions, constants,
556 // variables, or templates.
557 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
560 // Accept candidates that occur in the current record.
561 if (Record->containsDecl(ND))
564 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
565 // Accept candidates that occur in any of the current class' base classes.
566 for (const auto &BS : RD->bases()) {
567 if (const RecordType *BSTy =
568 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
569 if (BSTy->getDecl()->containsDecl(ND))
579 const RecordDecl *const Record;
584 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
586 const RecordType *RTy,
587 SourceLocation OpLoc, bool IsArrow,
588 CXXScopeSpec &SS, bool HasTemplateArgs,
590 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
591 RecordDecl *RDecl = RTy->getDecl();
592 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
593 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
594 diag::err_typecheck_incomplete_tag,
598 if (HasTemplateArgs) {
599 // LookupTemplateName doesn't expect these both to exist simultaneously.
600 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
603 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
607 DeclContext *DC = RDecl;
609 // If the member name was a qualified-id, look into the
610 // nested-name-specifier.
611 DC = SemaRef.computeDeclContext(SS, false);
613 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
614 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
615 << SS.getRange() << DC;
619 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
621 if (!isa<TypeDecl>(DC)) {
622 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
623 << DC << SS.getRange();
628 // The record definition is complete, now look up the member.
629 SemaRef.LookupQualifiedName(R, DC, SS);
634 DeclarationName Typo = R.getLookupName();
635 SourceLocation TypoLoc = R.getNameLoc();
636 TE = SemaRef.CorrectTypoDelayed(
637 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
638 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
639 [=, &SemaRef](const TypoCorrection &TC) {
641 assert(!TC.isKeyword() &&
642 "Got a keyword as a correction for a member!");
643 bool DroppedSpecifier =
644 TC.WillReplaceSpecifier() &&
645 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
646 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
647 << Typo << DC << DroppedSpecifier
650 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
653 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
654 R.clear(); // Ensure there's no decls lingering in the shared state.
655 R.suppressDiagnostics();
656 R.setLookupName(TC.getCorrection());
657 for (NamedDecl *ND : TC)
660 return SemaRef.BuildMemberReferenceExpr(
661 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
662 nullptr, R, nullptr);
664 Sema::CTK_ErrorRecovery, DC);
669 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
670 ExprResult &BaseExpr, bool &IsArrow,
671 SourceLocation OpLoc, CXXScopeSpec &SS,
672 Decl *ObjCImpDecl, bool HasTemplateArgs);
675 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
676 SourceLocation OpLoc, bool IsArrow,
678 SourceLocation TemplateKWLoc,
679 NamedDecl *FirstQualifierInScope,
680 const DeclarationNameInfo &NameInfo,
681 const TemplateArgumentListInfo *TemplateArgs,
682 ActOnMemberAccessExtraArgs *ExtraArgs) {
683 if (BaseType->isDependentType() ||
684 (SS.isSet() && isDependentScopeSpecifier(SS)))
685 return ActOnDependentMemberExpr(Base, BaseType,
687 SS, TemplateKWLoc, FirstQualifierInScope,
688 NameInfo, TemplateArgs);
690 LookupResult R(*this, NameInfo, LookupMemberName);
692 // Implicit member accesses.
694 TypoExpr *TE = nullptr;
695 QualType RecordTy = BaseType;
696 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
697 if (LookupMemberExprInRecord(*this, R, nullptr,
698 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
699 SS, TemplateArgs != nullptr, TE))
704 // Explicit member accesses.
706 ExprResult BaseResult = Base;
707 ExprResult Result = LookupMemberExpr(
708 *this, R, BaseResult, IsArrow, OpLoc, SS,
709 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
710 TemplateArgs != nullptr);
712 if (BaseResult.isInvalid())
714 Base = BaseResult.get();
716 if (Result.isInvalid())
722 // LookupMemberExpr can modify Base, and thus change BaseType
723 BaseType = Base->getType();
726 return BuildMemberReferenceExpr(Base, BaseType,
727 OpLoc, IsArrow, SS, TemplateKWLoc,
728 FirstQualifierInScope, R, TemplateArgs,
733 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
734 SourceLocation OpLoc, const CXXScopeSpec &SS,
735 FieldDecl *Field, DeclAccessPair FoundDecl,
736 const DeclarationNameInfo &MemberNameInfo);
739 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
741 IndirectFieldDecl *indirectField,
742 DeclAccessPair foundDecl,
743 Expr *baseObjectExpr,
744 SourceLocation opLoc) {
745 // First, build the expression that refers to the base object.
747 bool baseObjectIsPointer = false;
748 Qualifiers baseQuals;
750 // Case 1: the base of the indirect field is not a field.
751 VarDecl *baseVariable = indirectField->getVarDecl();
752 CXXScopeSpec EmptySS;
754 assert(baseVariable->getType()->isRecordType());
756 // In principle we could have a member access expression that
757 // accesses an anonymous struct/union that's a static member of
758 // the base object's class. However, under the current standard,
759 // static data members cannot be anonymous structs or unions.
760 // Supporting this is as easy as building a MemberExpr here.
761 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
763 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
766 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
767 if (result.isInvalid()) return ExprError();
769 baseObjectExpr = result.get();
770 baseObjectIsPointer = false;
771 baseQuals = baseObjectExpr->getType().getQualifiers();
773 // Case 2: the base of the indirect field is a field and the user
774 // wrote a member expression.
775 } else if (baseObjectExpr) {
776 // The caller provided the base object expression. Determine
777 // whether its a pointer and whether it adds any qualifiers to the
778 // anonymous struct/union fields we're looking into.
779 QualType objectType = baseObjectExpr->getType();
781 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
782 baseObjectIsPointer = true;
783 objectType = ptr->getPointeeType();
785 baseObjectIsPointer = false;
787 baseQuals = objectType.getQualifiers();
789 // Case 3: the base of the indirect field is a field and we should
790 // build an implicit member access.
792 // We've found a member of an anonymous struct/union that is
793 // inside a non-anonymous struct/union, so in a well-formed
794 // program our base object expression is "this".
795 QualType ThisTy = getCurrentThisType();
796 if (ThisTy.isNull()) {
797 Diag(loc, diag::err_invalid_member_use_in_static_method)
798 << indirectField->getDeclName();
802 // Our base object expression is "this".
803 CheckCXXThisCapture(loc);
805 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
806 baseObjectIsPointer = true;
807 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
810 // Build the implicit member references to the field of the
811 // anonymous struct/union.
812 Expr *result = baseObjectExpr;
813 IndirectFieldDecl::chain_iterator
814 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
816 // Build the first member access in the chain with full information.
818 FieldDecl *field = cast<FieldDecl>(*FI);
820 // Make a nameInfo that properly uses the anonymous name.
821 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
823 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
824 SourceLocation(), EmptySS, field,
825 foundDecl, memberNameInfo).get();
829 // FIXME: check qualified member access
832 // In all cases, we should now skip the first declaration in the chain.
836 FieldDecl *field = cast<FieldDecl>(*FI++);
838 // FIXME: these are somewhat meaningless
839 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
840 DeclAccessPair fakeFoundDecl =
841 DeclAccessPair::make(field, field->getAccess());
844 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
845 SourceLocation(), (FI == FEnd ? SS : EmptySS),
846 field, fakeFoundDecl, memberNameInfo).get();
853 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
854 const CXXScopeSpec &SS,
856 const DeclarationNameInfo &NameInfo) {
857 // Property names are always simple identifiers and therefore never
858 // require any interesting additional storage.
859 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
860 S.Context.PseudoObjectTy, VK_LValue,
861 SS.getWithLocInContext(S.Context),
865 /// \brief Build a MemberExpr AST node.
866 static MemberExpr *BuildMemberExpr(
867 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
868 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
869 ValueDecl *Member, DeclAccessPair FoundDecl,
870 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
871 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
872 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
873 MemberExpr *E = MemberExpr::Create(
874 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
875 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
876 SemaRef.MarkMemberReferenced(E);
881 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
882 SourceLocation OpLoc, bool IsArrow,
883 const CXXScopeSpec &SS,
884 SourceLocation TemplateKWLoc,
885 NamedDecl *FirstQualifierInScope,
887 const TemplateArgumentListInfo *TemplateArgs,
888 bool SuppressQualifierCheck,
889 ActOnMemberAccessExtraArgs *ExtraArgs) {
890 QualType BaseType = BaseExprType;
892 assert(BaseType->isPointerType());
893 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
895 R.setBaseObjectType(BaseType);
897 LambdaScopeInfo *const CurLSI = getCurLambda();
898 // If this is an implicit member reference and the overloaded
899 // name refers to both static and non-static member functions
900 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
901 // check if we should/can capture 'this'...
902 // Keep this example in mind:
905 // static void f(double) { }
908 // auto L = [=](auto a) {
909 // return [](int i) {
910 // return [=](auto b) {
912 // //f(decltype(a){});
918 // N(5.32); // OK, must not error.
923 if (!BaseExpr && CurLSI) {
924 SourceLocation Loc = R.getNameLoc();
925 if (SS.getRange().isValid())
926 Loc = SS.getRange().getBegin();
927 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
928 // If the enclosing function is not dependent, then this lambda is
929 // capture ready, so if we can capture this, do so.
930 if (!EnclosingFunctionCtx->isDependentContext()) {
931 // If the current lambda and all enclosing lambdas can capture 'this' -
932 // then go ahead and capture 'this' (since our unresolved overload set
933 // contains both static and non-static member functions).
934 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
935 CheckCXXThisCapture(Loc);
936 } else if (CurContext->isDependentContext()) {
937 // ... since this is an implicit member reference, that might potentially
938 // involve a 'this' capture, mark 'this' for potential capture in
939 // enclosing lambdas.
940 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
941 CurLSI->addPotentialThisCapture(Loc);
944 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
945 DeclarationName MemberName = MemberNameInfo.getName();
946 SourceLocation MemberLoc = MemberNameInfo.getLoc();
952 // Rederive where we looked up.
953 DeclContext *DC = (SS.isSet()
954 ? computeDeclContext(SS, false)
955 : BaseType->getAs<RecordType>()->getDecl());
958 ExprResult RetryExpr;
959 if (!IsArrow && BaseExpr) {
960 SFINAETrap Trap(*this, true);
961 ParsedType ObjectType;
962 bool MayBePseudoDestructor = false;
963 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
964 OpLoc, tok::arrow, ObjectType,
965 MayBePseudoDestructor);
966 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
967 CXXScopeSpec TempSS(SS);
968 RetryExpr = ActOnMemberAccessExpr(
969 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
970 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
972 if (Trap.hasErrorOccurred())
973 RetryExpr = ExprError();
975 if (RetryExpr.isUsable()) {
976 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
977 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
982 Diag(R.getNameLoc(), diag::err_no_member)
984 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
988 // Diagnose lookups that find only declarations from a non-base
989 // type. This is possible for either qualified lookups (which may
990 // have been qualified with an unrelated type) or implicit member
991 // expressions (which were found with unqualified lookup and thus
992 // may have come from an enclosing scope). Note that it's okay for
993 // lookup to find declarations from a non-base type as long as those
994 // aren't the ones picked by overload resolution.
995 if ((SS.isSet() || !BaseExpr ||
996 (isa<CXXThisExpr>(BaseExpr) &&
997 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
998 !SuppressQualifierCheck &&
999 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1002 // Construct an unresolved result if we in fact got an unresolved
1004 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1005 // Suppress any lookup-related diagnostics; we'll do these when we
1007 R.suppressDiagnostics();
1009 UnresolvedMemberExpr *MemExpr
1010 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1011 BaseExpr, BaseExprType,
1013 SS.getWithLocInContext(Context),
1014 TemplateKWLoc, MemberNameInfo,
1015 TemplateArgs, R.begin(), R.end());
1020 assert(R.isSingleResult());
1021 DeclAccessPair FoundDecl = R.begin().getPair();
1022 NamedDecl *MemberDecl = R.getFoundDecl();
1024 // FIXME: diagnose the presence of template arguments now.
1026 // If the decl being referenced had an error, return an error for this
1027 // sub-expr without emitting another error, in order to avoid cascading
1029 if (MemberDecl->isInvalidDecl())
1032 // Handle the implicit-member-access case.
1034 // If this is not an instance member, convert to a non-member access.
1035 if (!MemberDecl->isCXXInstanceMember())
1036 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1038 SourceLocation Loc = R.getNameLoc();
1039 if (SS.getRange().isValid())
1040 Loc = SS.getRange().getBegin();
1041 CheckCXXThisCapture(Loc);
1042 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1045 bool ShouldCheckUse = true;
1046 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1047 // Don't diagnose the use of a virtual member function unless it's
1048 // explicitly qualified.
1049 if (MD->isVirtual() && !SS.isSet())
1050 ShouldCheckUse = false;
1053 // Check the use of this member.
1054 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1057 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1058 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1059 FoundDecl, MemberNameInfo);
1061 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1062 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1065 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1066 // We may have found a field within an anonymous union or struct
1067 // (C++ [class.union]).
1068 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
1069 FoundDecl, BaseExpr,
1072 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
1073 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1074 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1075 Var->getType().getNonReferenceType(), VK_LValue,
1079 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1080 ExprValueKind valueKind;
1082 if (MemberFn->isInstance()) {
1083 valueKind = VK_RValue;
1084 type = Context.BoundMemberTy;
1086 valueKind = VK_LValue;
1087 type = MemberFn->getType();
1090 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1091 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1092 type, valueKind, OK_Ordinary);
1094 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1096 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1097 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1098 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1099 Enum->getType(), VK_RValue, OK_Ordinary);
1102 // We found something that we didn't expect. Complain.
1103 if (isa<TypeDecl>(MemberDecl))
1104 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1105 << MemberName << BaseType << int(IsArrow);
1107 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1108 << MemberName << BaseType << int(IsArrow);
1110 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1112 R.suppressDiagnostics();
1116 /// Given that normal member access failed on the given expression,
1117 /// and given that the expression's type involves builtin-id or
1118 /// builtin-Class, decide whether substituting in the redefinition
1119 /// types would be profitable. The redefinition type is whatever
1120 /// this translation unit tried to typedef to id/Class; we store
1121 /// it to the side and then re-use it in places like this.
1122 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1123 const ObjCObjectPointerType *opty
1124 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1125 if (!opty) return false;
1127 const ObjCObjectType *ty = opty->getObjectType();
1130 if (ty->isObjCId()) {
1131 redef = S.Context.getObjCIdRedefinitionType();
1132 } else if (ty->isObjCClass()) {
1133 redef = S.Context.getObjCClassRedefinitionType();
1138 // Do the substitution as long as the redefinition type isn't just a
1139 // possibly-qualified pointer to builtin-id or builtin-Class again.
1140 opty = redef->getAs<ObjCObjectPointerType>();
1141 if (opty && !opty->getObjectType()->getInterface())
1144 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1148 static bool isRecordType(QualType T) {
1149 return T->isRecordType();
1151 static bool isPointerToRecordType(QualType T) {
1152 if (const PointerType *PT = T->getAs<PointerType>())
1153 return PT->getPointeeType()->isRecordType();
1157 /// Perform conversions on the LHS of a member access expression.
1159 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1160 if (IsArrow && !Base->getType()->isFunctionType())
1161 return DefaultFunctionArrayLvalueConversion(Base);
1163 return CheckPlaceholderExpr(Base);
1166 /// Look up the given member of the given non-type-dependent
1167 /// expression. This can return in one of two ways:
1168 /// * If it returns a sentinel null-but-valid result, the caller will
1169 /// assume that lookup was performed and the results written into
1170 /// the provided structure. It will take over from there.
1171 /// * Otherwise, the returned expression will be produced in place of
1172 /// an ordinary member expression.
1174 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1175 /// fixed for ObjC++.
1176 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1177 ExprResult &BaseExpr, bool &IsArrow,
1178 SourceLocation OpLoc, CXXScopeSpec &SS,
1179 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1180 assert(BaseExpr.get() && "no base expression");
1182 // Perform default conversions.
1183 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1184 if (BaseExpr.isInvalid())
1187 QualType BaseType = BaseExpr.get()->getType();
1188 assert(!BaseType->isDependentType());
1190 DeclarationName MemberName = R.getLookupName();
1191 SourceLocation MemberLoc = R.getNameLoc();
1193 // For later type-checking purposes, turn arrow accesses into dot
1194 // accesses. The only access type we support that doesn't follow
1195 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1196 // and those never use arrows, so this is unaffected.
1198 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1199 BaseType = Ptr->getPointeeType();
1200 else if (const ObjCObjectPointerType *Ptr
1201 = BaseType->getAs<ObjCObjectPointerType>())
1202 BaseType = Ptr->getPointeeType();
1203 else if (BaseType->isRecordType()) {
1204 // Recover from arrow accesses to records, e.g.:
1205 // struct MyRecord foo;
1207 // This is actually well-formed in C++ if MyRecord has an
1208 // overloaded operator->, but that should have been dealt with
1209 // by now--or a diagnostic message already issued if a problem
1210 // was encountered while looking for the overloaded operator->.
1211 if (!S.getLangOpts().CPlusPlus) {
1212 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1213 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1214 << FixItHint::CreateReplacement(OpLoc, ".");
1217 } else if (BaseType->isFunctionType()) {
1220 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1221 << BaseType << BaseExpr.get()->getSourceRange();
1226 // Handle field access to simple records.
1227 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1228 TypoExpr *TE = nullptr;
1229 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
1230 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
1233 // Returning valid-but-null is how we indicate to the caller that
1234 // the lookup result was filled in. If typo correction was attempted and
1235 // failed, the lookup result will have been cleared--that combined with the
1236 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1237 return ExprResult(TE);
1240 // Handle ivar access to Objective-C objects.
1241 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1242 if (!SS.isEmpty() && !SS.isInvalid()) {
1243 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1244 << 1 << SS.getScopeRep()
1245 << FixItHint::CreateRemoval(SS.getRange());
1249 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1251 // There are three cases for the base type:
1252 // - builtin id (qualified or unqualified)
1253 // - builtin Class (qualified or unqualified)
1255 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1257 if (S.getLangOpts().ObjCAutoRefCount &&
1258 (OTy->isObjCId() || OTy->isObjCClass()))
1260 // There's an implicit 'isa' ivar on all objects.
1261 // But we only actually find it this way on objects of type 'id',
1263 if (OTy->isObjCId() && Member->isStr("isa"))
1264 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1265 OpLoc, S.Context.getObjCClassType());
1266 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1267 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1268 ObjCImpDecl, HasTemplateArgs);
1272 if (S.RequireCompleteType(OpLoc, BaseType,
1273 diag::err_typecheck_incomplete_tag,
1277 ObjCInterfaceDecl *ClassDeclared = nullptr;
1278 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1281 // Attempt to correct for typos in ivar names.
1282 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1283 Validator->IsObjCIvarLookup = IsArrow;
1284 if (TypoCorrection Corrected = S.CorrectTypo(
1285 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
1286 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
1287 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1290 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1291 << IDecl->getDeclName() << MemberName);
1293 // Figure out the class that declares the ivar.
1294 assert(!ClassDeclared);
1295 Decl *D = cast<Decl>(IV->getDeclContext());
1296 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1297 D = CAT->getClassInterface();
1298 ClassDeclared = cast<ObjCInterfaceDecl>(D);
1300 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1301 S.Diag(MemberLoc, diag::err_property_found_suggest)
1302 << Member << BaseExpr.get()->getType()
1303 << FixItHint::CreateReplacement(OpLoc, ".");
1307 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1308 << IDecl->getDeclName() << MemberName
1309 << BaseExpr.get()->getSourceRange();
1314 assert(ClassDeclared);
1316 // If the decl being referenced had an error, return an error for this
1317 // sub-expr without emitting another error, in order to avoid cascading
1319 if (IV->isInvalidDecl())
1322 // Check whether we can reference this field.
1323 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
1325 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1326 IV->getAccessControl() != ObjCIvarDecl::Package) {
1327 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1328 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1329 ClassOfMethodDecl = MD->getClassInterface();
1330 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1331 // Case of a c-function declared inside an objc implementation.
1332 // FIXME: For a c-style function nested inside an objc implementation
1333 // class, there is no implementation context available, so we pass
1334 // down the context as argument to this routine. Ideally, this context
1335 // need be passed down in the AST node and somehow calculated from the
1336 // AST for a function decl.
1337 if (ObjCImplementationDecl *IMPD =
1338 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1339 ClassOfMethodDecl = IMPD->getClassInterface();
1340 else if (ObjCCategoryImplDecl* CatImplClass =
1341 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1342 ClassOfMethodDecl = CatImplClass->getClassInterface();
1344 if (!S.getLangOpts().DebuggerSupport) {
1345 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1346 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1347 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1348 S.Diag(MemberLoc, diag::error_private_ivar_access)
1349 << IV->getDeclName();
1350 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1352 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1353 << IV->getDeclName();
1357 if (S.getLangOpts().ObjCAutoRefCount) {
1358 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1359 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1360 if (UO->getOpcode() == UO_Deref)
1361 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1363 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1364 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1365 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1370 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1371 ObjCMethodFamily MF = MD->getMethodFamily();
1372 warn = (MF != OMF_init && MF != OMF_dealloc &&
1373 MF != OMF_finalize &&
1374 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1377 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1380 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1381 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1384 if (S.getLangOpts().ObjCAutoRefCount) {
1385 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1386 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1387 S.recordUseOfEvaluatedWeak(Result);
1394 // Objective-C property access.
1395 const ObjCObjectPointerType *OPT;
1396 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1397 if (!SS.isEmpty() && !SS.isInvalid()) {
1398 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1399 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
1403 // This actually uses the base as an r-value.
1404 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1405 if (BaseExpr.isInvalid())
1408 assert(S.Context.hasSameUnqualifiedType(BaseType,
1409 BaseExpr.get()->getType()));
1411 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1413 const ObjCObjectType *OT = OPT->getObjectType();
1415 // id, with and without qualifiers.
1416 if (OT->isObjCId()) {
1417 // Check protocols on qualified interfaces.
1418 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1420 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
1421 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1422 // Check the use of this declaration
1423 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
1426 return new (S.Context)
1427 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1428 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1431 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1432 // Check the use of this method.
1433 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
1435 Selector SetterSel =
1436 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1437 S.PP.getSelectorTable(),
1439 ObjCMethodDecl *SMD = nullptr;
1440 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1441 /*Property id*/ nullptr,
1442 SetterSel, S.Context))
1443 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1445 return new (S.Context)
1446 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1447 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1450 // Use of id.member can only be for a property reference. Do not
1451 // use the 'id' redefinition in this case.
1452 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1453 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1454 ObjCImpDecl, HasTemplateArgs);
1456 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1457 << MemberName << BaseType);
1460 // 'Class', unqualified only.
1461 if (OT->isObjCClass()) {
1462 // Only works in a method declaration (??!).
1463 ObjCMethodDecl *MD = S.getCurMethodDecl();
1465 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1466 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1467 ObjCImpDecl, HasTemplateArgs);
1472 // Also must look for a getter name which uses property syntax.
1473 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1474 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1475 ObjCMethodDecl *Getter;
1476 if ((Getter = IFace->lookupClassMethod(Sel))) {
1477 // Check the use of this method.
1478 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
1481 Getter = IFace->lookupPrivateMethod(Sel, false);
1482 // If we found a getter then this may be a valid dot-reference, we
1483 // will look for the matching setter, in case it is needed.
1484 Selector SetterSel =
1485 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1486 S.PP.getSelectorTable(),
1488 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1490 // If this reference is in an @implementation, also check for 'private'
1492 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1495 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1498 if (Getter || Setter) {
1499 return new (S.Context) ObjCPropertyRefExpr(
1500 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1501 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1504 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1505 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1506 ObjCImpDecl, HasTemplateArgs);
1508 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1509 << MemberName << BaseType);
1512 // Normal property access.
1513 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1514 MemberLoc, SourceLocation(), QualType(),
1518 // Handle 'field access' to vectors, such as 'V.xx'.
1519 if (BaseType->isExtVectorType()) {
1520 // FIXME: this expr should store IsArrow.
1521 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1526 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1527 VK = POE->getSyntacticForm()->getValueKind();
1529 VK = BaseExpr.get()->getValueKind();
1531 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1536 return new (S.Context)
1537 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1540 // Adjust builtin-sel to the appropriate redefinition type if that's
1541 // not just a pointer to builtin-sel again.
1542 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1543 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1544 BaseExpr = S.ImpCastExprToType(
1545 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1546 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1547 ObjCImpDecl, HasTemplateArgs);
1553 // Recover from dot accesses to pointers, e.g.:
1556 // This is actually well-formed in two cases:
1557 // - 'type' is an Objective C type
1558 // - 'bar' is a pseudo-destructor name which happens to refer to
1559 // the appropriate pointer type
1560 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1561 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1562 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1563 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1564 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1565 << FixItHint::CreateReplacement(OpLoc, "->");
1567 // Recurse as an -> access.
1569 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1570 ObjCImpDecl, HasTemplateArgs);
1574 // If the user is trying to apply -> or . to a function name, it's probably
1575 // because they forgot parentheses to call that function.
1576 if (S.tryToRecoverWithCall(
1577 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1579 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1580 if (BaseExpr.isInvalid())
1582 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1583 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1584 ObjCImpDecl, HasTemplateArgs);
1587 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1588 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1593 /// The main callback when the parser finds something like
1594 /// expression . [nested-name-specifier] identifier
1595 /// expression -> [nested-name-specifier] identifier
1596 /// where 'identifier' encompasses a fairly broad spectrum of
1597 /// possibilities, including destructor and operator references.
1599 /// \param OpKind either tok::arrow or tok::period
1600 /// \param ObjCImpDecl the current Objective-C \@implementation
1601 /// decl; this is an ugly hack around the fact that Objective-C
1602 /// \@implementations aren't properly put in the context chain
1603 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1604 SourceLocation OpLoc,
1605 tok::TokenKind OpKind,
1607 SourceLocation TemplateKWLoc,
1609 Decl *ObjCImpDecl) {
1610 if (SS.isSet() && SS.isInvalid())
1613 // Warn about the explicit constructor calls Microsoft extension.
1614 if (getLangOpts().MicrosoftExt &&
1615 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1616 Diag(Id.getSourceRange().getBegin(),
1617 diag::ext_ms_explicit_constructor_call);
1619 TemplateArgumentListInfo TemplateArgsBuffer;
1621 // Decompose the name into its component parts.
1622 DeclarationNameInfo NameInfo;
1623 const TemplateArgumentListInfo *TemplateArgs;
1624 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1625 NameInfo, TemplateArgs);
1627 DeclarationName Name = NameInfo.getName();
1628 bool IsArrow = (OpKind == tok::arrow);
1630 NamedDecl *FirstQualifierInScope
1631 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
1633 // This is a postfix expression, so get rid of ParenListExprs.
1634 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1635 if (Result.isInvalid()) return ExprError();
1636 Base = Result.get();
1638 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1639 isDependentScopeSpecifier(SS)) {
1640 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1641 TemplateKWLoc, FirstQualifierInScope,
1642 NameInfo, TemplateArgs);
1645 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1646 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1647 TemplateKWLoc, FirstQualifierInScope,
1648 NameInfo, TemplateArgs, &ExtraArgs);
1652 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1653 SourceLocation OpLoc, const CXXScopeSpec &SS,
1654 FieldDecl *Field, DeclAccessPair FoundDecl,
1655 const DeclarationNameInfo &MemberNameInfo) {
1656 // x.a is an l-value if 'a' has a reference type. Otherwise:
1657 // x.a is an l-value/x-value/pr-value if the base is (and note
1658 // that *x is always an l-value), except that if the base isn't
1659 // an ordinary object then we must have an rvalue.
1660 ExprValueKind VK = VK_LValue;
1661 ExprObjectKind OK = OK_Ordinary;
1663 if (BaseExpr->getObjectKind() == OK_Ordinary)
1664 VK = BaseExpr->getValueKind();
1668 if (VK != VK_RValue && Field->isBitField())
1671 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1672 QualType MemberType = Field->getType();
1673 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1674 MemberType = Ref->getPointeeType();
1677 QualType BaseType = BaseExpr->getType();
1678 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1680 Qualifiers BaseQuals = BaseType.getQualifiers();
1682 // GC attributes are never picked up by members.
1683 BaseQuals.removeObjCGCAttr();
1685 // CVR attributes from the base are picked up by members,
1686 // except that 'mutable' members don't pick up 'const'.
1687 if (Field->isMutable()) BaseQuals.removeConst();
1689 Qualifiers MemberQuals
1690 = S.Context.getCanonicalType(MemberType).getQualifiers();
1692 assert(!MemberQuals.hasAddressSpace());
1695 Qualifiers Combined = BaseQuals + MemberQuals;
1696 if (Combined != MemberQuals)
1697 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1700 S.UnusedPrivateFields.remove(Field);
1703 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1705 if (Base.isInvalid())
1707 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
1708 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1709 MemberNameInfo, MemberType, VK, OK);
1712 /// Builds an implicit member access expression. The current context
1713 /// is known to be an instance method, and the given unqualified lookup
1714 /// set is known to contain only instance members, at least one of which
1715 /// is from an appropriate type.
1717 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1718 SourceLocation TemplateKWLoc,
1720 const TemplateArgumentListInfo *TemplateArgs,
1721 bool IsKnownInstance) {
1722 assert(!R.empty() && !R.isAmbiguous());
1724 SourceLocation loc = R.getNameLoc();
1726 // If this is known to be an instance access, go ahead and build an
1727 // implicit 'this' expression now.
1728 // 'this' expression now.
1729 QualType ThisTy = getCurrentThisType();
1730 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1732 Expr *baseExpr = nullptr; // null signifies implicit access
1733 if (IsKnownInstance) {
1734 SourceLocation Loc = R.getNameLoc();
1735 if (SS.getRange().isValid())
1736 Loc = SS.getRange().getBegin();
1737 CheckCXXThisCapture(Loc);
1738 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1741 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1742 /*OpLoc*/ SourceLocation(),
1745 /*FirstQualifierInScope*/ nullptr,