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