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