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