clang API Documentation

SemaExprMember.cpp
Go to the documentation of this file.
00001 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis member access expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #include "clang/Sema/Overload.h"
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "clang/AST/ASTLambda.h"
00016 #include "clang/AST/DeclCXX.h"
00017 #include "clang/AST/DeclObjC.h"
00018 #include "clang/AST/DeclTemplate.h"
00019 #include "clang/AST/ExprCXX.h"
00020 #include "clang/AST/ExprObjC.h"
00021 #include "clang/Lex/Preprocessor.h"
00022 #include "clang/Sema/Lookup.h"
00023 #include "clang/Sema/Scope.h"
00024 #include "clang/Sema/ScopeInfo.h"
00025 
00026 using namespace clang;
00027 using namespace sema;
00028 
00029 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
00030 static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
00031   const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
00032   return !Bases.count(Base->getCanonicalDecl());
00033 }
00034 
00035 /// Determines if the given class is provably not derived from all of
00036 /// the prospective base classes.
00037 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
00038                                      const BaseSet &Bases) {
00039   void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
00040   return BaseIsNotInSet(Record, BasesPtr) &&
00041          Record->forallBases(BaseIsNotInSet, BasesPtr);
00042 }
00043 
00044 enum IMAKind {
00045   /// The reference is definitely not an instance member access.
00046   IMA_Static,
00047 
00048   /// The reference may be an implicit instance member access.
00049   IMA_Mixed,
00050 
00051   /// The reference may be to an instance member, but it might be invalid if
00052   /// so, because the context is not an instance method.
00053   IMA_Mixed_StaticContext,
00054 
00055   /// The reference may be to an instance member, but it is invalid if
00056   /// so, because the context is from an unrelated class.
00057   IMA_Mixed_Unrelated,
00058 
00059   /// The reference is definitely an implicit instance member access.
00060   IMA_Instance,
00061 
00062   /// The reference may be to an unresolved using declaration.
00063   IMA_Unresolved,
00064 
00065   /// The reference is a contextually-permitted abstract member reference.
00066   IMA_Abstract,
00067 
00068   /// The reference may be to an unresolved using declaration and the
00069   /// context is not an instance method.
00070   IMA_Unresolved_StaticContext,
00071 
00072   // The reference refers to a field which is not a member of the containing
00073   // class, which is allowed because we're in C++11 mode and the context is
00074   // unevaluated.
00075   IMA_Field_Uneval_Context,
00076 
00077   /// All possible referrents are instance members and the current
00078   /// context is not an instance method.
00079   IMA_Error_StaticContext,
00080 
00081   /// All possible referrents are instance members of an unrelated
00082   /// class.
00083   IMA_Error_Unrelated
00084 };
00085 
00086 /// The given lookup names class member(s) and is not being used for
00087 /// an address-of-member expression.  Classify the type of access
00088 /// according to whether it's possible that this reference names an
00089 /// instance member.  This is best-effort in dependent contexts; it is okay to
00090 /// conservatively answer "yes", in which case some errors will simply
00091 /// not be caught until template-instantiation.
00092 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
00093                                             Scope *CurScope,
00094                                             const LookupResult &R) {
00095   assert(!R.empty() && (*R.begin())->isCXXClassMember());
00096 
00097   DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
00098 
00099   bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
00100     (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
00101 
00102   if (R.isUnresolvableResult())
00103     return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
00104 
00105   // Collect all the declaring classes of instance members we find.
00106   bool hasNonInstance = false;
00107   bool isField = false;
00108   BaseSet Classes;
00109   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
00110     NamedDecl *D = *I;
00111 
00112     if (D->isCXXInstanceMember()) {
00113       if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
00114           || dyn_cast<IndirectFieldDecl>(D))
00115         isField = true;
00116 
00117       CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
00118       Classes.insert(R->getCanonicalDecl());
00119     }
00120     else
00121       hasNonInstance = true;
00122   }
00123 
00124   // If we didn't find any instance members, it can't be an implicit
00125   // member reference.
00126   if (Classes.empty())
00127     return IMA_Static;
00128   
00129   // C++11 [expr.prim.general]p12:
00130   //   An id-expression that denotes a non-static data member or non-static
00131   //   member function of a class can only be used:
00132   //   (...)
00133   //   - if that id-expression denotes a non-static data member and it
00134   //     appears in an unevaluated operand.
00135   //
00136   // This rule is specific to C++11.  However, we also permit this form
00137   // in unevaluated inline assembly operands, like the operand to a SIZE.
00138   IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
00139   assert(!AbstractInstanceResult);
00140   switch (SemaRef.ExprEvalContexts.back().Context) {
00141   case Sema::Unevaluated:
00142     if (isField && SemaRef.getLangOpts().CPlusPlus11)
00143       AbstractInstanceResult = IMA_Field_Uneval_Context;
00144     break;
00145 
00146   case Sema::UnevaluatedAbstract:
00147     AbstractInstanceResult = IMA_Abstract;
00148     break;
00149 
00150   case Sema::ConstantEvaluated:
00151   case Sema::PotentiallyEvaluated:
00152   case Sema::PotentiallyEvaluatedIfUsed:
00153     break;
00154   }
00155 
00156   // If the current context is not an instance method, it can't be
00157   // an implicit member reference.
00158   if (isStaticContext) {
00159     if (hasNonInstance)
00160       return IMA_Mixed_StaticContext;
00161 
00162     return AbstractInstanceResult ? AbstractInstanceResult
00163                                   : IMA_Error_StaticContext;
00164   }
00165 
00166   CXXRecordDecl *contextClass;
00167   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
00168     contextClass = MD->getParent()->getCanonicalDecl();
00169   else
00170     contextClass = cast<CXXRecordDecl>(DC);
00171 
00172   // [class.mfct.non-static]p3: 
00173   // ...is used in the body of a non-static member function of class X,
00174   // if name lookup (3.4.1) resolves the name in the id-expression to a
00175   // non-static non-type member of some class C [...]
00176   // ...if C is not X or a base class of X, the class member access expression
00177   // is ill-formed.
00178   if (R.getNamingClass() &&
00179       contextClass->getCanonicalDecl() !=
00180         R.getNamingClass()->getCanonicalDecl()) {
00181     // If the naming class is not the current context, this was a qualified
00182     // member name lookup, and it's sufficient to check that we have the naming
00183     // class as a base class.
00184     Classes.clear();
00185     Classes.insert(R.getNamingClass()->getCanonicalDecl());
00186   }
00187 
00188   // If we can prove that the current context is unrelated to all the
00189   // declaring classes, it can't be an implicit member reference (in
00190   // which case it's an error if any of those members are selected).
00191   if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
00192     return hasNonInstance ? IMA_Mixed_Unrelated :
00193            AbstractInstanceResult ? AbstractInstanceResult :
00194                                     IMA_Error_Unrelated;
00195 
00196   return (hasNonInstance ? IMA_Mixed : IMA_Instance);
00197 }
00198 
00199 /// Diagnose a reference to a field with no object available.
00200 static void diagnoseInstanceReference(Sema &SemaRef,
00201                                       const CXXScopeSpec &SS,
00202                                       NamedDecl *Rep,
00203                                       const DeclarationNameInfo &nameInfo) {
00204   SourceLocation Loc = nameInfo.getLoc();
00205   SourceRange Range(Loc);
00206   if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
00207 
00208   DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
00209   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
00210   CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
00211   CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
00212 
00213   bool InStaticMethod = Method && Method->isStatic();
00214   bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
00215 
00216   if (IsField && InStaticMethod)
00217     // "invalid use of member 'x' in static member function"
00218     SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
00219         << Range << nameInfo.getName();
00220   else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
00221            !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
00222     // Unqualified lookup in a non-static member function found a member of an
00223     // enclosing class.
00224     SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
00225       << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
00226   else if (IsField)
00227     SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
00228       << nameInfo.getName() << Range;
00229   else
00230     SemaRef.Diag(Loc, diag::err_member_call_without_object)
00231       << Range;
00232 }
00233 
00234 /// Builds an expression which might be an implicit member expression.
00235 ExprResult
00236 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
00237                                       SourceLocation TemplateKWLoc,
00238                                       LookupResult &R,
00239                                 const TemplateArgumentListInfo *TemplateArgs) {
00240   switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
00241   case IMA_Instance:
00242     return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
00243 
00244   case IMA_Mixed:
00245   case IMA_Mixed_Unrelated:
00246   case IMA_Unresolved:
00247     return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
00248 
00249   case IMA_Field_Uneval_Context:
00250     Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
00251       << R.getLookupNameInfo().getName();
00252     // Fall through.
00253   case IMA_Static:
00254   case IMA_Abstract:
00255   case IMA_Mixed_StaticContext:
00256   case IMA_Unresolved_StaticContext:
00257     if (TemplateArgs || TemplateKWLoc.isValid())
00258       return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
00259     return BuildDeclarationNameExpr(SS, R, false);
00260 
00261   case IMA_Error_StaticContext:
00262   case IMA_Error_Unrelated:
00263     diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
00264                               R.getLookupNameInfo());
00265     return ExprError();
00266   }
00267 
00268   llvm_unreachable("unexpected instance member access kind");
00269 }
00270 
00271 /// Check an ext-vector component access expression.
00272 ///
00273 /// VK should be set in advance to the value kind of the base
00274 /// expression.
00275 static QualType
00276 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
00277                         SourceLocation OpLoc, const IdentifierInfo *CompName,
00278                         SourceLocation CompLoc) {
00279   // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
00280   // see FIXME there.
00281   //
00282   // FIXME: This logic can be greatly simplified by splitting it along
00283   // halving/not halving and reworking the component checking.
00284   const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
00285 
00286   // The vector accessor can't exceed the number of elements.
00287   const char *compStr = CompName->getNameStart();
00288 
00289   // This flag determines whether or not the component is one of the four
00290   // special names that indicate a subset of exactly half the elements are
00291   // to be selected.
00292   bool HalvingSwizzle = false;
00293 
00294   // This flag determines whether or not CompName has an 's' char prefix,
00295   // indicating that it is a string of hex values to be used as vector indices.
00296   bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
00297 
00298   bool HasRepeated = false;
00299   bool HasIndex[16] = {};
00300 
00301   int Idx;
00302 
00303   // Check that we've found one of the special components, or that the component
00304   // names must come from the same set.
00305   if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
00306       !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
00307     HalvingSwizzle = true;
00308   } else if (!HexSwizzle &&
00309              (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
00310     do {
00311       if (HasIndex[Idx]) HasRepeated = true;
00312       HasIndex[Idx] = true;
00313       compStr++;
00314     } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
00315   } else {
00316     if (HexSwizzle) compStr++;
00317     while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
00318       if (HasIndex[Idx]) HasRepeated = true;
00319       HasIndex[Idx] = true;
00320       compStr++;
00321     }
00322   }
00323 
00324   if (!HalvingSwizzle && *compStr) {
00325     // We didn't get to the end of the string. This means the component names
00326     // didn't come from the same set *or* we encountered an illegal name.
00327     S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
00328       << StringRef(compStr, 1) << SourceRange(CompLoc);
00329     return QualType();
00330   }
00331 
00332   // Ensure no component accessor exceeds the width of the vector type it
00333   // operates on.
00334   if (!HalvingSwizzle) {
00335     compStr = CompName->getNameStart();
00336 
00337     if (HexSwizzle)
00338       compStr++;
00339 
00340     while (*compStr) {
00341       if (!vecType->isAccessorWithinNumElements(*compStr++)) {
00342         S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
00343           << baseType << SourceRange(CompLoc);
00344         return QualType();
00345       }
00346     }
00347   }
00348 
00349   // The component accessor looks fine - now we need to compute the actual type.
00350   // The vector type is implied by the component accessor. For example,
00351   // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
00352   // vec4.s0 is a float, vec4.s23 is a vec3, etc.
00353   // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
00354   unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
00355                                      : CompName->getLength();
00356   if (HexSwizzle)
00357     CompSize--;
00358 
00359   if (CompSize == 1)
00360     return vecType->getElementType();
00361 
00362   if (HasRepeated) VK = VK_RValue;
00363 
00364   QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
00365   // Now look up the TypeDefDecl from the vector type. Without this,
00366   // diagostics look bad. We want extended vector types to appear built-in.
00367   for (Sema::ExtVectorDeclsType::iterator 
00368          I = S.ExtVectorDecls.begin(S.getExternalSource()),
00369          E = S.ExtVectorDecls.end(); 
00370        I != E; ++I) {
00371     if ((*I)->getUnderlyingType() == VT)
00372       return S.Context.getTypedefType(*I);
00373   }
00374   
00375   return VT; // should never get here (a typedef type should always be found).
00376 }
00377 
00378 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
00379                                                 IdentifierInfo *Member,
00380                                                 const Selector &Sel,
00381                                                 ASTContext &Context) {
00382   if (Member)
00383     if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
00384       return PD;
00385   if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
00386     return OMD;
00387 
00388   for (const auto *I : PDecl->protocols()) {
00389     if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
00390                                                            Context))
00391       return D;
00392   }
00393   return nullptr;
00394 }
00395 
00396 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
00397                                       IdentifierInfo *Member,
00398                                       const Selector &Sel,
00399                                       ASTContext &Context) {
00400   // Check protocols on qualified interfaces.
00401   Decl *GDecl = nullptr;
00402   for (const auto *I : QIdTy->quals()) {
00403     if (Member)
00404       if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
00405         GDecl = PD;
00406         break;
00407       }
00408     // Also must look for a getter or setter name which uses property syntax.
00409     if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
00410       GDecl = OMD;
00411       break;
00412     }
00413   }
00414   if (!GDecl) {
00415     for (const auto *I : QIdTy->quals()) {
00416       // Search in the protocol-qualifier list of current protocol.
00417       GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
00418       if (GDecl)
00419         return GDecl;
00420     }
00421   }
00422   return GDecl;
00423 }
00424 
00425 ExprResult
00426 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
00427                                bool IsArrow, SourceLocation OpLoc,
00428                                const CXXScopeSpec &SS,
00429                                SourceLocation TemplateKWLoc,
00430                                NamedDecl *FirstQualifierInScope,
00431                                const DeclarationNameInfo &NameInfo,
00432                                const TemplateArgumentListInfo *TemplateArgs) {
00433   // Even in dependent contexts, try to diagnose base expressions with
00434   // obviously wrong types, e.g.:
00435   //
00436   // T* t;
00437   // t.f;
00438   //
00439   // In Obj-C++, however, the above expression is valid, since it could be
00440   // accessing the 'f' property if T is an Obj-C interface. The extra check
00441   // allows this, while still reporting an error if T is a struct pointer.
00442   if (!IsArrow) {
00443     const PointerType *PT = BaseType->getAs<PointerType>();
00444     if (PT && (!getLangOpts().ObjC1 ||
00445                PT->getPointeeType()->isRecordType())) {
00446       assert(BaseExpr && "cannot happen with implicit member accesses");
00447       Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
00448         << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
00449       return ExprError();
00450     }
00451   }
00452 
00453   assert(BaseType->isDependentType() ||
00454          NameInfo.getName().isDependentName() ||
00455          isDependentScopeSpecifier(SS));
00456 
00457   // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
00458   // must have pointer type, and the accessed type is the pointee.
00459   return CXXDependentScopeMemberExpr::Create(
00460       Context, BaseExpr, BaseType, IsArrow, OpLoc,
00461       SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
00462       NameInfo, TemplateArgs);
00463 }
00464 
00465 /// We know that the given qualified member reference points only to
00466 /// declarations which do not belong to the static type of the base
00467 /// expression.  Diagnose the problem.
00468 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
00469                                              Expr *BaseExpr,
00470                                              QualType BaseType,
00471                                              const CXXScopeSpec &SS,
00472                                              NamedDecl *rep,
00473                                        const DeclarationNameInfo &nameInfo) {
00474   // If this is an implicit member access, use a different set of
00475   // diagnostics.
00476   if (!BaseExpr)
00477     return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
00478 
00479   SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
00480     << SS.getRange() << rep << BaseType;
00481 }
00482 
00483 // Check whether the declarations we found through a nested-name
00484 // specifier in a member expression are actually members of the base
00485 // type.  The restriction here is:
00486 //
00487 //   C++ [expr.ref]p2:
00488 //     ... In these cases, the id-expression shall name a
00489 //     member of the class or of one of its base classes.
00490 //
00491 // So it's perfectly legitimate for the nested-name specifier to name
00492 // an unrelated class, and for us to find an overload set including
00493 // decls from classes which are not superclasses, as long as the decl
00494 // we actually pick through overload resolution is from a superclass.
00495 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
00496                                          QualType BaseType,
00497                                          const CXXScopeSpec &SS,
00498                                          const LookupResult &R) {
00499   CXXRecordDecl *BaseRecord =
00500     cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
00501   if (!BaseRecord) {
00502     // We can't check this yet because the base type is still
00503     // dependent.
00504     assert(BaseType->isDependentType());
00505     return false;
00506   }
00507 
00508   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
00509     // If this is an implicit member reference and we find a
00510     // non-instance member, it's not an error.
00511     if (!BaseExpr && !(*I)->isCXXInstanceMember())
00512       return false;
00513 
00514     // Note that we use the DC of the decl, not the underlying decl.
00515     DeclContext *DC = (*I)->getDeclContext();
00516     while (DC->isTransparentContext())
00517       DC = DC->getParent();
00518 
00519     if (!DC->isRecord())
00520       continue;
00521 
00522     CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
00523     if (BaseRecord->getCanonicalDecl() == MemberRecord ||
00524         !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
00525       return false;
00526   }
00527 
00528   DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
00529                                    R.getRepresentativeDecl(),
00530                                    R.getLookupNameInfo());
00531   return true;
00532 }
00533 
00534 namespace {
00535 
00536 // Callback to only accept typo corrections that are either a ValueDecl or a
00537 // FunctionTemplateDecl and are declared in the current record or, for a C++
00538 // classes, one of its base classes.
00539 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
00540 public:
00541   explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
00542       : Record(RTy->getDecl()) {
00543     // Don't add bare keywords to the consumer since they will always fail
00544     // validation by virtue of not being associated with any decls.
00545     WantTypeSpecifiers = false;
00546     WantExpressionKeywords = false;
00547     WantCXXNamedCasts = false;
00548     WantFunctionLikeCasts = false;
00549     WantRemainingKeywords = false;
00550   }
00551 
00552   bool ValidateCandidate(const TypoCorrection &candidate) override {
00553     NamedDecl *ND = candidate.getCorrectionDecl();
00554     // Don't accept candidates that cannot be member functions, constants,
00555     // variables, or templates.
00556     if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
00557       return false;
00558 
00559     // Accept candidates that occur in the current record.
00560     if (Record->containsDecl(ND))
00561       return true;
00562 
00563     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
00564       // Accept candidates that occur in any of the current class' base classes.
00565       for (const auto &BS : RD->bases()) {
00566         if (const RecordType *BSTy =
00567                 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
00568           if (BSTy->getDecl()->containsDecl(ND))
00569             return true;
00570         }
00571       }
00572     }
00573 
00574     return false;
00575   }
00576 
00577 private:
00578   const RecordDecl *const Record;
00579 };
00580 
00581 }
00582 
00583 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
00584                                      Expr *BaseExpr,
00585                                      const RecordType *RTy,
00586                                      SourceLocation OpLoc, bool IsArrow,
00587                                      CXXScopeSpec &SS, bool HasTemplateArgs,
00588                                      TypoExpr *&TE) {
00589   SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
00590   RecordDecl *RDecl = RTy->getDecl();
00591   if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
00592       SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
00593                                   diag::err_typecheck_incomplete_tag,
00594                                   BaseRange))
00595     return true;
00596 
00597   if (HasTemplateArgs) {
00598     // LookupTemplateName doesn't expect these both to exist simultaneously.
00599     QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
00600 
00601     bool MOUS;
00602     SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
00603     return false;
00604   }
00605 
00606   DeclContext *DC = RDecl;
00607   if (SS.isSet()) {
00608     // If the member name was a qualified-id, look into the
00609     // nested-name-specifier.
00610     DC = SemaRef.computeDeclContext(SS, false);
00611 
00612     if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
00613       SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
00614           << SS.getRange() << DC;
00615       return true;
00616     }
00617 
00618     assert(DC && "Cannot handle non-computable dependent contexts in lookup");
00619 
00620     if (!isa<TypeDecl>(DC)) {
00621       SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
00622           << DC << SS.getRange();
00623       return true;
00624     }
00625   }
00626 
00627   // The record definition is complete, now look up the member.
00628   SemaRef.LookupQualifiedName(R, DC);
00629 
00630   if (!R.empty())
00631     return false;
00632 
00633   DeclarationName Typo = R.getLookupName();
00634   SourceLocation TypoLoc = R.getNameLoc();
00635   TE = SemaRef.CorrectTypoDelayed(
00636       R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
00637       llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
00638       [=, &SemaRef](const TypoCorrection &TC) {
00639         if (TC) {
00640           assert(!TC.isKeyword() &&
00641                  "Got a keyword as a correction for a member!");
00642           bool DroppedSpecifier =
00643               TC.WillReplaceSpecifier() &&
00644               Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
00645           SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
00646                                        << Typo << DC << DroppedSpecifier
00647                                        << SS.getRange());
00648         } else {
00649           SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
00650         }
00651       },
00652       [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
00653         R.clear(); // Ensure there's no decls lingering in the shared state.
00654         R.suppressDiagnostics();
00655         R.setLookupName(TC.getCorrection());
00656         for (NamedDecl *ND : TC)
00657           R.addDecl(ND);
00658         R.resolveKind();
00659         return SemaRef.BuildMemberReferenceExpr(
00660             BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
00661             nullptr, R, nullptr);
00662       },
00663       Sema::CTK_ErrorRecovery, DC);
00664 
00665   return false;
00666 }
00667 
00668 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
00669                                    ExprResult &BaseExpr, bool &IsArrow,
00670                                    SourceLocation OpLoc, CXXScopeSpec &SS,
00671                                    Decl *ObjCImpDecl, bool HasTemplateArgs);
00672 
00673 ExprResult
00674 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
00675                                SourceLocation OpLoc, bool IsArrow,
00676                                CXXScopeSpec &SS,
00677                                SourceLocation TemplateKWLoc,
00678                                NamedDecl *FirstQualifierInScope,
00679                                const DeclarationNameInfo &NameInfo,
00680                                const TemplateArgumentListInfo *TemplateArgs,
00681                                ActOnMemberAccessExtraArgs *ExtraArgs) {
00682   if (BaseType->isDependentType() ||
00683       (SS.isSet() && isDependentScopeSpecifier(SS)))
00684     return ActOnDependentMemberExpr(Base, BaseType,
00685                                     IsArrow, OpLoc,
00686                                     SS, TemplateKWLoc, FirstQualifierInScope,
00687                                     NameInfo, TemplateArgs);
00688 
00689   LookupResult R(*this, NameInfo, LookupMemberName);
00690 
00691   // Implicit member accesses.
00692   if (!Base) {
00693     TypoExpr *TE = nullptr;
00694     QualType RecordTy = BaseType;
00695     if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
00696     if (LookupMemberExprInRecord(*this, R, nullptr,
00697                                  RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
00698                                  SS, TemplateArgs != nullptr, TE))
00699       return ExprError();
00700     if (TE)
00701       return TE;
00702 
00703   // Explicit member accesses.
00704   } else {
00705     ExprResult BaseResult = Base;
00706     ExprResult Result = LookupMemberExpr(
00707         *this, R, BaseResult, IsArrow, OpLoc, SS,
00708         ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
00709         TemplateArgs != nullptr);
00710 
00711     if (BaseResult.isInvalid())
00712       return ExprError();
00713     Base = BaseResult.get();
00714 
00715     if (Result.isInvalid())
00716       return ExprError();
00717 
00718     if (Result.get())
00719       return Result;
00720 
00721     // LookupMemberExpr can modify Base, and thus change BaseType
00722     BaseType = Base->getType();
00723   }
00724 
00725   return BuildMemberReferenceExpr(Base, BaseType,
00726                                   OpLoc, IsArrow, SS, TemplateKWLoc,
00727                                   FirstQualifierInScope, R, TemplateArgs,
00728                                   false, ExtraArgs);
00729 }
00730 
00731 static ExprResult
00732 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
00733                         const CXXScopeSpec &SS, FieldDecl *Field,
00734                         DeclAccessPair FoundDecl,
00735                         const DeclarationNameInfo &MemberNameInfo);
00736 
00737 ExprResult
00738 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
00739                                                SourceLocation loc,
00740                                                IndirectFieldDecl *indirectField,
00741                                                DeclAccessPair foundDecl,
00742                                                Expr *baseObjectExpr,
00743                                                SourceLocation opLoc) {
00744   // First, build the expression that refers to the base object.
00745   
00746   bool baseObjectIsPointer = false;
00747   Qualifiers baseQuals;
00748   
00749   // Case 1:  the base of the indirect field is not a field.
00750   VarDecl *baseVariable = indirectField->getVarDecl();
00751   CXXScopeSpec EmptySS;
00752   if (baseVariable) {
00753     assert(baseVariable->getType()->isRecordType());
00754     
00755     // In principle we could have a member access expression that
00756     // accesses an anonymous struct/union that's a static member of
00757     // the base object's class.  However, under the current standard,
00758     // static data members cannot be anonymous structs or unions.
00759     // Supporting this is as easy as building a MemberExpr here.
00760     assert(!baseObjectExpr && "anonymous struct/union is static data member?");
00761     
00762     DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
00763     
00764     ExprResult result 
00765       = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
00766     if (result.isInvalid()) return ExprError();
00767     
00768     baseObjectExpr = result.get();    
00769     baseObjectIsPointer = false;
00770     baseQuals = baseObjectExpr->getType().getQualifiers();
00771     
00772     // Case 2: the base of the indirect field is a field and the user
00773     // wrote a member expression.
00774   } else if (baseObjectExpr) {
00775     // The caller provided the base object expression. Determine
00776     // whether its a pointer and whether it adds any qualifiers to the
00777     // anonymous struct/union fields we're looking into.
00778     QualType objectType = baseObjectExpr->getType();
00779     
00780     if (const PointerType *ptr = objectType->getAs<PointerType>()) {
00781       baseObjectIsPointer = true;
00782       objectType = ptr->getPointeeType();
00783     } else {
00784       baseObjectIsPointer = false;
00785     }
00786     baseQuals = objectType.getQualifiers();
00787     
00788     // Case 3: the base of the indirect field is a field and we should
00789     // build an implicit member access.
00790   } else {
00791     // We've found a member of an anonymous struct/union that is
00792     // inside a non-anonymous struct/union, so in a well-formed
00793     // program our base object expression is "this".
00794     QualType ThisTy = getCurrentThisType();
00795     if (ThisTy.isNull()) {
00796       Diag(loc, diag::err_invalid_member_use_in_static_method)
00797         << indirectField->getDeclName();
00798       return ExprError();
00799     }
00800     
00801     // Our base object expression is "this".
00802     CheckCXXThisCapture(loc);
00803     baseObjectExpr 
00804       = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
00805     baseObjectIsPointer = true;
00806     baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
00807   }
00808   
00809   // Build the implicit member references to the field of the
00810   // anonymous struct/union.
00811   Expr *result = baseObjectExpr;
00812   IndirectFieldDecl::chain_iterator
00813   FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
00814   
00815   // Build the first member access in the chain with full information.
00816   if (!baseVariable) {
00817     FieldDecl *field = cast<FieldDecl>(*FI);
00818     
00819     // Make a nameInfo that properly uses the anonymous name.
00820     DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
00821     
00822     result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
00823                                      EmptySS, field, foundDecl,
00824                                      memberNameInfo).get();
00825     if (!result)
00826       return ExprError();
00827 
00828     // FIXME: check qualified member access
00829   }
00830   
00831   // In all cases, we should now skip the first declaration in the chain.
00832   ++FI;
00833   
00834   while (FI != FEnd) {
00835     FieldDecl *field = cast<FieldDecl>(*FI++);
00836 
00837     // FIXME: these are somewhat meaningless
00838     DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
00839     DeclAccessPair fakeFoundDecl =
00840         DeclAccessPair::make(field, field->getAccess());
00841 
00842     result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
00843                                      (FI == FEnd? SS : EmptySS), field,
00844                                      fakeFoundDecl, memberNameInfo).get();
00845   }
00846   
00847   return result;
00848 }
00849 
00850 static ExprResult
00851 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
00852                        const CXXScopeSpec &SS,
00853                        MSPropertyDecl *PD,
00854                        const DeclarationNameInfo &NameInfo) {
00855   // Property names are always simple identifiers and therefore never
00856   // require any interesting additional storage.
00857   return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
00858                                            S.Context.PseudoObjectTy, VK_LValue,
00859                                            SS.getWithLocInContext(S.Context),
00860                                            NameInfo.getLoc());
00861 }
00862 
00863 /// \brief Build a MemberExpr AST node.
00864 static MemberExpr *
00865 BuildMemberExpr(Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
00866                 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
00867                 ValueDecl *Member, DeclAccessPair FoundDecl,
00868                 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
00869                 ExprValueKind VK, ExprObjectKind OK,
00870                 const TemplateArgumentListInfo *TemplateArgs = nullptr) {
00871   assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
00872   MemberExpr *E =
00873       MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
00874                          TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
00875                          TemplateArgs, Ty, VK, OK);
00876   SemaRef.MarkMemberReferenced(E);
00877   return E;
00878 }
00879 
00880 ExprResult
00881 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
00882                                SourceLocation OpLoc, bool IsArrow,
00883                                const CXXScopeSpec &SS,
00884                                SourceLocation TemplateKWLoc,
00885                                NamedDecl *FirstQualifierInScope,
00886                                LookupResult &R,
00887                                const TemplateArgumentListInfo *TemplateArgs,
00888                                bool SuppressQualifierCheck,
00889                                ActOnMemberAccessExtraArgs *ExtraArgs) {
00890   QualType BaseType = BaseExprType;
00891   if (IsArrow) {
00892     assert(BaseType->isPointerType());
00893     BaseType = BaseType->castAs<PointerType>()->getPointeeType();
00894   }
00895   R.setBaseObjectType(BaseType);
00896   
00897   LambdaScopeInfo *const CurLSI = getCurLambda();
00898   // If this is an implicit member reference and the overloaded
00899   // name refers to both static and non-static member functions
00900   // (i.e. BaseExpr is null) and if we are currently processing a lambda, 
00901   // check if we should/can capture 'this'...
00902   // Keep this example in mind:
00903   //  struct X {
00904   //   void f(int) { }
00905   //   static void f(double) { }
00906   // 
00907   //   int g() {
00908   //     auto L = [=](auto a) { 
00909   //       return [](int i) {
00910   //         return [=](auto b) {
00911   //           f(b); 
00912   //           //f(decltype(a){});
00913   //         };
00914   //       };
00915   //     };
00916   //     auto M = L(0.0); 
00917   //     auto N = M(3);
00918   //     N(5.32); // OK, must not error. 
00919   //     return 0;
00920   //   }
00921   //  };
00922   //
00923   if (!BaseExpr && CurLSI) {
00924     SourceLocation Loc = R.getNameLoc();
00925     if (SS.getRange().isValid())
00926       Loc = SS.getRange().getBegin();    
00927     DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
00928     // If the enclosing function is not dependent, then this lambda is 
00929     // capture ready, so if we can capture this, do so.
00930     if (!EnclosingFunctionCtx->isDependentContext()) {
00931       // If the current lambda and all enclosing lambdas can capture 'this' -
00932       // then go ahead and capture 'this' (since our unresolved overload set 
00933       // contains both static and non-static member functions). 
00934       if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
00935         CheckCXXThisCapture(Loc);
00936     } else if (CurContext->isDependentContext()) { 
00937       // ... since this is an implicit member reference, that might potentially
00938       // involve a 'this' capture, mark 'this' for potential capture in 
00939       // enclosing lambdas.
00940       if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
00941         CurLSI->addPotentialThisCapture(Loc);
00942     }
00943   }
00944   const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
00945   DeclarationName MemberName = MemberNameInfo.getName();
00946   SourceLocation MemberLoc = MemberNameInfo.getLoc();
00947 
00948   if (R.isAmbiguous())
00949     return ExprError();
00950 
00951   if (R.empty()) {
00952     // Rederive where we looked up.
00953     DeclContext *DC = (SS.isSet()
00954                        ? computeDeclContext(SS, false)
00955                        : BaseType->getAs<RecordType>()->getDecl());
00956 
00957     if (ExtraArgs) {
00958       ExprResult RetryExpr;
00959       if (!IsArrow && BaseExpr) {
00960         SFINAETrap Trap(*this, true);
00961         ParsedType ObjectType;
00962         bool MayBePseudoDestructor = false;
00963         RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
00964                                                  OpLoc, tok::arrow, ObjectType,
00965                                                  MayBePseudoDestructor);
00966         if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
00967           CXXScopeSpec TempSS(SS);
00968           RetryExpr = ActOnMemberAccessExpr(
00969               ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
00970               TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
00971               ExtraArgs->HasTrailingLParen);
00972         }
00973         if (Trap.hasErrorOccurred())
00974           RetryExpr = ExprError();
00975       }
00976       if (RetryExpr.isUsable()) {
00977         Diag(OpLoc, diag::err_no_member_overloaded_arrow)
00978           << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
00979         return RetryExpr;
00980       }
00981     }
00982 
00983     Diag(R.getNameLoc(), diag::err_no_member)
00984       << MemberName << DC
00985       << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
00986     return ExprError();
00987   }
00988 
00989   // Diagnose lookups that find only declarations from a non-base
00990   // type.  This is possible for either qualified lookups (which may
00991   // have been qualified with an unrelated type) or implicit member
00992   // expressions (which were found with unqualified lookup and thus
00993   // may have come from an enclosing scope).  Note that it's okay for
00994   // lookup to find declarations from a non-base type as long as those
00995   // aren't the ones picked by overload resolution.
00996   if ((SS.isSet() || !BaseExpr ||
00997        (isa<CXXThisExpr>(BaseExpr) &&
00998         cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
00999       !SuppressQualifierCheck &&
01000       CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
01001     return ExprError();
01002   
01003   // Construct an unresolved result if we in fact got an unresolved
01004   // result.
01005   if (R.isOverloadedResult() || R.isUnresolvableResult()) {
01006     // Suppress any lookup-related diagnostics; we'll do these when we
01007     // pick a member.
01008     R.suppressDiagnostics();
01009 
01010     UnresolvedMemberExpr *MemExpr
01011       = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
01012                                      BaseExpr, BaseExprType,
01013                                      IsArrow, OpLoc,
01014                                      SS.getWithLocInContext(Context),
01015                                      TemplateKWLoc, MemberNameInfo,
01016                                      TemplateArgs, R.begin(), R.end());
01017 
01018     return MemExpr;
01019   }
01020 
01021   assert(R.isSingleResult());
01022   DeclAccessPair FoundDecl = R.begin().getPair();
01023   NamedDecl *MemberDecl = R.getFoundDecl();
01024 
01025   // FIXME: diagnose the presence of template arguments now.
01026 
01027   // If the decl being referenced had an error, return an error for this
01028   // sub-expr without emitting another error, in order to avoid cascading
01029   // error cases.
01030   if (MemberDecl->isInvalidDecl())
01031     return ExprError();
01032 
01033   // Handle the implicit-member-access case.
01034   if (!BaseExpr) {
01035     // If this is not an instance member, convert to a non-member access.
01036     if (!MemberDecl->isCXXInstanceMember())
01037       return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
01038 
01039     SourceLocation Loc = R.getNameLoc();
01040     if (SS.getRange().isValid())
01041       Loc = SS.getRange().getBegin();
01042     CheckCXXThisCapture(Loc);
01043     BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
01044   }
01045 
01046   bool ShouldCheckUse = true;
01047   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
01048     // Don't diagnose the use of a virtual member function unless it's
01049     // explicitly qualified.
01050     if (MD->isVirtual() && !SS.isSet())
01051       ShouldCheckUse = false;
01052   }
01053 
01054   // Check the use of this member.
01055   if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
01056     return ExprError();
01057 
01058   if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
01059     return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
01060                                    SS, FD, FoundDecl, MemberNameInfo);
01061 
01062   if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
01063     return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
01064                                   MemberNameInfo);
01065 
01066   if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
01067     // We may have found a field within an anonymous union or struct
01068     // (C++ [class.union]).
01069     return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
01070                                                     FoundDecl, BaseExpr,
01071                                                     OpLoc);
01072 
01073   if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
01074     return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
01075                            Var, FoundDecl, MemberNameInfo,
01076                            Var->getType().getNonReferenceType(), VK_LValue,
01077                            OK_Ordinary);
01078   }
01079 
01080   if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
01081     ExprValueKind valueKind;
01082     QualType type;
01083     if (MemberFn->isInstance()) {
01084       valueKind = VK_RValue;
01085       type = Context.BoundMemberTy;
01086     } else {
01087       valueKind = VK_LValue;
01088       type = MemberFn->getType();
01089     }
01090 
01091     return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
01092                            MemberFn, FoundDecl, MemberNameInfo, type, valueKind,
01093                            OK_Ordinary);
01094   }
01095   assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
01096 
01097   if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
01098     return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
01099                            Enum, FoundDecl, MemberNameInfo, Enum->getType(),
01100                            VK_RValue, OK_Ordinary);
01101   }
01102 
01103   // We found something that we didn't expect. Complain.
01104   if (isa<TypeDecl>(MemberDecl))
01105     Diag(MemberLoc, diag::err_typecheck_member_reference_type)
01106       << MemberName << BaseType << int(IsArrow);
01107   else
01108     Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
01109       << MemberName << BaseType << int(IsArrow);
01110 
01111   Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
01112     << MemberName;
01113   R.suppressDiagnostics();
01114   return ExprError();
01115 }
01116 
01117 /// Given that normal member access failed on the given expression,
01118 /// and given that the expression's type involves builtin-id or
01119 /// builtin-Class, decide whether substituting in the redefinition
01120 /// types would be profitable.  The redefinition type is whatever
01121 /// this translation unit tried to typedef to id/Class;  we store
01122 /// it to the side and then re-use it in places like this.
01123 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
01124   const ObjCObjectPointerType *opty
01125     = base.get()->getType()->getAs<ObjCObjectPointerType>();
01126   if (!opty) return false;
01127 
01128   const ObjCObjectType *ty = opty->getObjectType();
01129 
01130   QualType redef;
01131   if (ty->isObjCId()) {
01132     redef = S.Context.getObjCIdRedefinitionType();
01133   } else if (ty->isObjCClass()) {
01134     redef = S.Context.getObjCClassRedefinitionType();
01135   } else {
01136     return false;
01137   }
01138 
01139   // Do the substitution as long as the redefinition type isn't just a
01140   // possibly-qualified pointer to builtin-id or builtin-Class again.
01141   opty = redef->getAs<ObjCObjectPointerType>();
01142   if (opty && !opty->getObjectType()->getInterface())
01143     return false;
01144 
01145   base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
01146   return true;
01147 }
01148 
01149 static bool isRecordType(QualType T) {
01150   return T->isRecordType();
01151 }
01152 static bool isPointerToRecordType(QualType T) {
01153   if (const PointerType *PT = T->getAs<PointerType>())
01154     return PT->getPointeeType()->isRecordType();
01155   return false;
01156 }
01157 
01158 /// Perform conversions on the LHS of a member access expression.
01159 ExprResult
01160 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
01161   if (IsArrow && !Base->getType()->isFunctionType())
01162     return DefaultFunctionArrayLvalueConversion(Base);
01163 
01164   return CheckPlaceholderExpr(Base);
01165 }
01166 
01167 /// Look up the given member of the given non-type-dependent
01168 /// expression.  This can return in one of two ways:
01169 ///  * If it returns a sentinel null-but-valid result, the caller will
01170 ///    assume that lookup was performed and the results written into
01171 ///    the provided structure.  It will take over from there.
01172 ///  * Otherwise, the returned expression will be produced in place of
01173 ///    an ordinary member expression.
01174 ///
01175 /// The ObjCImpDecl bit is a gross hack that will need to be properly
01176 /// fixed for ObjC++.
01177 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
01178                                    ExprResult &BaseExpr, bool &IsArrow,
01179                                    SourceLocation OpLoc, CXXScopeSpec &SS,
01180                                    Decl *ObjCImpDecl, bool HasTemplateArgs) {
01181   assert(BaseExpr.get() && "no base expression");
01182 
01183   // Perform default conversions.
01184   BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
01185   if (BaseExpr.isInvalid())
01186     return ExprError();
01187 
01188   QualType BaseType = BaseExpr.get()->getType();
01189   assert(!BaseType->isDependentType());
01190 
01191   DeclarationName MemberName = R.getLookupName();
01192   SourceLocation MemberLoc = R.getNameLoc();
01193 
01194   // For later type-checking purposes, turn arrow accesses into dot
01195   // accesses.  The only access type we support that doesn't follow
01196   // the C equivalence "a->b === (*a).b" is ObjC property accesses,
01197   // and those never use arrows, so this is unaffected.
01198   if (IsArrow) {
01199     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
01200       BaseType = Ptr->getPointeeType();
01201     else if (const ObjCObjectPointerType *Ptr
01202                = BaseType->getAs<ObjCObjectPointerType>())
01203       BaseType = Ptr->getPointeeType();
01204     else if (BaseType->isRecordType()) {
01205       // Recover from arrow accesses to records, e.g.:
01206       //   struct MyRecord foo;
01207       //   foo->bar
01208       // This is actually well-formed in C++ if MyRecord has an
01209       // overloaded operator->, but that should have been dealt with
01210       // by now--or a diagnostic message already issued if a problem
01211       // was encountered while looking for the overloaded operator->.
01212       if (!S.getLangOpts().CPlusPlus) {
01213         S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
01214           << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
01215           << FixItHint::CreateReplacement(OpLoc, ".");
01216       }
01217       IsArrow = false;
01218     } else if (BaseType->isFunctionType()) {
01219       goto fail;
01220     } else {
01221       S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
01222         << BaseType << BaseExpr.get()->getSourceRange();
01223       return ExprError();
01224     }
01225   }
01226 
01227   // Handle field access to simple records.
01228   if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
01229     TypoExpr *TE = nullptr;
01230     if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
01231                                  OpLoc, IsArrow, SS, HasTemplateArgs, TE))
01232       return ExprError();
01233 
01234     // Returning valid-but-null is how we indicate to the caller that
01235     // the lookup result was filled in. If typo correction was attempted and
01236     // failed, the lookup result will have been cleared--that combined with the
01237     // valid-but-null ExprResult will trigger the appropriate diagnostics.
01238     return ExprResult(TE);
01239   }
01240 
01241   // Handle ivar access to Objective-C objects.
01242   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
01243     if (!SS.isEmpty() && !SS.isInvalid()) {
01244       S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
01245         << 1 << SS.getScopeRep()
01246         << FixItHint::CreateRemoval(SS.getRange());
01247       SS.clear();
01248     }
01249 
01250     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
01251 
01252     // There are three cases for the base type:
01253     //   - builtin id (qualified or unqualified)
01254     //   - builtin Class (qualified or unqualified)
01255     //   - an interface
01256     ObjCInterfaceDecl *IDecl = OTy->getInterface();
01257     if (!IDecl) {
01258       if (S.getLangOpts().ObjCAutoRefCount &&
01259           (OTy->isObjCId() || OTy->isObjCClass()))
01260         goto fail;
01261       // There's an implicit 'isa' ivar on all objects.
01262       // But we only actually find it this way on objects of type 'id',
01263       // apparently.
01264       if (OTy->isObjCId() && Member->isStr("isa"))
01265         return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
01266                                            OpLoc, S.Context.getObjCClassType());
01267       if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
01268         return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
01269                                 ObjCImpDecl, HasTemplateArgs);
01270       goto fail;
01271     }
01272 
01273     if (S.RequireCompleteType(OpLoc, BaseType,
01274                               diag::err_typecheck_incomplete_tag,
01275                               BaseExpr.get()))
01276       return ExprError();
01277 
01278     ObjCInterfaceDecl *ClassDeclared = nullptr;
01279     ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
01280 
01281     if (!IV) {
01282       // Attempt to correct for typos in ivar names.
01283       auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
01284       Validator->IsObjCIvarLookup = IsArrow;
01285       if (TypoCorrection Corrected = S.CorrectTypo(
01286               R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
01287               std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
01288         IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
01289         S.diagnoseTypo(
01290             Corrected,
01291             S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
01292                 << IDecl->getDeclName() << MemberName);
01293 
01294         // Figure out the class that declares the ivar.
01295         assert(!ClassDeclared);
01296         Decl *D = cast<Decl>(IV->getDeclContext());
01297         if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
01298           D = CAT->getClassInterface();
01299         ClassDeclared = cast<ObjCInterfaceDecl>(D);
01300       } else {
01301         if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
01302           S.Diag(MemberLoc, diag::err_property_found_suggest)
01303               << Member << BaseExpr.get()->getType()
01304               << FixItHint::CreateReplacement(OpLoc, ".");
01305           return ExprError();
01306         }
01307 
01308         S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
01309             << IDecl->getDeclName() << MemberName
01310             << BaseExpr.get()->getSourceRange();
01311         return ExprError();
01312       }
01313     }
01314 
01315     assert(ClassDeclared);
01316 
01317     // If the decl being referenced had an error, return an error for this
01318     // sub-expr without emitting another error, in order to avoid cascading
01319     // error cases.
01320     if (IV->isInvalidDecl())
01321       return ExprError();
01322 
01323     // Check whether we can reference this field.
01324     if (S.DiagnoseUseOfDecl(IV, MemberLoc))
01325       return ExprError();
01326     if (IV->getAccessControl() != ObjCIvarDecl::Public &&
01327         IV->getAccessControl() != ObjCIvarDecl::Package) {
01328       ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
01329       if (ObjCMethodDecl *MD = S.getCurMethodDecl())
01330         ClassOfMethodDecl =  MD->getClassInterface();
01331       else if (ObjCImpDecl && S.getCurFunctionDecl()) {
01332         // Case of a c-function declared inside an objc implementation.
01333         // FIXME: For a c-style function nested inside an objc implementation
01334         // class, there is no implementation context available, so we pass
01335         // down the context as argument to this routine. Ideally, this context
01336         // need be passed down in the AST node and somehow calculated from the
01337         // AST for a function decl.
01338         if (ObjCImplementationDecl *IMPD =
01339               dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
01340           ClassOfMethodDecl = IMPD->getClassInterface();
01341         else if (ObjCCategoryImplDecl* CatImplClass =
01342                    dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
01343           ClassOfMethodDecl = CatImplClass->getClassInterface();
01344       }
01345       if (!S.getLangOpts().DebuggerSupport) {
01346         if (IV->getAccessControl() == ObjCIvarDecl::Private) {
01347           if (!declaresSameEntity(ClassDeclared, IDecl) ||
01348               !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
01349             S.Diag(MemberLoc, diag::error_private_ivar_access)
01350               << IV->getDeclName();
01351         } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
01352           // @protected
01353           S.Diag(MemberLoc, diag::error_protected_ivar_access)
01354               << IV->getDeclName();
01355       }
01356     }
01357     bool warn = true;
01358     if (S.getLangOpts().ObjCAutoRefCount) {
01359       Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
01360       if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
01361         if (UO->getOpcode() == UO_Deref)
01362           BaseExp = UO->getSubExpr()->IgnoreParenCasts();
01363       
01364       if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
01365         if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
01366           S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
01367           warn = false;
01368         }
01369     }
01370     if (warn) {
01371       if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
01372         ObjCMethodFamily MF = MD->getMethodFamily();
01373         warn = (MF != OMF_init && MF != OMF_dealloc && 
01374                 MF != OMF_finalize &&
01375                 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
01376       }
01377       if (warn)
01378         S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
01379     }
01380 
01381     ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
01382         IV, IV->getType(), MemberLoc, OpLoc, BaseExpr.get(), IsArrow);
01383 
01384     if (S.getLangOpts().ObjCAutoRefCount) {
01385       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
01386         if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
01387           S.recordUseOfEvaluatedWeak(Result);
01388       }
01389     }
01390 
01391     return Result;
01392   }
01393 
01394   // Objective-C property access.
01395   const ObjCObjectPointerType *OPT;
01396   if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
01397     if (!SS.isEmpty() && !SS.isInvalid()) {
01398       S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
01399           << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
01400       SS.clear();
01401     }
01402 
01403     // This actually uses the base as an r-value.
01404     BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
01405     if (BaseExpr.isInvalid())
01406       return ExprError();
01407 
01408     assert(S.Context.hasSameUnqualifiedType(BaseType,
01409                                             BaseExpr.get()->getType()));
01410 
01411     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
01412 
01413     const ObjCObjectType *OT = OPT->getObjectType();
01414 
01415     // id, with and without qualifiers.
01416     if (OT->isObjCId()) {
01417       // Check protocols on qualified interfaces.
01418       Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
01419       if (Decl *PMDecl =
01420               FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
01421         if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
01422           // Check the use of this declaration
01423           if (S.DiagnoseUseOfDecl(PD, MemberLoc))
01424             return ExprError();
01425 
01426           return new (S.Context)
01427               ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
01428                                   OK_ObjCProperty, MemberLoc, BaseExpr.get());
01429         }
01430 
01431         if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
01432           // Check the use of this method.
01433           if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
01434             return ExprError();
01435           Selector SetterSel =
01436             SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
01437                                                    S.PP.getSelectorTable(),
01438                                                    Member);
01439           ObjCMethodDecl *SMD = nullptr;
01440           if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
01441                                                      /*Property id*/ nullptr,
01442                                                      SetterSel, S.Context))
01443             SMD = dyn_cast<ObjCMethodDecl>(SDecl);
01444 
01445           return new (S.Context)
01446               ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
01447                                   OK_ObjCProperty, MemberLoc, BaseExpr.get());
01448         }
01449       }
01450       // Use of id.member can only be for a property reference. Do not
01451       // use the 'id' redefinition in this case.
01452       if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
01453         return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
01454                                 ObjCImpDecl, HasTemplateArgs);
01455 
01456       return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
01457                          << MemberName << BaseType);
01458     }
01459 
01460     // 'Class', unqualified only.
01461     if (OT->isObjCClass()) {
01462       // Only works in a method declaration (??!).
01463       ObjCMethodDecl *MD = S.getCurMethodDecl();
01464       if (!MD) {
01465         if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
01466           return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
01467                                   ObjCImpDecl, HasTemplateArgs);
01468 
01469         goto fail;
01470       }
01471 
01472       // Also must look for a getter name which uses property syntax.
01473       Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
01474       ObjCInterfaceDecl *IFace = MD->getClassInterface();
01475       ObjCMethodDecl *Getter;
01476       if ((Getter = IFace->lookupClassMethod(Sel))) {
01477         // Check the use of this method.
01478         if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
01479           return ExprError();
01480       } else
01481         Getter = IFace->lookupPrivateMethod(Sel, false);
01482       // If we found a getter then this may be a valid dot-reference, we
01483       // will look for the matching setter, in case it is needed.
01484       Selector SetterSel =
01485         SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
01486                                                S.PP.getSelectorTable(),
01487                                                Member);
01488       ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
01489       if (!Setter) {
01490         // If this reference is in an @implementation, also check for 'private'
01491         // methods.
01492         Setter = IFace->lookupPrivateMethod(SetterSel, false);
01493       }
01494 
01495       if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
01496         return ExprError();
01497 
01498       if (Getter || Setter) {
01499         return new (S.Context) ObjCPropertyRefExpr(
01500             Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
01501             OK_ObjCProperty, MemberLoc, BaseExpr.get());
01502       }
01503 
01504       if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
01505         return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
01506                                 ObjCImpDecl, HasTemplateArgs);
01507 
01508       return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
01509                          << MemberName << BaseType);
01510     }
01511 
01512     // Normal property access.
01513     return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
01514                                        MemberLoc, SourceLocation(), QualType(),
01515                                        false);
01516   }
01517 
01518   // Handle 'field access' to vectors, such as 'V.xx'.
01519   if (BaseType->isExtVectorType()) {
01520     // FIXME: this expr should store IsArrow.
01521     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
01522     ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
01523     QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
01524                                            Member, MemberLoc);
01525     if (ret.isNull())
01526       return ExprError();
01527 
01528     return new (S.Context)
01529         ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
01530   }
01531 
01532   // Adjust builtin-sel to the appropriate redefinition type if that's
01533   // not just a pointer to builtin-sel again.
01534   if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
01535       !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
01536     BaseExpr = S.ImpCastExprToType(
01537         BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
01538     return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
01539                             ObjCImpDecl, HasTemplateArgs);
01540   }
01541 
01542   // Failure cases.
01543  fail:
01544 
01545   // Recover from dot accesses to pointers, e.g.:
01546   //   type *foo;
01547   //   foo.bar
01548   // This is actually well-formed in two cases:
01549   //   - 'type' is an Objective C type
01550   //   - 'bar' is a pseudo-destructor name which happens to refer to
01551   //     the appropriate pointer type
01552   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
01553     if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
01554         MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
01555       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
01556           << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
01557           << FixItHint::CreateReplacement(OpLoc, "->");
01558 
01559       // Recurse as an -> access.
01560       IsArrow = true;
01561       return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
01562                               ObjCImpDecl, HasTemplateArgs);
01563     }
01564   }
01565 
01566   // If the user is trying to apply -> or . to a function name, it's probably
01567   // because they forgot parentheses to call that function.
01568   if (S.tryToRecoverWithCall(
01569           BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
01570           /*complain*/ false,
01571           IsArrow ? &isPointerToRecordType : &isRecordType)) {
01572     if (BaseExpr.isInvalid())
01573       return ExprError();
01574     BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
01575     return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
01576                             ObjCImpDecl, HasTemplateArgs);
01577   }
01578 
01579   S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
01580     << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
01581 
01582   return ExprError();
01583 }
01584 
01585 /// The main callback when the parser finds something like
01586 ///   expression . [nested-name-specifier] identifier
01587 ///   expression -> [nested-name-specifier] identifier
01588 /// where 'identifier' encompasses a fairly broad spectrum of
01589 /// possibilities, including destructor and operator references.
01590 ///
01591 /// \param OpKind either tok::arrow or tok::period
01592 /// \param HasTrailingLParen whether the next token is '(', which
01593 ///   is used to diagnose mis-uses of special members that can
01594 ///   only be called
01595 /// \param ObjCImpDecl the current Objective-C \@implementation
01596 ///   decl; this is an ugly hack around the fact that Objective-C
01597 ///   \@implementations aren't properly put in the context chain
01598 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
01599                                        SourceLocation OpLoc,
01600                                        tok::TokenKind OpKind,
01601                                        CXXScopeSpec &SS,
01602                                        SourceLocation TemplateKWLoc,
01603                                        UnqualifiedId &Id,
01604                                        Decl *ObjCImpDecl,
01605                                        bool HasTrailingLParen) {
01606   if (SS.isSet() && SS.isInvalid())
01607     return ExprError();
01608 
01609   // The only way a reference to a destructor can be used is to
01610   // immediately call it. If the next token is not a '(', produce
01611   // a diagnostic and build the call now.
01612   if (!HasTrailingLParen &&
01613       Id.getKind() == UnqualifiedId::IK_DestructorName) {
01614     ExprResult DtorAccess =
01615         ActOnMemberAccessExpr(S, Base, OpLoc, OpKind, SS, TemplateKWLoc, Id,
01616                               ObjCImpDecl, /*HasTrailingLParen*/true);
01617     if (DtorAccess.isInvalid())
01618       return DtorAccess;
01619     return DiagnoseDtorReference(Id.getLocStart(), DtorAccess.get());
01620   }
01621 
01622   // Warn about the explicit constructor calls Microsoft extension.
01623   if (getLangOpts().MicrosoftExt &&
01624       Id.getKind() == UnqualifiedId::IK_ConstructorName)
01625     Diag(Id.getSourceRange().getBegin(),
01626          diag::ext_ms_explicit_constructor_call);
01627 
01628   TemplateArgumentListInfo TemplateArgsBuffer;
01629 
01630   // Decompose the name into its component parts.
01631   DeclarationNameInfo NameInfo;
01632   const TemplateArgumentListInfo *TemplateArgs;
01633   DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
01634                          NameInfo, TemplateArgs);
01635 
01636   DeclarationName Name = NameInfo.getName();
01637   bool IsArrow = (OpKind == tok::arrow);
01638 
01639   NamedDecl *FirstQualifierInScope
01640     = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
01641 
01642   // This is a postfix expression, so get rid of ParenListExprs.
01643   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
01644   if (Result.isInvalid()) return ExprError();
01645   Base = Result.get();
01646 
01647   if (Base->getType()->isDependentType() || Name.isDependentName() ||
01648       isDependentScopeSpecifier(SS)) {
01649     return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
01650                                     TemplateKWLoc, FirstQualifierInScope,
01651                                     NameInfo, TemplateArgs);
01652   }
01653 
01654   ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl,
01655                                           HasTrailingLParen};
01656   return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
01657                                   TemplateKWLoc, FirstQualifierInScope,
01658                                   NameInfo, TemplateArgs, &ExtraArgs);
01659 }
01660 
01661 static ExprResult
01662 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
01663                         const CXXScopeSpec &SS, FieldDecl *Field,
01664                         DeclAccessPair FoundDecl,
01665                         const DeclarationNameInfo &MemberNameInfo) {
01666   // x.a is an l-value if 'a' has a reference type. Otherwise:
01667   // x.a is an l-value/x-value/pr-value if the base is (and note
01668   //   that *x is always an l-value), except that if the base isn't
01669   //   an ordinary object then we must have an rvalue.
01670   ExprValueKind VK = VK_LValue;
01671   ExprObjectKind OK = OK_Ordinary;
01672   if (!IsArrow) {
01673     if (BaseExpr->getObjectKind() == OK_Ordinary)
01674       VK = BaseExpr->getValueKind();
01675     else
01676       VK = VK_RValue;
01677   }
01678   if (VK != VK_RValue && Field->isBitField())
01679     OK = OK_BitField;
01680   
01681   // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
01682   QualType MemberType = Field->getType();
01683   if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
01684     MemberType = Ref->getPointeeType();
01685     VK = VK_LValue;
01686   } else {
01687     QualType BaseType = BaseExpr->getType();
01688     if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
01689 
01690     Qualifiers BaseQuals = BaseType.getQualifiers();
01691 
01692     // GC attributes are never picked up by members.
01693     BaseQuals.removeObjCGCAttr();
01694 
01695     // CVR attributes from the base are picked up by members,
01696     // except that 'mutable' members don't pick up 'const'.
01697     if (Field->isMutable()) BaseQuals.removeConst();
01698 
01699     Qualifiers MemberQuals
01700     = S.Context.getCanonicalType(MemberType).getQualifiers();
01701 
01702     assert(!MemberQuals.hasAddressSpace());
01703 
01704 
01705     Qualifiers Combined = BaseQuals + MemberQuals;
01706     if (Combined != MemberQuals)
01707       MemberType = S.Context.getQualifiedType(MemberType, Combined);
01708   }
01709 
01710   S.UnusedPrivateFields.remove(Field);
01711 
01712   ExprResult Base =
01713   S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
01714                                   FoundDecl, Field);
01715   if (Base.isInvalid())
01716     return ExprError();
01717   return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, SS,
01718                          /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
01719                          MemberNameInfo, MemberType, VK, OK);
01720 }
01721 
01722 /// Builds an implicit member access expression.  The current context
01723 /// is known to be an instance method, and the given unqualified lookup
01724 /// set is known to contain only instance members, at least one of which
01725 /// is from an appropriate type.
01726 ExprResult
01727 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
01728                               SourceLocation TemplateKWLoc,
01729                               LookupResult &R,
01730                               const TemplateArgumentListInfo *TemplateArgs,
01731                               bool IsKnownInstance) {
01732   assert(!R.empty() && !R.isAmbiguous());
01733   
01734   SourceLocation loc = R.getNameLoc();
01735 
01736   // If this is known to be an instance access, go ahead and build an
01737   // implicit 'this' expression now.
01738   // 'this' expression now.
01739   QualType ThisTy = getCurrentThisType();
01740   assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
01741 
01742   Expr *baseExpr = nullptr; // null signifies implicit access
01743   if (IsKnownInstance) {
01744     SourceLocation Loc = R.getNameLoc();
01745     if (SS.getRange().isValid())
01746       Loc = SS.getRange().getBegin();
01747     CheckCXXThisCapture(Loc);
01748     baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
01749   }
01750 
01751   return BuildMemberReferenceExpr(baseExpr, ThisTy,
01752                                   /*OpLoc*/ SourceLocation(),
01753                                   /*IsArrow*/ true,
01754                                   SS, TemplateKWLoc,
01755                                   /*FirstQualifierInScope*/ nullptr,
01756                                   R, TemplateArgs);
01757 }