blob: 2da4488d3f6c77123c64a33cb2f0f55be661830e [file] [log] [blame]
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001//===--- 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//===----------------------------------------------------------------------===//
Stephen Hines176edba2014-12-01 14:53:08 -080013#include "clang/Sema/Overload.h"
Faisal Valic00e4192013-11-07 05:17:06 +000014#include "clang/AST/ASTLambda.h"
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000015#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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070024#include "clang/Sema/SemaInternal.h"
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000025
26using namespace clang;
27using namespace sema;
28
Richard Smithf62c6902012-11-22 00:24:47 +000029typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
30static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
31 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
32 return !Bases.count(Base->getCanonicalDecl());
33}
34
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000035/// Determines if the given class is provably not derived from all of
36/// the prospective base classes.
Richard Smithf62c6902012-11-22 00:24:47 +000037static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
38 const BaseSet &Bases) {
39 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
40 return BaseIsNotInSet(Record, BasesPtr) &&
41 Record->forallBases(BaseIsNotInSet, BasesPtr);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000042}
43
44enum IMAKind {
45 /// The reference is definitely not an instance member access.
46 IMA_Static,
47
48 /// The reference may be an implicit instance member access.
49 IMA_Mixed,
50
Eli Friedman9bc291d2012-01-18 03:53:45 +000051 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000052 /// so, because the context is not an instance method.
53 IMA_Mixed_StaticContext,
54
55 /// The reference may be to an instance member, but it is invalid if
56 /// so, because the context is from an unrelated class.
57 IMA_Mixed_Unrelated,
58
59 /// The reference is definitely an implicit instance member access.
60 IMA_Instance,
61
62 /// The reference may be to an unresolved using declaration.
63 IMA_Unresolved,
64
John McCallaeeacf72013-05-03 00:10:13 +000065 /// The reference is a contextually-permitted abstract member reference.
66 IMA_Abstract,
67
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000068 /// The reference may be to an unresolved using declaration and the
69 /// context is not an instance method.
70 IMA_Unresolved_StaticContext,
71
Eli Friedmanef331b72012-01-20 01:26:23 +000072 // The reference refers to a field which is not a member of the containing
73 // class, which is allowed because we're in C++11 mode and the context is
74 // unevaluated.
75 IMA_Field_Uneval_Context,
Eli Friedman9bc291d2012-01-18 03:53:45 +000076
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000077 /// All possible referrents are instance members and the current
78 /// context is not an instance method.
79 IMA_Error_StaticContext,
80
81 /// All possible referrents are instance members of an unrelated
82 /// class.
83 IMA_Error_Unrelated
84};
85
86/// The given lookup names class member(s) and is not being used for
87/// an address-of-member expression. Classify the type of access
88/// according to whether it's possible that this reference names an
Eli Friedman9bc291d2012-01-18 03:53:45 +000089/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000090/// conservatively answer "yes", in which case some errors will simply
91/// not be caught until template-instantiation.
92static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000093 const LookupResult &R) {
94 assert(!R.empty() && (*R.begin())->isCXXClassMember());
95
96 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
97
Douglas Gregorcefc3af2012-04-16 07:05:22 +000098 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
99 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000100
101 if (R.isUnresolvableResult())
102 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
103
104 // Collect all the declaring classes of instance members we find.
105 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000106 bool isField = false;
Richard Smithf62c6902012-11-22 00:24:47 +0000107 BaseSet Classes;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000108 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
109 NamedDecl *D = *I;
110
111 if (D->isCXXInstanceMember()) {
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -0700112 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
113 isa<IndirectFieldDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000114
115 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
116 Classes.insert(R->getCanonicalDecl());
117 }
118 else
119 hasNonInstance = true;
120 }
121
122 // If we didn't find any instance members, it can't be an implicit
123 // member reference.
124 if (Classes.empty())
125 return IMA_Static;
John McCallaeeacf72013-05-03 00:10:13 +0000126
127 // C++11 [expr.prim.general]p12:
128 // An id-expression that denotes a non-static data member or non-static
129 // member function of a class can only be used:
130 // (...)
131 // - if that id-expression denotes a non-static data member and it
132 // appears in an unevaluated operand.
133 //
134 // This rule is specific to C++11. However, we also permit this form
135 // in unevaluated inline assembly operands, like the operand to a SIZE.
136 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
137 assert(!AbstractInstanceResult);
138 switch (SemaRef.ExprEvalContexts.back().Context) {
139 case Sema::Unevaluated:
140 if (isField && SemaRef.getLangOpts().CPlusPlus11)
141 AbstractInstanceResult = IMA_Field_Uneval_Context;
142 break;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000143
John McCallaeeacf72013-05-03 00:10:13 +0000144 case Sema::UnevaluatedAbstract:
145 AbstractInstanceResult = IMA_Abstract;
146 break;
147
148 case Sema::ConstantEvaluated:
149 case Sema::PotentiallyEvaluated:
150 case Sema::PotentiallyEvaluatedIfUsed:
151 break;
Richard Smith2c8aee42012-02-25 10:04:07 +0000152 }
153
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000154 // If the current context is not an instance method, it can't be
155 // an implicit member reference.
156 if (isStaticContext) {
157 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000158 return IMA_Mixed_StaticContext;
159
John McCallaeeacf72013-05-03 00:10:13 +0000160 return AbstractInstanceResult ? AbstractInstanceResult
161 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000162 }
163
164 CXXRecordDecl *contextClass;
165 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
166 contextClass = MD->getParent()->getCanonicalDecl();
167 else
168 contextClass = cast<CXXRecordDecl>(DC);
169
170 // [class.mfct.non-static]p3:
171 // ...is used in the body of a non-static member function of class X,
172 // if name lookup (3.4.1) resolves the name in the id-expression to a
173 // non-static non-type member of some class C [...]
174 // ...if C is not X or a base class of X, the class member access expression
175 // is ill-formed.
176 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000177 contextClass->getCanonicalDecl() !=
Richard Smithf62c6902012-11-22 00:24:47 +0000178 R.getNamingClass()->getCanonicalDecl()) {
179 // If the naming class is not the current context, this was a qualified
180 // member name lookup, and it's sufficient to check that we have the naming
181 // class as a base class.
182 Classes.clear();
Richard Smith746619a2012-11-22 00:40:54 +0000183 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithf62c6902012-11-22 00:24:47 +0000184 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000185
186 // If we can prove that the current context is unrelated to all the
187 // declaring classes, it can't be an implicit member reference (in
188 // which case it's an error if any of those members are selected).
Richard Smithf62c6902012-11-22 00:24:47 +0000189 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smithd390de92012-02-25 10:20:59 +0000190 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallaeeacf72013-05-03 00:10:13 +0000191 AbstractInstanceResult ? AbstractInstanceResult :
192 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000193
194 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
195}
196
197/// Diagnose a reference to a field with no object available.
Richard Smitha85cf392012-04-05 01:13:04 +0000198static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000199 const CXXScopeSpec &SS,
Richard Smitha85cf392012-04-05 01:13:04 +0000200 NamedDecl *Rep,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000201 const DeclarationNameInfo &nameInfo) {
202 SourceLocation Loc = nameInfo.getLoc();
203 SourceRange Range(Loc);
204 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman9bc291d2012-01-18 03:53:45 +0000205
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700206 // Look through using shadow decls and aliases.
207 Rep = Rep->getUnderlyingDecl();
208
Richard Smitha85cf392012-04-05 01:13:04 +0000209 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
210 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700211 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smitha85cf392012-04-05 01:13:04 +0000212 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
213
214 bool InStaticMethod = Method && Method->isStatic();
215 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
216
217 if (IsField && InStaticMethod)
218 // "invalid use of member 'x' in static member function"
219 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
220 << Range << nameInfo.getName();
221 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
222 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
223 // Unqualified lookup in a non-static member function found a member of an
224 // enclosing class.
225 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
226 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
227 else if (IsField)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000228 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smitha85cf392012-04-05 01:13:04 +0000229 << nameInfo.getName() << Range;
230 else
231 SemaRef.Diag(Loc, diag::err_member_call_without_object)
232 << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000233}
234
235/// Builds an expression which might be an implicit member expression.
236ExprResult
237Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000238 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000239 LookupResult &R,
240 const TemplateArgumentListInfo *TemplateArgs) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700241 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000242 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000243 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000244
245 case IMA_Mixed:
246 case IMA_Mixed_Unrelated:
247 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000248 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000249
Richard Smithd390de92012-02-25 10:20:59 +0000250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
253 // Fall through.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000254 case IMA_Static:
John McCallaeeacf72013-05-03 00:10:13 +0000255 case IMA_Abstract:
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000256 case IMA_Mixed_StaticContext:
257 case IMA_Unresolved_StaticContext:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000258 if (TemplateArgs || TemplateKWLoc.isValid())
259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000260 return BuildDeclarationNameExpr(SS, R, false);
261
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
Richard Smitha85cf392012-04-05 01:13:04 +0000264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000265 R.getLookupNameInfo());
266 return ExprError();
267 }
268
269 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000270}
271
Stephen Hines6fbdfec2011-09-09 16:26:17 -0700272/// Determine whether input char is from rgba component set.
273static bool
274IsRGBA(char c) {
275 switch (c) {
276 case 'r':
277 case 'g':
278 case 'b':
279 case 'a':
280 return true;
281 default:
282 return false;
283 }
284}
285
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000286/// Check an ext-vector component access expression.
287///
288/// VK should be set in advance to the value kind of the base
289/// expression.
290static QualType
291CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
292 SourceLocation OpLoc, const IdentifierInfo *CompName,
293 SourceLocation CompLoc) {
294 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
295 // see FIXME there.
296 //
297 // FIXME: This logic can be greatly simplified by splitting it along
298 // halving/not halving and reworking the component checking.
299 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
300
301 // The vector accessor can't exceed the number of elements.
302 const char *compStr = CompName->getNameStart();
303
304 // This flag determines whether or not the component is one of the four
305 // special names that indicate a subset of exactly half the elements are
306 // to be selected.
307 bool HalvingSwizzle = false;
308
309 // This flag determines whether or not CompName has an 's' char prefix,
310 // indicating that it is a string of hex values to be used as vector indices.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700311 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000312
313 bool HasRepeated = false;
314 bool HasIndex[16] = {};
315
316 int Idx;
317
318 // Check that we've found one of the special components, or that the component
319 // names must come from the same set.
320 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
321 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
322 HalvingSwizzle = true;
323 } else if (!HexSwizzle &&
324 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
Stephen Hines6fbdfec2011-09-09 16:26:17 -0700325 bool HasRGBA = IsRGBA(*compStr);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000326 do {
Stephen Hines6fbdfec2011-09-09 16:26:17 -0700327 if (HasRGBA != IsRGBA(*compStr))
328 break;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000329 if (HasIndex[Idx]) HasRepeated = true;
330 HasIndex[Idx] = true;
331 compStr++;
332 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
333 } else {
334 if (HexSwizzle) compStr++;
335 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
336 if (HasIndex[Idx]) HasRepeated = true;
337 HasIndex[Idx] = true;
338 compStr++;
339 }
340 }
341
342 if (!HalvingSwizzle && *compStr) {
343 // We didn't get to the end of the string. This means the component names
344 // didn't come from the same set *or* we encountered an illegal name.
345 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000346 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000347 return QualType();
348 }
349
350 // Ensure no component accessor exceeds the width of the vector type it
351 // operates on.
352 if (!HalvingSwizzle) {
353 compStr = CompName->getNameStart();
354
355 if (HexSwizzle)
356 compStr++;
357
358 while (*compStr) {
359 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
360 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
361 << baseType << SourceRange(CompLoc);
362 return QualType();
363 }
364 }
365 }
366
367 // The component accessor looks fine - now we need to compute the actual type.
368 // The vector type is implied by the component accessor. For example,
369 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
370 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
371 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
372 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
373 : CompName->getLength();
374 if (HexSwizzle)
375 CompSize--;
376
377 if (CompSize == 1)
378 return vecType->getElementType();
379
380 if (HasRepeated) VK = VK_RValue;
381
382 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
383 // Now look up the TypeDefDecl from the vector type. Without this,
384 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000385 for (Sema::ExtVectorDeclsType::iterator
Axel Naumann0ec56b72012-10-18 19:05:02 +0000386 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregord58a0a52011-07-28 00:39:29 +0000387 E = S.ExtVectorDecls.end();
388 I != E; ++I) {
389 if ((*I)->getUnderlyingType() == VT)
390 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000391 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000392
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000393 return VT; // should never get here (a typedef type should always be found).
394}
395
396static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
397 IdentifierInfo *Member,
398 const Selector &Sel,
399 ASTContext &Context) {
400 if (Member)
401 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
402 return PD;
403 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
404 return OMD;
405
Stephen Hines651f13c2014-04-23 16:59:28 -0700406 for (const auto *I : PDecl->protocols()) {
407 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000408 Context))
409 return D;
410 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700411 return nullptr;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000412}
413
414static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
415 IdentifierInfo *Member,
416 const Selector &Sel,
417 ASTContext &Context) {
418 // Check protocols on qualified interfaces.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700419 Decl *GDecl = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700420 for (const auto *I : QIdTy->quals()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000421 if (Member)
Stephen Hines651f13c2014-04-23 16:59:28 -0700422 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000423 GDecl = PD;
424 break;
425 }
426 // Also must look for a getter or setter name which uses property syntax.
Stephen Hines651f13c2014-04-23 16:59:28 -0700427 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000428 GDecl = OMD;
429 break;
430 }
431 }
432 if (!GDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700433 for (const auto *I : QIdTy->quals()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000434 // Search in the protocol-qualifier list of current protocol.
Stephen Hines651f13c2014-04-23 16:59:28 -0700435 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000436 if (GDecl)
437 return GDecl;
438 }
439 }
440 return GDecl;
441}
442
443ExprResult
444Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
445 bool IsArrow, SourceLocation OpLoc,
446 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000447 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000448 NamedDecl *FirstQualifierInScope,
449 const DeclarationNameInfo &NameInfo,
450 const TemplateArgumentListInfo *TemplateArgs) {
451 // Even in dependent contexts, try to diagnose base expressions with
452 // obviously wrong types, e.g.:
453 //
454 // T* t;
455 // t.f;
456 //
457 // In Obj-C++, however, the above expression is valid, since it could be
458 // accessing the 'f' property if T is an Obj-C interface. The extra check
459 // allows this, while still reporting an error if T is a struct pointer.
460 if (!IsArrow) {
461 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikie4e4d0842012-03-11 07:00:24 +0000462 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000463 PT->getPointeeType()->isRecordType())) {
464 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +0000465 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +0000466 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000467 return ExprError();
468 }
469 }
470
471 assert(BaseType->isDependentType() ||
472 NameInfo.getName().isDependentName() ||
473 isDependentScopeSpecifier(SS));
474
475 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
476 // must have pointer type, and the accessed type is the pointee.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700477 return CXXDependentScopeMemberExpr::Create(
478 Context, BaseExpr, BaseType, IsArrow, OpLoc,
479 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
480 NameInfo, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000481}
482
483/// We know that the given qualified member reference points only to
484/// declarations which do not belong to the static type of the base
485/// expression. Diagnose the problem.
486static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
487 Expr *BaseExpr,
488 QualType BaseType,
489 const CXXScopeSpec &SS,
490 NamedDecl *rep,
491 const DeclarationNameInfo &nameInfo) {
492 // If this is an implicit member access, use a different set of
493 // diagnostics.
494 if (!BaseExpr)
Richard Smitha85cf392012-04-05 01:13:04 +0000495 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000496
497 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
498 << SS.getRange() << rep << BaseType;
499}
500
501// Check whether the declarations we found through a nested-name
502// specifier in a member expression are actually members of the base
503// type. The restriction here is:
504//
505// C++ [expr.ref]p2:
506// ... In these cases, the id-expression shall name a
507// member of the class or of one of its base classes.
508//
509// So it's perfectly legitimate for the nested-name specifier to name
510// an unrelated class, and for us to find an overload set including
511// decls from classes which are not superclasses, as long as the decl
512// we actually pick through overload resolution is from a superclass.
513bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
514 QualType BaseType,
515 const CXXScopeSpec &SS,
516 const LookupResult &R) {
Richard Smithf62c6902012-11-22 00:24:47 +0000517 CXXRecordDecl *BaseRecord =
518 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
519 if (!BaseRecord) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000520 // We can't check this yet because the base type is still
521 // dependent.
522 assert(BaseType->isDependentType());
523 return false;
524 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000525
526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
527 // If this is an implicit member reference and we find a
528 // non-instance member, it's not an error.
529 if (!BaseExpr && !(*I)->isCXXInstanceMember())
530 return false;
531
532 // Note that we use the DC of the decl, not the underlying decl.
533 DeclContext *DC = (*I)->getDeclContext();
534 while (DC->isTransparentContext())
535 DC = DC->getParent();
536
537 if (!DC->isRecord())
538 continue;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000539
Richard Smithf62c6902012-11-22 00:24:47 +0000540 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
541 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
542 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000543 return false;
544 }
545
546 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
547 R.getRepresentativeDecl(),
548 R.getLookupNameInfo());
549 return true;
550}
551
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000552namespace {
553
554// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +0000555// FunctionTemplateDecl and are declared in the current record or, for a C++
556// classes, one of its base classes.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000557class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Stephen Hines176edba2014-12-01 14:53:08 -0800558public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +0000559 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Stephen Hines176edba2014-12-01 14:53:08 -0800560 : Record(RTy->getDecl()) {
561 // Don't add bare keywords to the consumer since they will always fail
562 // validation by virtue of not being associated with any decls.
563 WantTypeSpecifiers = false;
564 WantExpressionKeywords = false;
565 WantCXXNamedCasts = false;
566 WantFunctionLikeCasts = false;
567 WantRemainingKeywords = false;
568 }
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +0000569
Stephen Hines651f13c2014-04-23 16:59:28 -0700570 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000571 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +0000572 // Don't accept candidates that cannot be member functions, constants,
573 // variables, or templates.
574 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
575 return false;
576
577 // Accept candidates that occur in the current record.
578 if (Record->containsDecl(ND))
579 return true;
580
581 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
582 // Accept candidates that occur in any of the current class' base classes.
Stephen Hines651f13c2014-04-23 16:59:28 -0700583 for (const auto &BS : RD->bases()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800584 if (const RecordType *BSTy =
585 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +0000586 if (BSTy->getDecl()->containsDecl(ND))
587 return true;
588 }
589 }
590 }
591
592 return false;
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000593 }
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +0000594
Stephen Hines176edba2014-12-01 14:53:08 -0800595private:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +0000596 const RecordDecl *const Record;
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000597};
598
599}
600
Stephen Hines176edba2014-12-01 14:53:08 -0800601static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
602 Expr *BaseExpr,
603 const RecordType *RTy,
604 SourceLocation OpLoc, bool IsArrow,
605 CXXScopeSpec &SS, bool HasTemplateArgs,
606 TypoExpr *&TE) {
607 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000608 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000609 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
610 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregord10099e2012-05-04 16:32:21 +0000611 diag::err_typecheck_incomplete_tag,
612 BaseRange))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000613 return true;
614
615 if (HasTemplateArgs) {
616 // LookupTemplateName doesn't expect these both to exist simultaneously.
617 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
618
619 bool MOUS;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700620 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000621 return false;
622 }
623
624 DeclContext *DC = RDecl;
625 if (SS.isSet()) {
626 // If the member name was a qualified-id, look into the
627 // nested-name-specifier.
628 DC = SemaRef.computeDeclContext(SS, false);
629
630 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
631 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Stephen Hines176edba2014-12-01 14:53:08 -0800632 << SS.getRange() << DC;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000633 return true;
634 }
635
636 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
637
638 if (!isa<TypeDecl>(DC)) {
639 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Stephen Hines176edba2014-12-01 14:53:08 -0800640 << DC << SS.getRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000641 return true;
642 }
643 }
644
645 // The record definition is complete, now look up the member.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700646 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000647
648 if (!R.empty())
649 return false;
650
Stephen Hines176edba2014-12-01 14:53:08 -0800651 DeclarationName Typo = R.getLookupName();
652 SourceLocation TypoLoc = R.getNameLoc();
653 TE = SemaRef.CorrectTypoDelayed(
654 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
655 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
656 [=, &SemaRef](const TypoCorrection &TC) {
657 if (TC) {
658 assert(!TC.isKeyword() &&
659 "Got a keyword as a correction for a member!");
660 bool DroppedSpecifier =
661 TC.WillReplaceSpecifier() &&
662 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
663 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
664 << Typo << DC << DroppedSpecifier
665 << SS.getRange());
666 } else {
667 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
668 }
669 },
670 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
671 R.clear(); // Ensure there's no decls lingering in the shared state.
672 R.suppressDiagnostics();
673 R.setLookupName(TC.getCorrection());
674 for (NamedDecl *ND : TC)
675 R.addDecl(ND);
676 R.resolveKind();
677 return SemaRef.BuildMemberReferenceExpr(
678 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
679 nullptr, R, nullptr);
680 },
681 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000682
683 return false;
684}
685
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700686static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
687 ExprResult &BaseExpr, bool &IsArrow,
688 SourceLocation OpLoc, CXXScopeSpec &SS,
689 Decl *ObjCImpDecl, bool HasTemplateArgs);
690
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000691ExprResult
692Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
693 SourceLocation OpLoc, bool IsArrow,
694 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000695 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000696 NamedDecl *FirstQualifierInScope,
697 const DeclarationNameInfo &NameInfo,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700698 const TemplateArgumentListInfo *TemplateArgs,
699 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000700 if (BaseType->isDependentType() ||
701 (SS.isSet() && isDependentScopeSpecifier(SS)))
702 return ActOnDependentMemberExpr(Base, BaseType,
703 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000704 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000705 NameInfo, TemplateArgs);
706
707 LookupResult R(*this, NameInfo, LookupMemberName);
708
709 // Implicit member accesses.
710 if (!Base) {
Stephen Hines176edba2014-12-01 14:53:08 -0800711 TypoExpr *TE = nullptr;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000712 QualType RecordTy = BaseType;
713 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Stephen Hines176edba2014-12-01 14:53:08 -0800714 if (LookupMemberExprInRecord(*this, R, nullptr,
715 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
716 SS, TemplateArgs != nullptr, TE))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000717 return ExprError();
Stephen Hines176edba2014-12-01 14:53:08 -0800718 if (TE)
719 return TE;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000720
721 // Explicit member accesses.
722 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700723 ExprResult BaseResult = Base;
724 ExprResult Result = LookupMemberExpr(
725 *this, R, BaseResult, IsArrow, OpLoc, SS,
726 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
727 TemplateArgs != nullptr);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000728
729 if (BaseResult.isInvalid())
730 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700731 Base = BaseResult.get();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000732
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700733 if (Result.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000734 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000735
736 if (Result.get())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000737 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000738
739 // LookupMemberExpr can modify Base, and thus change BaseType
740 BaseType = Base->getType();
741 }
742
743 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000744 OpLoc, IsArrow, SS, TemplateKWLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700745 FirstQualifierInScope, R, TemplateArgs,
746 false, ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000747}
748
749static ExprResult
750BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700751 SourceLocation OpLoc, const CXXScopeSpec &SS,
752 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000753 const DeclarationNameInfo &MemberNameInfo);
754
755ExprResult
756Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
757 SourceLocation loc,
758 IndirectFieldDecl *indirectField,
Eli Friedmanbf03b372013-07-16 00:01:31 +0000759 DeclAccessPair foundDecl,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000760 Expr *baseObjectExpr,
761 SourceLocation opLoc) {
762 // First, build the expression that refers to the base object.
763
764 bool baseObjectIsPointer = false;
765 Qualifiers baseQuals;
766
767 // Case 1: the base of the indirect field is not a field.
768 VarDecl *baseVariable = indirectField->getVarDecl();
769 CXXScopeSpec EmptySS;
770 if (baseVariable) {
771 assert(baseVariable->getType()->isRecordType());
772
773 // In principle we could have a member access expression that
774 // accesses an anonymous struct/union that's a static member of
775 // the base object's class. However, under the current standard,
776 // static data members cannot be anonymous structs or unions.
777 // Supporting this is as easy as building a MemberExpr here.
778 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
779
780 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
781
782 ExprResult result
783 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
784 if (result.isInvalid()) return ExprError();
785
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700786 baseObjectExpr = result.get();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000787 baseObjectIsPointer = false;
788 baseQuals = baseObjectExpr->getType().getQualifiers();
789
790 // Case 2: the base of the indirect field is a field and the user
791 // wrote a member expression.
792 } else if (baseObjectExpr) {
793 // The caller provided the base object expression. Determine
794 // whether its a pointer and whether it adds any qualifiers to the
795 // anonymous struct/union fields we're looking into.
796 QualType objectType = baseObjectExpr->getType();
797
798 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
799 baseObjectIsPointer = true;
800 objectType = ptr->getPointeeType();
801 } else {
802 baseObjectIsPointer = false;
803 }
804 baseQuals = objectType.getQualifiers();
805
806 // Case 3: the base of the indirect field is a field and we should
807 // build an implicit member access.
808 } else {
809 // We've found a member of an anonymous struct/union that is
810 // inside a non-anonymous struct/union, so in a well-formed
811 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000812 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000813 if (ThisTy.isNull()) {
814 Diag(loc, diag::err_invalid_member_use_in_static_method)
815 << indirectField->getDeclName();
816 return ExprError();
817 }
818
819 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000820 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000821 baseObjectExpr
822 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
823 baseObjectIsPointer = true;
824 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
825 }
826
827 // Build the implicit member references to the field of the
828 // anonymous struct/union.
829 Expr *result = baseObjectExpr;
830 IndirectFieldDecl::chain_iterator
831 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
832
833 // Build the first member access in the chain with full information.
834 if (!baseVariable) {
835 FieldDecl *field = cast<FieldDecl>(*FI);
836
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000837 // Make a nameInfo that properly uses the anonymous name.
838 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700839
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000840 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700841 SourceLocation(), EmptySS, field,
842 foundDecl, memberNameInfo).get();
Eli Friedmanbf03b372013-07-16 00:01:31 +0000843 if (!result)
844 return ExprError();
845
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000846 // FIXME: check qualified member access
847 }
848
849 // In all cases, we should now skip the first declaration in the chain.
850 ++FI;
851
852 while (FI != FEnd) {
853 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmanbf03b372013-07-16 00:01:31 +0000854
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000855 // FIXME: these are somewhat meaningless
856 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmanbf03b372013-07-16 00:01:31 +0000857 DeclAccessPair fakeFoundDecl =
858 DeclAccessPair::make(field, field->getAccess());
859
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700860 result =
861 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
862 SourceLocation(), (FI == FEnd ? SS : EmptySS),
863 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000864 }
865
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700866 return result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000867}
868
John McCall76da55d2013-04-16 07:28:30 +0000869static ExprResult
870BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
871 const CXXScopeSpec &SS,
872 MSPropertyDecl *PD,
873 const DeclarationNameInfo &NameInfo) {
874 // Property names are always simple identifiers and therefore never
875 // require any interesting additional storage.
876 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
877 S.Context.PseudoObjectTy, VK_LValue,
878 SS.getWithLocInContext(S.Context),
879 NameInfo.getLoc());
880}
881
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000882/// \brief Build a MemberExpr AST node.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700883static MemberExpr *BuildMemberExpr(
884 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
885 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
886 ValueDecl *Member, DeclAccessPair FoundDecl,
887 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
888 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith3bad5b12011-10-27 22:11:44 +0000889 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700890 MemberExpr *E = MemberExpr::Create(
891 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
892 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedman5f2987c2012-02-02 03:46:19 +0000893 SemaRef.MarkMemberReferenced(E);
894 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000895}
896
897ExprResult
898Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
899 SourceLocation OpLoc, bool IsArrow,
900 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000901 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000902 NamedDecl *FirstQualifierInScope,
903 LookupResult &R,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000904 const TemplateArgumentListInfo *TemplateArgs,
905 bool SuppressQualifierCheck,
906 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000907 QualType BaseType = BaseExprType;
908 if (IsArrow) {
909 assert(BaseType->isPointerType());
John McCalle859fbf2011-10-25 17:37:35 +0000910 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000911 }
912 R.setBaseObjectType(BaseType);
Faisal Valic00e4192013-11-07 05:17:06 +0000913
914 LambdaScopeInfo *const CurLSI = getCurLambda();
915 // If this is an implicit member reference and the overloaded
916 // name refers to both static and non-static member functions
917 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
918 // check if we should/can capture 'this'...
919 // Keep this example in mind:
920 // struct X {
921 // void f(int) { }
922 // static void f(double) { }
923 //
924 // int g() {
925 // auto L = [=](auto a) {
926 // return [](int i) {
927 // return [=](auto b) {
928 // f(b);
929 // //f(decltype(a){});
930 // };
931 // };
932 // };
933 // auto M = L(0.0);
934 // auto N = M(3);
935 // N(5.32); // OK, must not error.
936 // return 0;
937 // }
938 // };
939 //
940 if (!BaseExpr && CurLSI) {
941 SourceLocation Loc = R.getNameLoc();
942 if (SS.getRange().isValid())
943 Loc = SS.getRange().getBegin();
944 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
945 // If the enclosing function is not dependent, then this lambda is
946 // capture ready, so if we can capture this, do so.
947 if (!EnclosingFunctionCtx->isDependentContext()) {
948 // If the current lambda and all enclosing lambdas can capture 'this' -
949 // then go ahead and capture 'this' (since our unresolved overload set
950 // contains both static and non-static member functions).
951 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
952 CheckCXXThisCapture(Loc);
953 } else if (CurContext->isDependentContext()) {
954 // ... since this is an implicit member reference, that might potentially
955 // involve a 'this' capture, mark 'this' for potential capture in
956 // enclosing lambdas.
957 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
958 CurLSI->addPotentialThisCapture(Loc);
959 }
960 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000961 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
962 DeclarationName MemberName = MemberNameInfo.getName();
963 SourceLocation MemberLoc = MemberNameInfo.getLoc();
964
965 if (R.isAmbiguous())
966 return ExprError();
967
968 if (R.empty()) {
969 // Rederive where we looked up.
970 DeclContext *DC = (SS.isSet()
971 ? computeDeclContext(SS, false)
972 : BaseType->getAs<RecordType>()->getDecl());
973
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000974 if (ExtraArgs) {
975 ExprResult RetryExpr;
976 if (!IsArrow && BaseExpr) {
Kaelyn Uhrain111263c2012-05-01 01:17:53 +0000977 SFINAETrap Trap(*this, true);
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000978 ParsedType ObjectType;
979 bool MayBePseudoDestructor = false;
980 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
981 OpLoc, tok::arrow, ObjectType,
982 MayBePseudoDestructor);
983 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
984 CXXScopeSpec TempSS(SS);
985 RetryExpr = ActOnMemberAccessExpr(
986 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700987 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000988 }
989 if (Trap.hasErrorOccurred())
990 RetryExpr = ExprError();
991 }
992 if (RetryExpr.isUsable()) {
993 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
994 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
995 return RetryExpr;
996 }
997 }
998
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000999 Diag(R.getNameLoc(), diag::err_no_member)
1000 << MemberName << DC
1001 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1002 return ExprError();
1003 }
1004
1005 // Diagnose lookups that find only declarations from a non-base
1006 // type. This is possible for either qualified lookups (which may
1007 // have been qualified with an unrelated type) or implicit member
1008 // expressions (which were found with unqualified lookup and thus
1009 // may have come from an enclosing scope). Note that it's okay for
1010 // lookup to find declarations from a non-base type as long as those
1011 // aren't the ones picked by overload resolution.
1012 if ((SS.isSet() || !BaseExpr ||
1013 (isa<CXXThisExpr>(BaseExpr) &&
1014 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1015 !SuppressQualifierCheck &&
1016 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1017 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +00001018
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001019 // Construct an unresolved result if we in fact got an unresolved
1020 // result.
1021 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1022 // Suppress any lookup-related diagnostics; we'll do these when we
1023 // pick a member.
1024 R.suppressDiagnostics();
1025
1026 UnresolvedMemberExpr *MemExpr
1027 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1028 BaseExpr, BaseExprType,
1029 IsArrow, OpLoc,
1030 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001031 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001032 TemplateArgs, R.begin(), R.end());
1033
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001034 return MemExpr;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001035 }
1036
1037 assert(R.isSingleResult());
1038 DeclAccessPair FoundDecl = R.begin().getPair();
1039 NamedDecl *MemberDecl = R.getFoundDecl();
1040
1041 // FIXME: diagnose the presence of template arguments now.
1042
1043 // If the decl being referenced had an error, return an error for this
1044 // sub-expr without emitting another error, in order to avoid cascading
1045 // error cases.
1046 if (MemberDecl->isInvalidDecl())
1047 return ExprError();
1048
1049 // Handle the implicit-member-access case.
1050 if (!BaseExpr) {
1051 // If this is not an instance member, convert to a non-member access.
1052 if (!MemberDecl->isCXXInstanceMember())
1053 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1054
1055 SourceLocation Loc = R.getNameLoc();
1056 if (SS.getRange().isValid())
1057 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001058 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001059 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1060 }
1061
1062 bool ShouldCheckUse = true;
1063 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1064 // Don't diagnose the use of a virtual member function unless it's
1065 // explicitly qualified.
1066 if (MD->isVirtual() && !SS.isSet())
1067 ShouldCheckUse = false;
1068 }
1069
1070 // Check the use of this member.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001071 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001072 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001073
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001074 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001075 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1076 FoundDecl, MemberNameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001077
John McCall76da55d2013-04-16 07:28:30 +00001078 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1079 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1080 MemberNameInfo);
1081
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001082 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1083 // We may have found a field within an anonymous union or struct
1084 // (C++ [class.union]).
1085 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmanbf03b372013-07-16 00:01:31 +00001086 FoundDecl, BaseExpr,
1087 OpLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001088
1089 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001090 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1091 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001092 Var->getType().getNonReferenceType(), VK_LValue,
1093 OK_Ordinary);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001094 }
1095
1096 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1097 ExprValueKind valueKind;
1098 QualType type;
1099 if (MemberFn->isInstance()) {
1100 valueKind = VK_RValue;
1101 type = Context.BoundMemberTy;
1102 } else {
1103 valueKind = VK_LValue;
1104 type = MemberFn->getType();
1105 }
1106
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001107 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1108 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1109 type, valueKind, OK_Ordinary);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001110 }
1111 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1112
1113 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001114 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1115 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1116 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001117 }
1118
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001119 // We found something that we didn't expect. Complain.
1120 if (isa<TypeDecl>(MemberDecl))
1121 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1122 << MemberName << BaseType << int(IsArrow);
1123 else
1124 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1125 << MemberName << BaseType << int(IsArrow);
1126
1127 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1128 << MemberName;
1129 R.suppressDiagnostics();
1130 return ExprError();
1131}
1132
1133/// Given that normal member access failed on the given expression,
1134/// and given that the expression's type involves builtin-id or
1135/// builtin-Class, decide whether substituting in the redefinition
1136/// types would be profitable. The redefinition type is whatever
1137/// this translation unit tried to typedef to id/Class; we store
1138/// it to the side and then re-use it in places like this.
1139static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1140 const ObjCObjectPointerType *opty
1141 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1142 if (!opty) return false;
1143
1144 const ObjCObjectType *ty = opty->getObjectType();
1145
1146 QualType redef;
1147 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001148 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001149 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001150 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001151 } else {
1152 return false;
1153 }
1154
1155 // Do the substitution as long as the redefinition type isn't just a
1156 // possibly-qualified pointer to builtin-id or builtin-Class again.
1157 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieu47fcbba2012-10-12 17:48:40 +00001158 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001159 return false;
1160
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001161 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001162 return true;
1163}
1164
John McCall6dbba4f2011-10-11 23:14:30 +00001165static bool isRecordType(QualType T) {
1166 return T->isRecordType();
1167}
1168static bool isPointerToRecordType(QualType T) {
1169 if (const PointerType *PT = T->getAs<PointerType>())
1170 return PT->getPointeeType()->isRecordType();
1171 return false;
1172}
1173
Richard Smithcda80f82011-10-26 19:06:56 +00001174/// Perform conversions on the LHS of a member access expression.
1175ExprResult
1176Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001177 if (IsArrow && !Base->getType()->isFunctionType())
1178 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcda80f82011-10-26 19:06:56 +00001179
Eli Friedman059d5782012-01-13 02:20:01 +00001180 return CheckPlaceholderExpr(Base);
Richard Smithcda80f82011-10-26 19:06:56 +00001181}
1182
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001183/// Look up the given member of the given non-type-dependent
1184/// expression. This can return in one of two ways:
1185/// * If it returns a sentinel null-but-valid result, the caller will
1186/// assume that lookup was performed and the results written into
1187/// the provided structure. It will take over from there.
1188/// * Otherwise, the returned expression will be produced in place of
1189/// an ordinary member expression.
1190///
1191/// The ObjCImpDecl bit is a gross hack that will need to be properly
1192/// fixed for ObjC++.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001193static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1194 ExprResult &BaseExpr, bool &IsArrow,
1195 SourceLocation OpLoc, CXXScopeSpec &SS,
1196 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001197 assert(BaseExpr.get() && "no base expression");
1198
1199 // Perform default conversions.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001200 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001201 if (BaseExpr.isInvalid())
1202 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001203
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001204 QualType BaseType = BaseExpr.get()->getType();
1205 assert(!BaseType->isDependentType());
1206
1207 DeclarationName MemberName = R.getLookupName();
1208 SourceLocation MemberLoc = R.getNameLoc();
1209
1210 // For later type-checking purposes, turn arrow accesses into dot
1211 // accesses. The only access type we support that doesn't follow
1212 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1213 // and those never use arrows, so this is unaffected.
1214 if (IsArrow) {
1215 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1216 BaseType = Ptr->getPointeeType();
1217 else if (const ObjCObjectPointerType *Ptr
1218 = BaseType->getAs<ObjCObjectPointerType>())
1219 BaseType = Ptr->getPointeeType();
1220 else if (BaseType->isRecordType()) {
1221 // Recover from arrow accesses to records, e.g.:
1222 // struct MyRecord foo;
1223 // foo->bar
1224 // This is actually well-formed in C++ if MyRecord has an
1225 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +00001226 // by now--or a diagnostic message already issued if a problem
1227 // was encountered while looking for the overloaded operator->.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001228 if (!S.getLangOpts().CPlusPlus) {
1229 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhraincd9d3052013-10-31 20:32:56 +00001230 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1231 << FixItHint::CreateReplacement(OpLoc, ".");
1232 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001233 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001234 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001235 goto fail;
1236 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001237 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001238 << BaseType << BaseExpr.get()->getSourceRange();
1239 return ExprError();
1240 }
1241 }
1242
1243 // Handle field access to simple records.
1244 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001245 TypoExpr *TE = nullptr;
1246 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
1247 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001248 return ExprError();
1249
1250 // Returning valid-but-null is how we indicate to the caller that
Stephen Hines176edba2014-12-01 14:53:08 -08001251 // the lookup result was filled in. If typo correction was attempted and
1252 // failed, the lookup result will have been cleared--that combined with the
1253 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1254 return ExprResult(TE);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001255 }
1256
1257 // Handle ivar access to Objective-C objects.
1258 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001259 if (!SS.isEmpty() && !SS.isInvalid()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001260 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001261 << 1 << SS.getScopeRep()
1262 << FixItHint::CreateRemoval(SS.getRange());
1263 SS.clear();
1264 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001265
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001266 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1267
1268 // There are three cases for the base type:
1269 // - builtin id (qualified or unqualified)
1270 // - builtin Class (qualified or unqualified)
1271 // - an interface
1272 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1273 if (!IDecl) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001274 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001275 (OTy->isObjCId() || OTy->isObjCClass()))
1276 goto fail;
1277 // There's an implicit 'isa' ivar on all objects.
1278 // But we only actually find it this way on objects of type 'id',
Eric Christopher2502ec82012-08-16 23:50:37 +00001279 // apparently.
Fariborz Jahanian7e352742013-03-27 21:19:25 +00001280 if (OTy->isObjCId() && Member->isStr("isa"))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001281 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1282 OpLoc, S.Context.getObjCClassType());
1283 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1284 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001285 ObjCImpDecl, HasTemplateArgs);
1286 goto fail;
1287 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001288
1289 if (S.RequireCompleteType(OpLoc, BaseType,
1290 diag::err_typecheck_incomplete_tag,
1291 BaseExpr.get()))
Douglas Gregord07cc362012-01-02 17:18:37 +00001292 return ExprError();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001293
1294 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001295 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1296
1297 if (!IV) {
1298 // Attempt to correct for typos in ivar names.
Stephen Hines176edba2014-12-01 14:53:08 -08001299 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1300 Validator->IsObjCIvarLookup = IsArrow;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001301 if (TypoCorrection Corrected = S.CorrectTypo(
1302 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001303 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001304 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001305 S.diagnoseTypo(
1306 Corrected,
1307 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1308 << IDecl->getDeclName() << MemberName);
Richard Smith2d670972013-08-17 00:46:16 +00001309
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001310 // Figure out the class that declares the ivar.
1311 assert(!ClassDeclared);
1312 Decl *D = cast<Decl>(IV->getDeclContext());
1313 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1314 D = CAT->getClassInterface();
1315 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001316 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001317 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001318 S.Diag(MemberLoc, diag::err_property_found_suggest)
1319 << Member << BaseExpr.get()->getType()
1320 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001321 return ExprError();
1322 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001323
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001324 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1325 << IDecl->getDeclName() << MemberName
1326 << BaseExpr.get()->getSourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001327 return ExprError();
1328 }
1329 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001330
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001331 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001332
1333 // If the decl being referenced had an error, return an error for this
1334 // sub-expr without emitting another error, in order to avoid cascading
1335 // error cases.
1336 if (IV->isInvalidDecl())
1337 return ExprError();
1338
1339 // Check whether we can reference this field.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001340 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001341 return ExprError();
1342 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1343 IV->getAccessControl() != ObjCIvarDecl::Package) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001344 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001345 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001346 ClassOfMethodDecl = MD->getClassInterface();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001347 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001348 // Case of a c-function declared inside an objc implementation.
1349 // FIXME: For a c-style function nested inside an objc implementation
1350 // class, there is no implementation context available, so we pass
1351 // down the context as argument to this routine. Ideally, this context
1352 // need be passed down in the AST node and somehow calculated from the
1353 // AST for a function decl.
1354 if (ObjCImplementationDecl *IMPD =
1355 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1356 ClassOfMethodDecl = IMPD->getClassInterface();
1357 else if (ObjCCategoryImplDecl* CatImplClass =
1358 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1359 ClassOfMethodDecl = CatImplClass->getClassInterface();
1360 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001361 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001362 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1363 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1364 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001365 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001366 << IV->getDeclName();
1367 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1368 // @protected
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001369 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1370 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001371 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001372 }
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001373 bool warn = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001374 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001375 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1376 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1377 if (UO->getOpcode() == UO_Deref)
1378 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1379
1380 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001381 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001382 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001383 warn = false;
1384 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001385 }
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001386 if (warn) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001387 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001388 ObjCMethodFamily MF = MD->getMethodFamily();
1389 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahanian26202292013-02-14 19:07:19 +00001390 MF != OMF_finalize &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001391 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001392 }
1393 if (warn)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001394 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001395 }
Jordan Rose7a270482012-09-28 22:21:35 +00001396
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001397 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1398 IV, IV->getType(), MemberLoc, OpLoc, BaseExpr.get(), IsArrow);
Jordan Rose7a270482012-09-28 22:21:35 +00001399
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001400 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose7a270482012-09-28 22:21:35 +00001401 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001402 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1403 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose7a270482012-09-28 22:21:35 +00001404 }
1405 }
1406
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001407 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001408 }
1409
1410 // Objective-C property access.
1411 const ObjCObjectPointerType *OPT;
1412 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001413 if (!SS.isEmpty() && !SS.isInvalid()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001414 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1415 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001416 SS.clear();
1417 }
1418
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001419 // This actually uses the base as an r-value.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001420 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001421 if (BaseExpr.isInvalid())
1422 return ExprError();
1423
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001424 assert(S.Context.hasSameUnqualifiedType(BaseType,
1425 BaseExpr.get()->getType()));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001426
1427 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1428
1429 const ObjCObjectType *OT = OPT->getObjectType();
1430
1431 // id, with and without qualifiers.
1432 if (OT->isObjCId()) {
1433 // Check protocols on qualified interfaces.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001434 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1435 if (Decl *PMDecl =
1436 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001437 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1438 // Check the use of this declaration
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001439 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001440 return ExprError();
1441
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001442 return new (S.Context)
1443 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1444 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001445 }
1446
1447 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1448 // Check the use of this method.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001449 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001450 return ExprError();
1451 Selector SetterSel =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001452 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1453 S.PP.getSelectorTable(),
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001454 Member);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001455 ObjCMethodDecl *SMD = nullptr;
1456 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001457 /*Property id*/ nullptr,
1458 SetterSel, S.Context))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001459 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001460
1461 return new (S.Context)
1462 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1463 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001464 }
1465 }
1466 // Use of id.member can only be for a property reference. Do not
1467 // use the 'id' redefinition in this case.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001468 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1469 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001470 ObjCImpDecl, HasTemplateArgs);
1471
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001472 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001473 << MemberName << BaseType);
1474 }
1475
1476 // 'Class', unqualified only.
1477 if (OT->isObjCClass()) {
1478 // Only works in a method declaration (??!).
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001479 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001480 if (!MD) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001481 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1482 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001483 ObjCImpDecl, HasTemplateArgs);
1484
1485 goto fail;
1486 }
1487
1488 // Also must look for a getter name which uses property syntax.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001489 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001490 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1491 ObjCMethodDecl *Getter;
1492 if ((Getter = IFace->lookupClassMethod(Sel))) {
1493 // Check the use of this method.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001494 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001495 return ExprError();
1496 } else
1497 Getter = IFace->lookupPrivateMethod(Sel, false);
1498 // If we found a getter then this may be a valid dot-reference, we
1499 // will look for the matching setter, in case it is needed.
1500 Selector SetterSel =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001501 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1502 S.PP.getSelectorTable(),
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001503 Member);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001504 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1505 if (!Setter) {
1506 // If this reference is in an @implementation, also check for 'private'
1507 // methods.
1508 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1509 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001510
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001511 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001512 return ExprError();
1513
1514 if (Getter || Setter) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001515 return new (S.Context) ObjCPropertyRefExpr(
1516 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1517 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001518 }
1519
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001520 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1521 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001522 ObjCImpDecl, HasTemplateArgs);
1523
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001524 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001525 << MemberName << BaseType);
1526 }
1527
1528 // Normal property access.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001529 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1530 MemberLoc, SourceLocation(), QualType(),
1531 false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001532 }
1533
1534 // Handle 'field access' to vectors, such as 'V.xx'.
1535 if (BaseType->isExtVectorType()) {
1536 // FIXME: this expr should store IsArrow.
1537 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07001538 ExprValueKind VK;
1539 if (IsArrow)
1540 VK = VK_LValue;
1541 else {
1542 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1543 VK = POE->getSyntacticForm()->getValueKind();
1544 else
1545 VK = BaseExpr.get()->getValueKind();
1546 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001547 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001548 Member, MemberLoc);
1549 if (ret.isNull())
1550 return ExprError();
1551
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001552 return new (S.Context)
1553 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001554 }
1555
1556 // Adjust builtin-sel to the appropriate redefinition type if that's
1557 // not just a pointer to builtin-sel again.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001558 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1559 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1560 BaseExpr = S.ImpCastExprToType(
1561 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1562 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001563 ObjCImpDecl, HasTemplateArgs);
1564 }
1565
1566 // Failure cases.
1567 fail:
1568
1569 // Recover from dot accesses to pointers, e.g.:
1570 // type *foo;
1571 // foo.bar
1572 // This is actually well-formed in two cases:
1573 // - 'type' is an Objective C type
1574 // - 'bar' is a pseudo-destructor name which happens to refer to
1575 // the appropriate pointer type
1576 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1577 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1578 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001579 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1580 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001581 << FixItHint::CreateReplacement(OpLoc, "->");
1582
1583 // Recurse as an -> access.
1584 IsArrow = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001585 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001586 ObjCImpDecl, HasTemplateArgs);
1587 }
1588 }
1589
1590 // If the user is trying to apply -> or . to a function name, it's probably
1591 // because they forgot parentheses to call that function.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001592 if (S.tryToRecoverWithCall(
1593 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1594 /*complain*/ false,
1595 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001596 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001597 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001598 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1599 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall6dbba4f2011-10-11 23:14:30 +00001600 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001601 }
1602
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001603 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +00001604 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001605
1606 return ExprError();
1607}
1608
1609/// The main callback when the parser finds something like
1610/// expression . [nested-name-specifier] identifier
1611/// expression -> [nested-name-specifier] identifier
1612/// where 'identifier' encompasses a fairly broad spectrum of
1613/// possibilities, including destructor and operator references.
1614///
1615/// \param OpKind either tok::arrow or tok::period
James Dennett699c9042012-06-15 07:13:21 +00001616/// \param ObjCImpDecl the current Objective-C \@implementation
1617/// decl; this is an ugly hack around the fact that Objective-C
1618/// \@implementations aren't properly put in the context chain
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001619ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1620 SourceLocation OpLoc,
1621 tok::TokenKind OpKind,
1622 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001623 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001624 UnqualifiedId &Id,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001625 Decl *ObjCImpDecl) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001626 if (SS.isSet() && SS.isInvalid())
1627 return ExprError();
1628
1629 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001630 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001631 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1632 Diag(Id.getSourceRange().getBegin(),
1633 diag::ext_ms_explicit_constructor_call);
1634
1635 TemplateArgumentListInfo TemplateArgsBuffer;
1636
1637 // Decompose the name into its component parts.
1638 DeclarationNameInfo NameInfo;
1639 const TemplateArgumentListInfo *TemplateArgs;
1640 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1641 NameInfo, TemplateArgs);
1642
1643 DeclarationName Name = NameInfo.getName();
1644 bool IsArrow = (OpKind == tok::arrow);
1645
1646 NamedDecl *FirstQualifierInScope
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001647 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001648
1649 // This is a postfix expression, so get rid of ParenListExprs.
1650 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1651 if (Result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001652 Base = Result.get();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001653
1654 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1655 isDependentScopeSpecifier(SS)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001656 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1657 TemplateKWLoc, FirstQualifierInScope,
1658 NameInfo, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001659 }
1660
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001661 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001662 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1663 TemplateKWLoc, FirstQualifierInScope,
1664 NameInfo, TemplateArgs, &ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001665}
1666
1667static ExprResult
1668BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001669 SourceLocation OpLoc, const CXXScopeSpec &SS,
1670 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001671 const DeclarationNameInfo &MemberNameInfo) {
1672 // x.a is an l-value if 'a' has a reference type. Otherwise:
1673 // x.a is an l-value/x-value/pr-value if the base is (and note
1674 // that *x is always an l-value), except that if the base isn't
1675 // an ordinary object then we must have an rvalue.
1676 ExprValueKind VK = VK_LValue;
1677 ExprObjectKind OK = OK_Ordinary;
1678 if (!IsArrow) {
1679 if (BaseExpr->getObjectKind() == OK_Ordinary)
1680 VK = BaseExpr->getValueKind();
1681 else
1682 VK = VK_RValue;
1683 }
1684 if (VK != VK_RValue && Field->isBitField())
1685 OK = OK_BitField;
1686
1687 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1688 QualType MemberType = Field->getType();
1689 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1690 MemberType = Ref->getPointeeType();
1691 VK = VK_LValue;
1692 } else {
1693 QualType BaseType = BaseExpr->getType();
1694 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001695
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001696 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001697
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001698 // GC attributes are never picked up by members.
1699 BaseQuals.removeObjCGCAttr();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001700
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001701 // CVR attributes from the base are picked up by members,
1702 // except that 'mutable' members don't pick up 'const'.
1703 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001704
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001705 Qualifiers MemberQuals
1706 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001707
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001708 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001709
1710
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001711 Qualifiers Combined = BaseQuals + MemberQuals;
1712 if (Combined != MemberQuals)
1713 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1714 }
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001715
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001716 S.UnusedPrivateFields.remove(Field);
1717
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001718 ExprResult Base =
1719 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1720 FoundDecl, Field);
1721 if (Base.isInvalid())
1722 return ExprError();
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001723 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001724 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1725 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001726}
1727
1728/// Builds an implicit member access expression. The current context
1729/// is known to be an instance method, and the given unqualified lookup
1730/// set is known to contain only instance members, at least one of which
1731/// is from an appropriate type.
1732ExprResult
1733Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001734 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001735 LookupResult &R,
1736 const TemplateArgumentListInfo *TemplateArgs,
1737 bool IsKnownInstance) {
1738 assert(!R.empty() && !R.isAmbiguous());
1739
1740 SourceLocation loc = R.getNameLoc();
Stephen Hines651f13c2014-04-23 16:59:28 -07001741
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001742 // If this is known to be an instance access, go ahead and build an
1743 // implicit 'this' expression now.
1744 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001745 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001746 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001747
1748 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001749 if (IsKnownInstance) {
1750 SourceLocation Loc = R.getNameLoc();
1751 if (SS.getRange().isValid())
1752 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001753 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001754 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1755 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001756
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001757 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1758 /*OpLoc*/ SourceLocation(),
1759 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001760 SS, TemplateKWLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001761 /*FirstQualifierInScope*/ nullptr,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001762 R, TemplateArgs);
1763}