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