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