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