Coverage Report

Created: 2020-09-22 08:39

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