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