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