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