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