1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis member access expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/SemaInternal.h"
14 #include "clang/Sema/Lookup.h"
15 #include "clang/Sema/Scope.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/Lex/Preprocessor.h"
22 
23 using namespace clang;
24 using namespace sema;
25 
26 /// Determines if the given class is provably not derived from all of
27 /// the prospective base classes.
28 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
29                                      CXXRecordDecl *Record,
30                             const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
31   if (Bases.count(Record->getCanonicalDecl()))
32     return false;
33 
34   RecordDecl *RD = Record->getDefinition();
35   if (!RD) return false;
36   Record = cast<CXXRecordDecl>(RD);
37 
38   for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
39          E = Record->bases_end(); I != E; ++I) {
40     CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
41     CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
42     if (!BaseRT) return false;
43 
44     CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
45     if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
46       return false;
47   }
48 
49   return true;
50 }
51 
52 enum IMAKind {
53   /// The reference is definitely not an instance member access.
54   IMA_Static,
55 
56   /// The reference may be an implicit instance member access.
57   IMA_Mixed,
58 
59   /// The reference may be to an instance member, but it might be invalid if
60   /// so, because the context is not an instance method.
61   IMA_Mixed_StaticContext,
62 
63   /// The reference may be to an instance member, but it is invalid if
64   /// so, because the context is from an unrelated class.
65   IMA_Mixed_Unrelated,
66 
67   /// The reference is definitely an implicit instance member access.
68   IMA_Instance,
69 
70   /// The reference may be to an unresolved using declaration.
71   IMA_Unresolved,
72 
73   /// The reference may be to an unresolved using declaration and the
74   /// context is not an instance method.
75   IMA_Unresolved_StaticContext,
76 
77   // The reference refers to a field which is not a member of the containing
78   // class, which is allowed because we're in C++11 mode and the context is
79   // unevaluated.
80   IMA_Field_Uneval_Context,
81 
82   /// All possible referrents are instance members and the current
83   /// context is not an instance method.
84   IMA_Error_StaticContext,
85 
86   /// All possible referrents are instance members of an unrelated
87   /// class.
88   IMA_Error_Unrelated
89 };
90 
91 /// The given lookup names class member(s) and is not being used for
92 /// an address-of-member expression.  Classify the type of access
93 /// according to whether it's possible that this reference names an
94 /// instance member.  This is best-effort in dependent contexts; it is okay to
95 /// conservatively answer "yes", in which case some errors will simply
96 /// not be caught until template-instantiation.
97 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
98                                             Scope *CurScope,
99                                             const LookupResult &R) {
100   assert(!R.empty() && (*R.begin())->isCXXClassMember());
101 
102   DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
103 
104   bool isStaticContext =
105     (!isa<CXXMethodDecl>(DC) ||
106      cast<CXXMethodDecl>(DC)->isStatic());
107 
108   // C++0x [expr.prim]p4:
109   //   Otherwise, if a member-declarator declares a non-static data member
110   // of a class X, the expression this is a prvalue of type "pointer to X"
111   // within the optional brace-or-equal-initializer.
112   if (CurScope->getFlags() & Scope::ThisScope)
113     isStaticContext = false;
114 
115   if (R.isUnresolvableResult())
116     return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
117 
118   // Collect all the declaring classes of instance members we find.
119   bool hasNonInstance = false;
120   bool isField = false;
121   llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
122   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
123     NamedDecl *D = *I;
124 
125     if (D->isCXXInstanceMember()) {
126       if (dyn_cast<FieldDecl>(D))
127         isField = true;
128 
129       CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
130       Classes.insert(R->getCanonicalDecl());
131     }
132     else
133       hasNonInstance = true;
134   }
135 
136   // If we didn't find any instance members, it can't be an implicit
137   // member reference.
138   if (Classes.empty())
139     return IMA_Static;
140 
141   // If the current context is not an instance method, it can't be
142   // an implicit member reference.
143   if (isStaticContext) {
144     if (hasNonInstance)
145         return IMA_Mixed_StaticContext;
146 
147     if (SemaRef.getLangOptions().CPlusPlus0x && isField) {
148       // C++11 [expr.prim.general]p12:
149       //   An id-expression that denotes a non-static data member or non-static
150       //   member function of a class can only be used:
151       //   (...)
152       //   - if that id-expression denotes a non-static data member and it
153       //     appears in an unevaluated operand.
154       const Sema::ExpressionEvaluationContextRecord& record
155         = SemaRef.ExprEvalContexts.back();
156       if (record.Context == Sema::Unevaluated)
157         return IMA_Field_Uneval_Context;
158     }
159 
160     return IMA_Error_StaticContext;
161   }
162 
163   CXXRecordDecl *contextClass;
164   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
165     contextClass = MD->getParent()->getCanonicalDecl();
166   else
167     contextClass = cast<CXXRecordDecl>(DC);
168 
169   // [class.mfct.non-static]p3:
170   // ...is used in the body of a non-static member function of class X,
171   // if name lookup (3.4.1) resolves the name in the id-expression to a
172   // non-static non-type member of some class C [...]
173   // ...if C is not X or a base class of X, the class member access expression
174   // is ill-formed.
175   if (R.getNamingClass() &&
176       contextClass != R.getNamingClass()->getCanonicalDecl() &&
177       contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
178     return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
179 
180   // If we can prove that the current context is unrelated to all the
181   // declaring classes, it can't be an implicit member reference (in
182   // which case it's an error if any of those members are selected).
183   if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
184     return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
185 
186   return (hasNonInstance ? IMA_Mixed : IMA_Instance);
187 }
188 
189 /// Diagnose a reference to a field with no object available.
190 static void DiagnoseInstanceReference(Sema &SemaRef,
191                                       const CXXScopeSpec &SS,
192                                       NamedDecl *rep,
193                                       const DeclarationNameInfo &nameInfo) {
194   SourceLocation Loc = nameInfo.getLoc();
195   SourceRange Range(Loc);
196   if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
197 
198   if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
199     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
200       if (MD->isStatic()) {
201         // "invalid use of member 'x' in static member function"
202         SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
203             << Range << nameInfo.getName();
204         return;
205       }
206     }
207 
208     SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
209         << nameInfo.getName() << Range;
210     return;
211   }
212 
213   SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
214 }
215 
216 /// Builds an expression which might be an implicit member expression.
217 ExprResult
218 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
219                                       SourceLocation TemplateKWLoc,
220                                       LookupResult &R,
221                                 const TemplateArgumentListInfo *TemplateArgs) {
222   switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
223   case IMA_Instance:
224     return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
225 
226   case IMA_Mixed:
227   case IMA_Mixed_Unrelated:
228   case IMA_Unresolved:
229     return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
230 
231   case IMA_Static:
232   case IMA_Mixed_StaticContext:
233   case IMA_Unresolved_StaticContext:
234   case IMA_Field_Uneval_Context:
235     if (TemplateArgs)
236       return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, *TemplateArgs);
237     return BuildDeclarationNameExpr(SS, R, false);
238 
239   case IMA_Error_StaticContext:
240   case IMA_Error_Unrelated:
241     DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
242                               R.getLookupNameInfo());
243     return ExprError();
244   }
245 
246   llvm_unreachable("unexpected instance member access kind");
247 }
248 
249 /// Check an ext-vector component access expression.
250 ///
251 /// VK should be set in advance to the value kind of the base
252 /// expression.
253 static QualType
254 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
255                         SourceLocation OpLoc, const IdentifierInfo *CompName,
256                         SourceLocation CompLoc) {
257   // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
258   // see FIXME there.
259   //
260   // FIXME: This logic can be greatly simplified by splitting it along
261   // halving/not halving and reworking the component checking.
262   const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
263 
264   // The vector accessor can't exceed the number of elements.
265   const char *compStr = CompName->getNameStart();
266 
267   // This flag determines whether or not the component is one of the four
268   // special names that indicate a subset of exactly half the elements are
269   // to be selected.
270   bool HalvingSwizzle = false;
271 
272   // This flag determines whether or not CompName has an 's' char prefix,
273   // indicating that it is a string of hex values to be used as vector indices.
274   bool HexSwizzle = *compStr == 's' || *compStr == 'S';
275 
276   bool HasRepeated = false;
277   bool HasIndex[16] = {};
278 
279   int Idx;
280 
281   // Check that we've found one of the special components, or that the component
282   // names must come from the same set.
283   if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
284       !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
285     HalvingSwizzle = true;
286   } else if (!HexSwizzle &&
287              (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
288     do {
289       if (HasIndex[Idx]) HasRepeated = true;
290       HasIndex[Idx] = true;
291       compStr++;
292     } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
293   } else {
294     if (HexSwizzle) compStr++;
295     while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
296       if (HasIndex[Idx]) HasRepeated = true;
297       HasIndex[Idx] = true;
298       compStr++;
299     }
300   }
301 
302   if (!HalvingSwizzle && *compStr) {
303     // We didn't get to the end of the string. This means the component names
304     // didn't come from the same set *or* we encountered an illegal name.
305     S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
306       << StringRef(compStr, 1) << SourceRange(CompLoc);
307     return QualType();
308   }
309 
310   // Ensure no component accessor exceeds the width of the vector type it
311   // operates on.
312   if (!HalvingSwizzle) {
313     compStr = CompName->getNameStart();
314 
315     if (HexSwizzle)
316       compStr++;
317 
318     while (*compStr) {
319       if (!vecType->isAccessorWithinNumElements(*compStr++)) {
320         S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
321           << baseType << SourceRange(CompLoc);
322         return QualType();
323       }
324     }
325   }
326 
327   // The component accessor looks fine - now we need to compute the actual type.
328   // The vector type is implied by the component accessor. For example,
329   // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
330   // vec4.s0 is a float, vec4.s23 is a vec3, etc.
331   // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
332   unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
333                                      : CompName->getLength();
334   if (HexSwizzle)
335     CompSize--;
336 
337   if (CompSize == 1)
338     return vecType->getElementType();
339 
340   if (HasRepeated) VK = VK_RValue;
341 
342   QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
343   // Now look up the TypeDefDecl from the vector type. Without this,
344   // diagostics look bad. We want extended vector types to appear built-in.
345   for (Sema::ExtVectorDeclsType::iterator
346          I = S.ExtVectorDecls.begin(S.ExternalSource),
347          E = S.ExtVectorDecls.end();
348        I != E; ++I) {
349     if ((*I)->getUnderlyingType() == VT)
350       return S.Context.getTypedefType(*I);
351   }
352 
353   return VT; // should never get here (a typedef type should always be found).
354 }
355 
356 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
357                                                 IdentifierInfo *Member,
358                                                 const Selector &Sel,
359                                                 ASTContext &Context) {
360   if (Member)
361     if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
362       return PD;
363   if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
364     return OMD;
365 
366   for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
367        E = PDecl->protocol_end(); I != E; ++I) {
368     if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
369                                                            Context))
370       return D;
371   }
372   return 0;
373 }
374 
375 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
376                                       IdentifierInfo *Member,
377                                       const Selector &Sel,
378                                       ASTContext &Context) {
379   // Check protocols on qualified interfaces.
380   Decl *GDecl = 0;
381   for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
382        E = QIdTy->qual_end(); I != E; ++I) {
383     if (Member)
384       if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
385         GDecl = PD;
386         break;
387       }
388     // Also must look for a getter or setter name which uses property syntax.
389     if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
390       GDecl = OMD;
391       break;
392     }
393   }
394   if (!GDecl) {
395     for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
396          E = QIdTy->qual_end(); I != E; ++I) {
397       // Search in the protocol-qualifier list of current protocol.
398       GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
399                                                        Context);
400       if (GDecl)
401         return GDecl;
402     }
403   }
404   return GDecl;
405 }
406 
407 ExprResult
408 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
409                                bool IsArrow, SourceLocation OpLoc,
410                                const CXXScopeSpec &SS,
411                                SourceLocation TemplateKWLoc,
412                                NamedDecl *FirstQualifierInScope,
413                                const DeclarationNameInfo &NameInfo,
414                                const TemplateArgumentListInfo *TemplateArgs) {
415   // Even in dependent contexts, try to diagnose base expressions with
416   // obviously wrong types, e.g.:
417   //
418   // T* t;
419   // t.f;
420   //
421   // In Obj-C++, however, the above expression is valid, since it could be
422   // accessing the 'f' property if T is an Obj-C interface. The extra check
423   // allows this, while still reporting an error if T is a struct pointer.
424   if (!IsArrow) {
425     const PointerType *PT = BaseType->getAs<PointerType>();
426     if (PT && (!getLangOptions().ObjC1 ||
427                PT->getPointeeType()->isRecordType())) {
428       assert(BaseExpr && "cannot happen with implicit member accesses");
429       Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
430         << BaseType << BaseExpr->getSourceRange();
431       return ExprError();
432     }
433   }
434 
435   assert(BaseType->isDependentType() ||
436          NameInfo.getName().isDependentName() ||
437          isDependentScopeSpecifier(SS));
438 
439   // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
440   // must have pointer type, and the accessed type is the pointee.
441   return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
442                                                    IsArrow, OpLoc,
443                                                SS.getWithLocInContext(Context),
444                                                    TemplateKWLoc,
445                                                    FirstQualifierInScope,
446                                                    NameInfo, TemplateArgs));
447 }
448 
449 /// We know that the given qualified member reference points only to
450 /// declarations which do not belong to the static type of the base
451 /// expression.  Diagnose the problem.
452 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
453                                              Expr *BaseExpr,
454                                              QualType BaseType,
455                                              const CXXScopeSpec &SS,
456                                              NamedDecl *rep,
457                                        const DeclarationNameInfo &nameInfo) {
458   // If this is an implicit member access, use a different set of
459   // diagnostics.
460   if (!BaseExpr)
461     return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
462 
463   SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
464     << SS.getRange() << rep << BaseType;
465 }
466 
467 // Check whether the declarations we found through a nested-name
468 // specifier in a member expression are actually members of the base
469 // type.  The restriction here is:
470 //
471 //   C++ [expr.ref]p2:
472 //     ... In these cases, the id-expression shall name a
473 //     member of the class or of one of its base classes.
474 //
475 // So it's perfectly legitimate for the nested-name specifier to name
476 // an unrelated class, and for us to find an overload set including
477 // decls from classes which are not superclasses, as long as the decl
478 // we actually pick through overload resolution is from a superclass.
479 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
480                                          QualType BaseType,
481                                          const CXXScopeSpec &SS,
482                                          const LookupResult &R) {
483   const RecordType *BaseRT = BaseType->getAs<RecordType>();
484   if (!BaseRT) {
485     // We can't check this yet because the base type is still
486     // dependent.
487     assert(BaseType->isDependentType());
488     return false;
489   }
490   CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
491 
492   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
493     // If this is an implicit member reference and we find a
494     // non-instance member, it's not an error.
495     if (!BaseExpr && !(*I)->isCXXInstanceMember())
496       return false;
497 
498     // Note that we use the DC of the decl, not the underlying decl.
499     DeclContext *DC = (*I)->getDeclContext();
500     while (DC->isTransparentContext())
501       DC = DC->getParent();
502 
503     if (!DC->isRecord())
504       continue;
505 
506     llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
507     MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
508 
509     if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
510       return false;
511   }
512 
513   DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
514                                    R.getRepresentativeDecl(),
515                                    R.getLookupNameInfo());
516   return true;
517 }
518 
519 namespace {
520 
521 // Callback to only accept typo corrections that are either a ValueDecl or a
522 // FunctionTemplateDecl.
523 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
524  public:
525   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
526     NamedDecl *ND = candidate.getCorrectionDecl();
527     return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
528   }
529 };
530 
531 }
532 
533 static bool
534 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
535                          SourceRange BaseRange, const RecordType *RTy,
536                          SourceLocation OpLoc, CXXScopeSpec &SS,
537                          bool HasTemplateArgs) {
538   RecordDecl *RDecl = RTy->getDecl();
539   if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
540                               SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
541                                     << BaseRange))
542     return true;
543 
544   if (HasTemplateArgs) {
545     // LookupTemplateName doesn't expect these both to exist simultaneously.
546     QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
547 
548     bool MOUS;
549     SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
550     return false;
551   }
552 
553   DeclContext *DC = RDecl;
554   if (SS.isSet()) {
555     // If the member name was a qualified-id, look into the
556     // nested-name-specifier.
557     DC = SemaRef.computeDeclContext(SS, false);
558 
559     if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
560       SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
561         << SS.getRange() << DC;
562       return true;
563     }
564 
565     assert(DC && "Cannot handle non-computable dependent contexts in lookup");
566 
567     if (!isa<TypeDecl>(DC)) {
568       SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
569         << DC << SS.getRange();
570       return true;
571     }
572   }
573 
574   // The record definition is complete, now look up the member.
575   SemaRef.LookupQualifiedName(R, DC);
576 
577   if (!R.empty())
578     return false;
579 
580   // We didn't find anything with the given name, so try to correct
581   // for typos.
582   DeclarationName Name = R.getLookupName();
583   RecordMemberExprValidatorCCC Validator;
584   TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
585                                                  R.getLookupKind(), NULL,
586                                                  &SS, &Validator, DC);
587   R.clear();
588   if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
589     std::string CorrectedStr(
590         Corrected.getAsString(SemaRef.getLangOptions()));
591     std::string CorrectedQuotedStr(
592         Corrected.getQuoted(SemaRef.getLangOptions()));
593     R.setLookupName(Corrected.getCorrection());
594     R.addDecl(ND);
595     SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
596       << Name << DC << CorrectedQuotedStr << SS.getRange()
597       << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
598     SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
599       << ND->getDeclName();
600   }
601 
602   return false;
603 }
604 
605 ExprResult
606 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
607                                SourceLocation OpLoc, bool IsArrow,
608                                CXXScopeSpec &SS,
609                                SourceLocation TemplateKWLoc,
610                                NamedDecl *FirstQualifierInScope,
611                                const DeclarationNameInfo &NameInfo,
612                                const TemplateArgumentListInfo *TemplateArgs) {
613   if (BaseType->isDependentType() ||
614       (SS.isSet() && isDependentScopeSpecifier(SS)))
615     return ActOnDependentMemberExpr(Base, BaseType,
616                                     IsArrow, OpLoc,
617                                     SS, TemplateKWLoc, FirstQualifierInScope,
618                                     NameInfo, TemplateArgs);
619 
620   LookupResult R(*this, NameInfo, LookupMemberName);
621 
622   // Implicit member accesses.
623   if (!Base) {
624     QualType RecordTy = BaseType;
625     if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
626     if (LookupMemberExprInRecord(*this, R, SourceRange(),
627                                  RecordTy->getAs<RecordType>(),
628                                  OpLoc, SS, TemplateArgs != 0))
629       return ExprError();
630 
631   // Explicit member accesses.
632   } else {
633     ExprResult BaseResult = Owned(Base);
634     ExprResult Result =
635       LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
636                        SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
637 
638     if (BaseResult.isInvalid())
639       return ExprError();
640     Base = BaseResult.take();
641 
642     if (Result.isInvalid()) {
643       Owned(Base);
644       return ExprError();
645     }
646 
647     if (Result.get())
648       return move(Result);
649 
650     // LookupMemberExpr can modify Base, and thus change BaseType
651     BaseType = Base->getType();
652   }
653 
654   return BuildMemberReferenceExpr(Base, BaseType,
655                                   OpLoc, IsArrow, SS, TemplateKWLoc,
656                                   FirstQualifierInScope, R, TemplateArgs);
657 }
658 
659 static ExprResult
660 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
661                         const CXXScopeSpec &SS, FieldDecl *Field,
662                         DeclAccessPair FoundDecl,
663                         const DeclarationNameInfo &MemberNameInfo);
664 
665 ExprResult
666 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
667                                                SourceLocation loc,
668                                                IndirectFieldDecl *indirectField,
669                                                Expr *baseObjectExpr,
670                                                SourceLocation opLoc) {
671   // First, build the expression that refers to the base object.
672 
673   bool baseObjectIsPointer = false;
674   Qualifiers baseQuals;
675 
676   // Case 1:  the base of the indirect field is not a field.
677   VarDecl *baseVariable = indirectField->getVarDecl();
678   CXXScopeSpec EmptySS;
679   if (baseVariable) {
680     assert(baseVariable->getType()->isRecordType());
681 
682     // In principle we could have a member access expression that
683     // accesses an anonymous struct/union that's a static member of
684     // the base object's class.  However, under the current standard,
685     // static data members cannot be anonymous structs or unions.
686     // Supporting this is as easy as building a MemberExpr here.
687     assert(!baseObjectExpr && "anonymous struct/union is static data member?");
688 
689     DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
690 
691     ExprResult result
692       = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
693     if (result.isInvalid()) return ExprError();
694 
695     baseObjectExpr = result.take();
696     baseObjectIsPointer = false;
697     baseQuals = baseObjectExpr->getType().getQualifiers();
698 
699     // Case 2: the base of the indirect field is a field and the user
700     // wrote a member expression.
701   } else if (baseObjectExpr) {
702     // The caller provided the base object expression. Determine
703     // whether its a pointer and whether it adds any qualifiers to the
704     // anonymous struct/union fields we're looking into.
705     QualType objectType = baseObjectExpr->getType();
706 
707     if (const PointerType *ptr = objectType->getAs<PointerType>()) {
708       baseObjectIsPointer = true;
709       objectType = ptr->getPointeeType();
710     } else {
711       baseObjectIsPointer = false;
712     }
713     baseQuals = objectType.getQualifiers();
714 
715     // Case 3: the base of the indirect field is a field and we should
716     // build an implicit member access.
717   } else {
718     // We've found a member of an anonymous struct/union that is
719     // inside a non-anonymous struct/union, so in a well-formed
720     // program our base object expression is "this".
721     QualType ThisTy = getCurrentThisType();
722     if (ThisTy.isNull()) {
723       Diag(loc, diag::err_invalid_member_use_in_static_method)
724         << indirectField->getDeclName();
725       return ExprError();
726     }
727 
728     // Our base object expression is "this".
729     CheckCXXThisCapture(loc);
730     baseObjectExpr
731       = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
732     baseObjectIsPointer = true;
733     baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
734   }
735 
736   // Build the implicit member references to the field of the
737   // anonymous struct/union.
738   Expr *result = baseObjectExpr;
739   IndirectFieldDecl::chain_iterator
740   FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
741 
742   // Build the first member access in the chain with full information.
743   if (!baseVariable) {
744     FieldDecl *field = cast<FieldDecl>(*FI);
745 
746     // FIXME: use the real found-decl info!
747     DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
748 
749     // Make a nameInfo that properly uses the anonymous name.
750     DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
751 
752     result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
753                                      EmptySS, field, foundDecl,
754                                      memberNameInfo).take();
755     baseObjectIsPointer = false;
756 
757     // FIXME: check qualified member access
758   }
759 
760   // In all cases, we should now skip the first declaration in the chain.
761   ++FI;
762 
763   while (FI != FEnd) {
764     FieldDecl *field = cast<FieldDecl>(*FI++);
765 
766     // FIXME: these are somewhat meaningless
767     DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
768     DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
769 
770     result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
771                                      (FI == FEnd? SS : EmptySS), field,
772                                      foundDecl, memberNameInfo).take();
773   }
774 
775   return Owned(result);
776 }
777 
778 /// \brief Build a MemberExpr AST node.
779 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
780                                    const CXXScopeSpec &SS,
781                                    SourceLocation TemplateKWLoc,
782                                    ValueDecl *Member,
783                                    DeclAccessPair FoundDecl,
784                                    const DeclarationNameInfo &MemberNameInfo,
785                                    QualType Ty,
786                                    ExprValueKind VK, ExprObjectKind OK,
787                                    const TemplateArgumentListInfo *TemplateArgs = 0) {
788   assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
789   return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
790                             TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
791                             TemplateArgs, Ty, VK, OK);
792 }
793 
794 ExprResult
795 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
796                                SourceLocation OpLoc, bool IsArrow,
797                                const CXXScopeSpec &SS,
798                                SourceLocation TemplateKWLoc,
799                                NamedDecl *FirstQualifierInScope,
800                                LookupResult &R,
801                          const TemplateArgumentListInfo *TemplateArgs,
802                                bool SuppressQualifierCheck) {
803   QualType BaseType = BaseExprType;
804   if (IsArrow) {
805     assert(BaseType->isPointerType());
806     BaseType = BaseType->castAs<PointerType>()->getPointeeType();
807   }
808   R.setBaseObjectType(BaseType);
809 
810   const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
811   DeclarationName MemberName = MemberNameInfo.getName();
812   SourceLocation MemberLoc = MemberNameInfo.getLoc();
813 
814   if (R.isAmbiguous())
815     return ExprError();
816 
817   if (R.empty()) {
818     // Rederive where we looked up.
819     DeclContext *DC = (SS.isSet()
820                        ? computeDeclContext(SS, false)
821                        : BaseType->getAs<RecordType>()->getDecl());
822 
823     Diag(R.getNameLoc(), diag::err_no_member)
824       << MemberName << DC
825       << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
826     return ExprError();
827   }
828 
829   // Diagnose lookups that find only declarations from a non-base
830   // type.  This is possible for either qualified lookups (which may
831   // have been qualified with an unrelated type) or implicit member
832   // expressions (which were found with unqualified lookup and thus
833   // may have come from an enclosing scope).  Note that it's okay for
834   // lookup to find declarations from a non-base type as long as those
835   // aren't the ones picked by overload resolution.
836   if ((SS.isSet() || !BaseExpr ||
837        (isa<CXXThisExpr>(BaseExpr) &&
838         cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
839       !SuppressQualifierCheck &&
840       CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
841     return ExprError();
842 
843   // Construct an unresolved result if we in fact got an unresolved
844   // result.
845   if (R.isOverloadedResult() || R.isUnresolvableResult()) {
846     // Suppress any lookup-related diagnostics; we'll do these when we
847     // pick a member.
848     R.suppressDiagnostics();
849 
850     UnresolvedMemberExpr *MemExpr
851       = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
852                                      BaseExpr, BaseExprType,
853                                      IsArrow, OpLoc,
854                                      SS.getWithLocInContext(Context),
855                                      TemplateKWLoc, MemberNameInfo,
856                                      TemplateArgs, R.begin(), R.end());
857 
858     return Owned(MemExpr);
859   }
860 
861   assert(R.isSingleResult());
862   DeclAccessPair FoundDecl = R.begin().getPair();
863   NamedDecl *MemberDecl = R.getFoundDecl();
864 
865   // FIXME: diagnose the presence of template arguments now.
866 
867   // If the decl being referenced had an error, return an error for this
868   // sub-expr without emitting another error, in order to avoid cascading
869   // error cases.
870   if (MemberDecl->isInvalidDecl())
871     return ExprError();
872 
873   // Handle the implicit-member-access case.
874   if (!BaseExpr) {
875     // If this is not an instance member, convert to a non-member access.
876     if (!MemberDecl->isCXXInstanceMember())
877       return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
878 
879     SourceLocation Loc = R.getNameLoc();
880     if (SS.getRange().isValid())
881       Loc = SS.getRange().getBegin();
882     CheckCXXThisCapture(Loc);
883     BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
884   }
885 
886   bool ShouldCheckUse = true;
887   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
888     // Don't diagnose the use of a virtual member function unless it's
889     // explicitly qualified.
890     if (MD->isVirtual() && !SS.isSet())
891       ShouldCheckUse = false;
892   }
893 
894   // Check the use of this member.
895   if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
896     Owned(BaseExpr);
897     return ExprError();
898   }
899 
900   if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
901     return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
902                                    SS, FD, FoundDecl, MemberNameInfo);
903 
904   if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
905     // We may have found a field within an anonymous union or struct
906     // (C++ [class.union]).
907     return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
908                                                     BaseExpr, OpLoc);
909 
910   if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
911     MarkDeclarationReferenced(MemberLoc, Var);
912     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
913                                  Var, FoundDecl, MemberNameInfo,
914                                  Var->getType().getNonReferenceType(),
915                                  VK_LValue, OK_Ordinary));
916   }
917 
918   if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
919     ExprValueKind valueKind;
920     QualType type;
921     if (MemberFn->isInstance()) {
922       valueKind = VK_RValue;
923       type = Context.BoundMemberTy;
924     } else {
925       valueKind = VK_LValue;
926       type = MemberFn->getType();
927     }
928 
929     MarkDeclarationReferenced(MemberLoc, MemberDecl);
930     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
931                                  MemberFn, FoundDecl, MemberNameInfo,
932                                  type, valueKind, OK_Ordinary));
933   }
934   assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
935 
936   if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
937     MarkDeclarationReferenced(MemberLoc, MemberDecl);
938     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
939                                  Enum, FoundDecl, MemberNameInfo,
940                                  Enum->getType(), VK_RValue, OK_Ordinary));
941   }
942 
943   Owned(BaseExpr);
944 
945   // We found something that we didn't expect. Complain.
946   if (isa<TypeDecl>(MemberDecl))
947     Diag(MemberLoc, diag::err_typecheck_member_reference_type)
948       << MemberName << BaseType << int(IsArrow);
949   else
950     Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
951       << MemberName << BaseType << int(IsArrow);
952 
953   Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
954     << MemberName;
955   R.suppressDiagnostics();
956   return ExprError();
957 }
958 
959 /// Given that normal member access failed on the given expression,
960 /// and given that the expression's type involves builtin-id or
961 /// builtin-Class, decide whether substituting in the redefinition
962 /// types would be profitable.  The redefinition type is whatever
963 /// this translation unit tried to typedef to id/Class;  we store
964 /// it to the side and then re-use it in places like this.
965 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
966   const ObjCObjectPointerType *opty
967     = base.get()->getType()->getAs<ObjCObjectPointerType>();
968   if (!opty) return false;
969 
970   const ObjCObjectType *ty = opty->getObjectType();
971 
972   QualType redef;
973   if (ty->isObjCId()) {
974     redef = S.Context.getObjCIdRedefinitionType();
975   } else if (ty->isObjCClass()) {
976     redef = S.Context.getObjCClassRedefinitionType();
977   } else {
978     return false;
979   }
980 
981   // Do the substitution as long as the redefinition type isn't just a
982   // possibly-qualified pointer to builtin-id or builtin-Class again.
983   opty = redef->getAs<ObjCObjectPointerType>();
984   if (opty && !opty->getObjectType()->getInterface() != 0)
985     return false;
986 
987   base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
988   return true;
989 }
990 
991 static bool isRecordType(QualType T) {
992   return T->isRecordType();
993 }
994 static bool isPointerToRecordType(QualType T) {
995   if (const PointerType *PT = T->getAs<PointerType>())
996     return PT->getPointeeType()->isRecordType();
997   return false;
998 }
999 
1000 /// Perform conversions on the LHS of a member access expression.
1001 ExprResult
1002 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1003   if (IsArrow && !Base->getType()->isFunctionType())
1004     return DefaultFunctionArrayLvalueConversion(Base);
1005 
1006   return CheckPlaceholderExpr(Base);
1007 }
1008 
1009 /// Look up the given member of the given non-type-dependent
1010 /// expression.  This can return in one of two ways:
1011 ///  * If it returns a sentinel null-but-valid result, the caller will
1012 ///    assume that lookup was performed and the results written into
1013 ///    the provided structure.  It will take over from there.
1014 ///  * Otherwise, the returned expression will be produced in place of
1015 ///    an ordinary member expression.
1016 ///
1017 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1018 /// fixed for ObjC++.
1019 ExprResult
1020 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1021                        bool &IsArrow, SourceLocation OpLoc,
1022                        CXXScopeSpec &SS,
1023                        Decl *ObjCImpDecl, bool HasTemplateArgs) {
1024   assert(BaseExpr.get() && "no base expression");
1025 
1026   // Perform default conversions.
1027   BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
1028   if (BaseExpr.isInvalid())
1029     return ExprError();
1030 
1031   QualType BaseType = BaseExpr.get()->getType();
1032   assert(!BaseType->isDependentType());
1033 
1034   DeclarationName MemberName = R.getLookupName();
1035   SourceLocation MemberLoc = R.getNameLoc();
1036 
1037   // For later type-checking purposes, turn arrow accesses into dot
1038   // accesses.  The only access type we support that doesn't follow
1039   // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1040   // and those never use arrows, so this is unaffected.
1041   if (IsArrow) {
1042     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1043       BaseType = Ptr->getPointeeType();
1044     else if (const ObjCObjectPointerType *Ptr
1045                = BaseType->getAs<ObjCObjectPointerType>())
1046       BaseType = Ptr->getPointeeType();
1047     else if (BaseType->isRecordType()) {
1048       // Recover from arrow accesses to records, e.g.:
1049       //   struct MyRecord foo;
1050       //   foo->bar
1051       // This is actually well-formed in C++ if MyRecord has an
1052       // overloaded operator->, but that should have been dealt with
1053       // by now.
1054       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1055         << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1056         << FixItHint::CreateReplacement(OpLoc, ".");
1057       IsArrow = false;
1058     } else if (BaseType->isFunctionType()) {
1059       goto fail;
1060     } else {
1061       Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1062         << BaseType << BaseExpr.get()->getSourceRange();
1063       return ExprError();
1064     }
1065   }
1066 
1067   // Handle field access to simple records.
1068   if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1069     if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1070                                  RTy, OpLoc, SS, HasTemplateArgs))
1071       return ExprError();
1072 
1073     // Returning valid-but-null is how we indicate to the caller that
1074     // the lookup result was filled in.
1075     return Owned((Expr*) 0);
1076   }
1077 
1078   // Handle ivar access to Objective-C objects.
1079   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1080     if (!SS.isEmpty() && !SS.isInvalid()) {
1081       Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1082         << 1 << SS.getScopeRep()
1083         << FixItHint::CreateRemoval(SS.getRange());
1084       SS.clear();
1085     }
1086 
1087     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1088 
1089     // There are three cases for the base type:
1090     //   - builtin id (qualified or unqualified)
1091     //   - builtin Class (qualified or unqualified)
1092     //   - an interface
1093     ObjCInterfaceDecl *IDecl = OTy->getInterface();
1094     if (!IDecl) {
1095       if (getLangOptions().ObjCAutoRefCount &&
1096           (OTy->isObjCId() || OTy->isObjCClass()))
1097         goto fail;
1098       // There's an implicit 'isa' ivar on all objects.
1099       // But we only actually find it this way on objects of type 'id',
1100       // apparently.ghjg
1101       if (OTy->isObjCId() && Member->isStr("isa")) {
1102         Diag(MemberLoc, diag::warn_objc_isa_use);
1103         return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1104                                                Context.getObjCClassType()));
1105       }
1106 
1107       if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1108         return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1109                                 ObjCImpDecl, HasTemplateArgs);
1110       goto fail;
1111     }
1112 
1113     if (RequireCompleteType(OpLoc, BaseType,
1114                             PDiag(diag::err_typecheck_incomplete_tag)
1115                               << BaseExpr.get()->getSourceRange()))
1116       return ExprError();
1117 
1118     ObjCInterfaceDecl *ClassDeclared;
1119     ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1120 
1121     if (!IV) {
1122       // Attempt to correct for typos in ivar names.
1123       DeclFilterCCC<ObjCIvarDecl> Validator;
1124       Validator.IsObjCIvarLookup = IsArrow;
1125       if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1126                                                  LookupMemberName, NULL, NULL,
1127                                                  &Validator, IDecl)) {
1128         IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1129         Diag(R.getNameLoc(),
1130              diag::err_typecheck_member_reference_ivar_suggest)
1131           << IDecl->getDeclName() << MemberName << IV->getDeclName()
1132           << FixItHint::CreateReplacement(R.getNameLoc(),
1133                                           IV->getNameAsString());
1134         Diag(IV->getLocation(), diag::note_previous_decl)
1135           << IV->getDeclName();
1136       } else {
1137         if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1138           Diag(MemberLoc,
1139           diag::err_property_found_suggest)
1140           << Member << BaseExpr.get()->getType()
1141           << FixItHint::CreateReplacement(OpLoc, ".");
1142           return ExprError();
1143         }
1144 
1145         Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1146           << IDecl->getDeclName() << MemberName
1147           << BaseExpr.get()->getSourceRange();
1148         return ExprError();
1149       }
1150     }
1151 
1152     // If the decl being referenced had an error, return an error for this
1153     // sub-expr without emitting another error, in order to avoid cascading
1154     // error cases.
1155     if (IV->isInvalidDecl())
1156       return ExprError();
1157 
1158     // Check whether we can reference this field.
1159     if (DiagnoseUseOfDecl(IV, MemberLoc))
1160       return ExprError();
1161     if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1162         IV->getAccessControl() != ObjCIvarDecl::Package) {
1163       ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1164       if (ObjCMethodDecl *MD = getCurMethodDecl())
1165         ClassOfMethodDecl =  MD->getClassInterface();
1166       else if (ObjCImpDecl && getCurFunctionDecl()) {
1167         // Case of a c-function declared inside an objc implementation.
1168         // FIXME: For a c-style function nested inside an objc implementation
1169         // class, there is no implementation context available, so we pass
1170         // down the context as argument to this routine. Ideally, this context
1171         // need be passed down in the AST node and somehow calculated from the
1172         // AST for a function decl.
1173         if (ObjCImplementationDecl *IMPD =
1174               dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1175           ClassOfMethodDecl = IMPD->getClassInterface();
1176         else if (ObjCCategoryImplDecl* CatImplClass =
1177                    dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1178           ClassOfMethodDecl = CatImplClass->getClassInterface();
1179       }
1180 
1181       if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1182         if (!declaresSameEntity(ClassDeclared, IDecl) ||
1183             !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1184           Diag(MemberLoc, diag::error_private_ivar_access)
1185             << IV->getDeclName();
1186       } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1187         // @protected
1188         Diag(MemberLoc, diag::error_protected_ivar_access)
1189           << IV->getDeclName();
1190     }
1191     if (getLangOptions().ObjCAutoRefCount) {
1192       Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1193       if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1194         if (UO->getOpcode() == UO_Deref)
1195           BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1196 
1197       if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1198         if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1199           Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1200     }
1201 
1202     return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1203                                                MemberLoc, BaseExpr.take(),
1204                                                IsArrow));
1205   }
1206 
1207   // Objective-C property access.
1208   const ObjCObjectPointerType *OPT;
1209   if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1210     if (!SS.isEmpty() && !SS.isInvalid()) {
1211       Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1212         << 0 << SS.getScopeRep()
1213         << FixItHint::CreateRemoval(SS.getRange());
1214       SS.clear();
1215     }
1216 
1217     // This actually uses the base as an r-value.
1218     BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1219     if (BaseExpr.isInvalid())
1220       return ExprError();
1221 
1222     assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1223 
1224     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1225 
1226     const ObjCObjectType *OT = OPT->getObjectType();
1227 
1228     // id, with and without qualifiers.
1229     if (OT->isObjCId()) {
1230       // Check protocols on qualified interfaces.
1231       Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1232       if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1233         if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1234           // Check the use of this declaration
1235           if (DiagnoseUseOfDecl(PD, MemberLoc))
1236             return ExprError();
1237 
1238           return Owned(new (Context) ObjCPropertyRefExpr(PD,
1239                                                          Context.PseudoObjectTy,
1240                                                          VK_LValue,
1241                                                          OK_ObjCProperty,
1242                                                          MemberLoc,
1243                                                          BaseExpr.take()));
1244         }
1245 
1246         if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1247           // Check the use of this method.
1248           if (DiagnoseUseOfDecl(OMD, MemberLoc))
1249             return ExprError();
1250           Selector SetterSel =
1251             SelectorTable::constructSetterName(PP.getIdentifierTable(),
1252                                                PP.getSelectorTable(), Member);
1253           ObjCMethodDecl *SMD = 0;
1254           if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1255                                                      SetterSel, Context))
1256             SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1257 
1258           return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1259                                                          Context.PseudoObjectTy,
1260                                                          VK_LValue, OK_ObjCProperty,
1261                                                          MemberLoc, BaseExpr.take()));
1262         }
1263       }
1264       // Use of id.member can only be for a property reference. Do not
1265       // use the 'id' redefinition in this case.
1266       if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1267         return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1268                                 ObjCImpDecl, HasTemplateArgs);
1269 
1270       return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1271                          << MemberName << BaseType);
1272     }
1273 
1274     // 'Class', unqualified only.
1275     if (OT->isObjCClass()) {
1276       // Only works in a method declaration (??!).
1277       ObjCMethodDecl *MD = getCurMethodDecl();
1278       if (!MD) {
1279         if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1280           return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1281                                   ObjCImpDecl, HasTemplateArgs);
1282 
1283         goto fail;
1284       }
1285 
1286       // Also must look for a getter name which uses property syntax.
1287       Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1288       ObjCInterfaceDecl *IFace = MD->getClassInterface();
1289       ObjCMethodDecl *Getter;
1290       if ((Getter = IFace->lookupClassMethod(Sel))) {
1291         // Check the use of this method.
1292         if (DiagnoseUseOfDecl(Getter, MemberLoc))
1293           return ExprError();
1294       } else
1295         Getter = IFace->lookupPrivateMethod(Sel, false);
1296       // If we found a getter then this may be a valid dot-reference, we
1297       // will look for the matching setter, in case it is needed.
1298       Selector SetterSel =
1299         SelectorTable::constructSetterName(PP.getIdentifierTable(),
1300                                            PP.getSelectorTable(), Member);
1301       ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1302       if (!Setter) {
1303         // If this reference is in an @implementation, also check for 'private'
1304         // methods.
1305         Setter = IFace->lookupPrivateMethod(SetterSel, false);
1306       }
1307       // Look through local category implementations associated with the class.
1308       if (!Setter)
1309         Setter = IFace->getCategoryClassMethod(SetterSel);
1310 
1311       if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1312         return ExprError();
1313 
1314       if (Getter || Setter) {
1315         return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1316                                                        Context.PseudoObjectTy,
1317                                                        VK_LValue, OK_ObjCProperty,
1318                                                        MemberLoc, BaseExpr.take()));
1319       }
1320 
1321       if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1322         return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1323                                 ObjCImpDecl, HasTemplateArgs);
1324 
1325       return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1326                          << MemberName << BaseType);
1327     }
1328 
1329     // Normal property access.
1330     return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1331                                      MemberName, MemberLoc,
1332                                      SourceLocation(), QualType(), false);
1333   }
1334 
1335   // Handle 'field access' to vectors, such as 'V.xx'.
1336   if (BaseType->isExtVectorType()) {
1337     // FIXME: this expr should store IsArrow.
1338     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1339     ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1340     QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1341                                            Member, MemberLoc);
1342     if (ret.isNull())
1343       return ExprError();
1344 
1345     return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1346                                                     *Member, MemberLoc));
1347   }
1348 
1349   // Adjust builtin-sel to the appropriate redefinition type if that's
1350   // not just a pointer to builtin-sel again.
1351   if (IsArrow &&
1352       BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1353       !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1354     BaseExpr = ImpCastExprToType(BaseExpr.take(),
1355                                  Context.getObjCSelRedefinitionType(),
1356                                  CK_BitCast);
1357     return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1358                             ObjCImpDecl, HasTemplateArgs);
1359   }
1360 
1361   // Failure cases.
1362  fail:
1363 
1364   // Recover from dot accesses to pointers, e.g.:
1365   //   type *foo;
1366   //   foo.bar
1367   // This is actually well-formed in two cases:
1368   //   - 'type' is an Objective C type
1369   //   - 'bar' is a pseudo-destructor name which happens to refer to
1370   //     the appropriate pointer type
1371   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1372     if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1373         MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1374       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1375         << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1376           << FixItHint::CreateReplacement(OpLoc, "->");
1377 
1378       // Recurse as an -> access.
1379       IsArrow = true;
1380       return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1381                               ObjCImpDecl, HasTemplateArgs);
1382     }
1383   }
1384 
1385   // If the user is trying to apply -> or . to a function name, it's probably
1386   // because they forgot parentheses to call that function.
1387   if (tryToRecoverWithCall(BaseExpr,
1388                            PDiag(diag::err_member_reference_needs_call),
1389                            /*complain*/ false,
1390                            IsArrow ? &isPointerToRecordType : &isRecordType)) {
1391     if (BaseExpr.isInvalid())
1392       return ExprError();
1393     BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1394     return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1395                             ObjCImpDecl, HasTemplateArgs);
1396   }
1397 
1398   Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1399     << BaseType << BaseExpr.get()->getSourceRange();
1400 
1401   return ExprError();
1402 }
1403 
1404 /// The main callback when the parser finds something like
1405 ///   expression . [nested-name-specifier] identifier
1406 ///   expression -> [nested-name-specifier] identifier
1407 /// where 'identifier' encompasses a fairly broad spectrum of
1408 /// possibilities, including destructor and operator references.
1409 ///
1410 /// \param OpKind either tok::arrow or tok::period
1411 /// \param HasTrailingLParen whether the next token is '(', which
1412 ///   is used to diagnose mis-uses of special members that can
1413 ///   only be called
1414 /// \param ObjCImpDecl the current ObjC @implementation decl;
1415 ///   this is an ugly hack around the fact that ObjC @implementations
1416 ///   aren't properly put in the context chain
1417 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1418                                        SourceLocation OpLoc,
1419                                        tok::TokenKind OpKind,
1420                                        CXXScopeSpec &SS,
1421                                        SourceLocation TemplateKWLoc,
1422                                        UnqualifiedId &Id,
1423                                        Decl *ObjCImpDecl,
1424                                        bool HasTrailingLParen) {
1425   if (SS.isSet() && SS.isInvalid())
1426     return ExprError();
1427 
1428   // Warn about the explicit constructor calls Microsoft extension.
1429   if (getLangOptions().MicrosoftExt &&
1430       Id.getKind() == UnqualifiedId::IK_ConstructorName)
1431     Diag(Id.getSourceRange().getBegin(),
1432          diag::ext_ms_explicit_constructor_call);
1433 
1434   TemplateArgumentListInfo TemplateArgsBuffer;
1435 
1436   // Decompose the name into its component parts.
1437   DeclarationNameInfo NameInfo;
1438   const TemplateArgumentListInfo *TemplateArgs;
1439   DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1440                          NameInfo, TemplateArgs);
1441 
1442   DeclarationName Name = NameInfo.getName();
1443   bool IsArrow = (OpKind == tok::arrow);
1444 
1445   NamedDecl *FirstQualifierInScope
1446     = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1447                        static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1448 
1449   // This is a postfix expression, so get rid of ParenListExprs.
1450   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1451   if (Result.isInvalid()) return ExprError();
1452   Base = Result.take();
1453 
1454   if (Base->getType()->isDependentType() || Name.isDependentName() ||
1455       isDependentScopeSpecifier(SS)) {
1456     Result = ActOnDependentMemberExpr(Base, Base->getType(),
1457                                       IsArrow, OpLoc,
1458                                       SS, TemplateKWLoc, FirstQualifierInScope,
1459                                       NameInfo, TemplateArgs);
1460   } else {
1461     LookupResult R(*this, NameInfo, LookupMemberName);
1462     ExprResult BaseResult = Owned(Base);
1463     Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1464                               SS, ObjCImpDecl, TemplateArgs != 0);
1465     if (BaseResult.isInvalid())
1466       return ExprError();
1467     Base = BaseResult.take();
1468 
1469     if (Result.isInvalid()) {
1470       Owned(Base);
1471       return ExprError();
1472     }
1473 
1474     if (Result.get()) {
1475       // The only way a reference to a destructor can be used is to
1476       // immediately call it, which falls into this case.  If the
1477       // next token is not a '(', produce a diagnostic and build the
1478       // call now.
1479       if (!HasTrailingLParen &&
1480           Id.getKind() == UnqualifiedId::IK_DestructorName)
1481         return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1482 
1483       return move(Result);
1484     }
1485 
1486     Result = BuildMemberReferenceExpr(Base, Base->getType(),
1487                                       OpLoc, IsArrow, SS, TemplateKWLoc,
1488                                       FirstQualifierInScope, R, TemplateArgs);
1489   }
1490 
1491   return move(Result);
1492 }
1493 
1494 static ExprResult
1495 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1496                         const CXXScopeSpec &SS, FieldDecl *Field,
1497                         DeclAccessPair FoundDecl,
1498                         const DeclarationNameInfo &MemberNameInfo) {
1499   // x.a is an l-value if 'a' has a reference type. Otherwise:
1500   // x.a is an l-value/x-value/pr-value if the base is (and note
1501   //   that *x is always an l-value), except that if the base isn't
1502   //   an ordinary object then we must have an rvalue.
1503   ExprValueKind VK = VK_LValue;
1504   ExprObjectKind OK = OK_Ordinary;
1505   if (!IsArrow) {
1506     if (BaseExpr->getObjectKind() == OK_Ordinary)
1507       VK = BaseExpr->getValueKind();
1508     else
1509       VK = VK_RValue;
1510   }
1511   if (VK != VK_RValue && Field->isBitField())
1512     OK = OK_BitField;
1513 
1514   // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1515   QualType MemberType = Field->getType();
1516   if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1517     MemberType = Ref->getPointeeType();
1518     VK = VK_LValue;
1519   } else {
1520     QualType BaseType = BaseExpr->getType();
1521     if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1522 
1523     Qualifiers BaseQuals = BaseType.getQualifiers();
1524 
1525     // GC attributes are never picked up by members.
1526     BaseQuals.removeObjCGCAttr();
1527 
1528     // CVR attributes from the base are picked up by members,
1529     // except that 'mutable' members don't pick up 'const'.
1530     if (Field->isMutable()) BaseQuals.removeConst();
1531 
1532     Qualifiers MemberQuals
1533     = S.Context.getCanonicalType(MemberType).getQualifiers();
1534 
1535     // TR 18037 does not allow fields to be declared with address spaces.
1536     assert(!MemberQuals.hasAddressSpace());
1537 
1538     Qualifiers Combined = BaseQuals + MemberQuals;
1539     if (Combined != MemberQuals)
1540       MemberType = S.Context.getQualifiedType(MemberType, Combined);
1541   }
1542 
1543   S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1544   ExprResult Base =
1545   S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1546                                   FoundDecl, Field);
1547   if (Base.isInvalid())
1548     return ExprError();
1549   return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
1550                                  /*TemplateKWLoc=*/SourceLocation(),
1551                                  Field, FoundDecl, MemberNameInfo,
1552                                  MemberType, VK, OK));
1553 }
1554 
1555 /// Builds an implicit member access expression.  The current context
1556 /// is known to be an instance method, and the given unqualified lookup
1557 /// set is known to contain only instance members, at least one of which
1558 /// is from an appropriate type.
1559 ExprResult
1560 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1561                               SourceLocation TemplateKWLoc,
1562                               LookupResult &R,
1563                               const TemplateArgumentListInfo *TemplateArgs,
1564                               bool IsKnownInstance) {
1565   assert(!R.empty() && !R.isAmbiguous());
1566 
1567   SourceLocation loc = R.getNameLoc();
1568 
1569   // We may have found a field within an anonymous union or struct
1570   // (C++ [class.union]).
1571   // FIXME: template-ids inside anonymous structs?
1572   if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1573     return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1574 
1575   // If this is known to be an instance access, go ahead and build an
1576   // implicit 'this' expression now.
1577   // 'this' expression now.
1578   QualType ThisTy = getCurrentThisType();
1579   assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1580 
1581   Expr *baseExpr = 0; // null signifies implicit access
1582   if (IsKnownInstance) {
1583     SourceLocation Loc = R.getNameLoc();
1584     if (SS.getRange().isValid())
1585       Loc = SS.getRange().getBegin();
1586     CheckCXXThisCapture(Loc);
1587     baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1588   }
1589 
1590   return BuildMemberReferenceExpr(baseExpr, ThisTy,
1591                                   /*OpLoc*/ SourceLocation(),
1592                                   /*IsArrow*/ true,
1593                                   SS, TemplateKWLoc,
1594                                   /*FirstQualifierInScope*/ 0,
1595                                   R, TemplateArgs);
1596 }
1597