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