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