1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for Objective C declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/RecursiveASTVisitor.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "clang/Sema/DeclSpec.h" 24 #include "clang/Sema/Lookup.h" 25 #include "clang/Sema/Scope.h" 26 #include "clang/Sema/ScopeInfo.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/DenseSet.h" 30 31 using namespace clang; 32 33 /// Check whether the given method, which must be in the 'init' 34 /// family, is a valid member of that family. 35 /// 36 /// \param receiverTypeIfCall - if null, check this as if declaring it; 37 /// if non-null, check this as if making a call to it with the given 38 /// receiver type 39 /// 40 /// \return true to indicate that there was an error and appropriate 41 /// actions were taken 42 bool Sema::checkInitMethod(ObjCMethodDecl *method, 43 QualType receiverTypeIfCall) { 44 if (method->isInvalidDecl()) return true; 45 46 // This castAs is safe: methods that don't return an object 47 // pointer won't be inferred as inits and will reject an explicit 48 // objc_method_family(init). 49 50 // We ignore protocols here. Should we? What about Class? 51 52 const ObjCObjectType *result = 53 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType(); 54 55 if (result->isObjCId()) { 56 return false; 57 } else if (result->isObjCClass()) { 58 // fall through: always an error 59 } else { 60 ObjCInterfaceDecl *resultClass = result->getInterface(); 61 assert(resultClass && "unexpected object type!"); 62 63 // It's okay for the result type to still be a forward declaration 64 // if we're checking an interface declaration. 65 if (!resultClass->hasDefinition()) { 66 if (receiverTypeIfCall.isNull() && 67 !isa<ObjCImplementationDecl>(method->getDeclContext())) 68 return false; 69 70 // Otherwise, we try to compare class types. 71 } else { 72 // If this method was declared in a protocol, we can't check 73 // anything unless we have a receiver type that's an interface. 74 const ObjCInterfaceDecl *receiverClass = nullptr; 75 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 76 if (receiverTypeIfCall.isNull()) 77 return false; 78 79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 80 ->getInterfaceDecl(); 81 82 // This can be null for calls to e.g. id<Foo>. 83 if (!receiverClass) return false; 84 } else { 85 receiverClass = method->getClassInterface(); 86 assert(receiverClass && "method not associated with a class!"); 87 } 88 89 // If either class is a subclass of the other, it's fine. 90 if (receiverClass->isSuperClassOf(resultClass) || 91 resultClass->isSuperClassOf(receiverClass)) 92 return false; 93 } 94 } 95 96 SourceLocation loc = method->getLocation(); 97 98 // If we're in a system header, and this is not a call, just make 99 // the method unusable. 100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "", 102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc)); 103 return true; 104 } 105 106 // Otherwise, it's an error. 107 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 108 method->setInvalidDecl(); 109 return true; 110 } 111 112 /// Issue a warning if the parameter of the overridden method is non-escaping 113 /// but the parameter of the overriding method is not. 114 static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, 115 Sema &S) { 116 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) { 117 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape); 118 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape); 119 return false; 120 } 121 122 return true; 123 } 124 125 /// Produce additional diagnostics if a category conforms to a protocol that 126 /// defines a method taking a non-escaping parameter. 127 static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, 128 const ObjCCategoryDecl *CD, 129 const ObjCProtocolDecl *PD, Sema &S) { 130 if (!diagnoseNoescape(NewD, OldD, S)) 131 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot) 132 << CD->IsClassExtension() << PD 133 << cast<ObjCMethodDecl>(NewD->getDeclContext()); 134 } 135 136 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 137 const ObjCMethodDecl *Overridden) { 138 if (Overridden->hasRelatedResultType() && 139 !NewMethod->hasRelatedResultType()) { 140 // This can only happen when the method follows a naming convention that 141 // implies a related result type, and the original (overridden) method has 142 // a suitable return type, but the new (overriding) method does not have 143 // a suitable return type. 144 QualType ResultType = NewMethod->getReturnType(); 145 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange(); 146 147 // Figure out which class this method is part of, if any. 148 ObjCInterfaceDecl *CurrentClass 149 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); 150 if (!CurrentClass) { 151 DeclContext *DC = NewMethod->getDeclContext(); 152 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC)) 153 CurrentClass = Cat->getClassInterface(); 154 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC)) 155 CurrentClass = Impl->getClassInterface(); 156 else if (ObjCCategoryImplDecl *CatImpl 157 = dyn_cast<ObjCCategoryImplDecl>(DC)) 158 CurrentClass = CatImpl->getClassInterface(); 159 } 160 161 if (CurrentClass) { 162 Diag(NewMethod->getLocation(), 163 diag::warn_related_result_type_compatibility_class) 164 << Context.getObjCInterfaceType(CurrentClass) 165 << ResultType 166 << ResultTypeRange; 167 } else { 168 Diag(NewMethod->getLocation(), 169 diag::warn_related_result_type_compatibility_protocol) 170 << ResultType 171 << ResultTypeRange; 172 } 173 174 if (ObjCMethodFamily Family = Overridden->getMethodFamily()) 175 Diag(Overridden->getLocation(), 176 diag::note_related_result_type_family) 177 << /*overridden method*/ 0 178 << Family; 179 else 180 Diag(Overridden->getLocation(), 181 diag::note_related_result_type_overridden); 182 } 183 184 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() != 185 Overridden->hasAttr<NSReturnsRetainedAttr>())) { 186 Diag(NewMethod->getLocation(), 187 getLangOpts().ObjCAutoRefCount 188 ? diag::err_nsreturns_retained_attribute_mismatch 189 : diag::warn_nsreturns_retained_attribute_mismatch) 190 << 1; 191 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method"; 192 } 193 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() != 194 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) { 195 Diag(NewMethod->getLocation(), 196 getLangOpts().ObjCAutoRefCount 197 ? diag::err_nsreturns_retained_attribute_mismatch 198 : diag::warn_nsreturns_retained_attribute_mismatch) 199 << 0; 200 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method"; 201 } 202 203 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 204 oe = Overridden->param_end(); 205 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(), 206 ne = NewMethod->param_end(); 207 ni != ne && oi != oe; ++ni, ++oi) { 208 const ParmVarDecl *oldDecl = (*oi); 209 ParmVarDecl *newDecl = (*ni); 210 if (newDecl->hasAttr<NSConsumedAttr>() != 211 oldDecl->hasAttr<NSConsumedAttr>()) { 212 Diag(newDecl->getLocation(), 213 getLangOpts().ObjCAutoRefCount 214 ? diag::err_nsconsumed_attribute_mismatch 215 : diag::warn_nsconsumed_attribute_mismatch); 216 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter"; 217 } 218 219 diagnoseNoescape(newDecl, oldDecl, *this); 220 } 221 } 222 223 /// Check a method declaration for compatibility with the Objective-C 224 /// ARC conventions. 225 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { 226 ObjCMethodFamily family = method->getMethodFamily(); 227 switch (family) { 228 case OMF_None: 229 case OMF_finalize: 230 case OMF_retain: 231 case OMF_release: 232 case OMF_autorelease: 233 case OMF_retainCount: 234 case OMF_self: 235 case OMF_initialize: 236 case OMF_performSelector: 237 return false; 238 239 case OMF_dealloc: 240 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) { 241 SourceRange ResultTypeRange = method->getReturnTypeSourceRange(); 242 if (ResultTypeRange.isInvalid()) 243 Diag(method->getLocation(), diag::err_dealloc_bad_result_type) 244 << method->getReturnType() 245 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 246 else 247 Diag(method->getLocation(), diag::err_dealloc_bad_result_type) 248 << method->getReturnType() 249 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 250 return true; 251 } 252 return false; 253 254 case OMF_init: 255 // If the method doesn't obey the init rules, don't bother annotating it. 256 if (checkInitMethod(method, QualType())) 257 return true; 258 259 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context)); 260 261 // Don't add a second copy of this attribute, but otherwise don't 262 // let it be suppressed. 263 if (method->hasAttr<NSReturnsRetainedAttr>()) 264 return false; 265 break; 266 267 case OMF_alloc: 268 case OMF_copy: 269 case OMF_mutableCopy: 270 case OMF_new: 271 if (method->hasAttr<NSReturnsRetainedAttr>() || 272 method->hasAttr<NSReturnsNotRetainedAttr>() || 273 method->hasAttr<NSReturnsAutoreleasedAttr>()) 274 return false; 275 break; 276 } 277 278 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context)); 279 return false; 280 } 281 282 static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND, 283 SourceLocation ImplLoc) { 284 if (!ND) 285 return; 286 bool IsCategory = false; 287 StringRef RealizedPlatform; 288 AvailabilityResult Availability = ND->getAvailability( 289 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(), 290 &RealizedPlatform); 291 if (Availability != AR_Deprecated) { 292 if (isa<ObjCMethodDecl>(ND)) { 293 if (Availability != AR_Unavailable) 294 return; 295 if (RealizedPlatform.empty()) 296 RealizedPlatform = S.Context.getTargetInfo().getPlatformName(); 297 // Warn about implementing unavailable methods, unless the unavailable 298 // is for an app extension. 299 if (RealizedPlatform.endswith("_app_extension")) 300 return; 301 S.Diag(ImplLoc, diag::warn_unavailable_def); 302 S.Diag(ND->getLocation(), diag::note_method_declared_at) 303 << ND->getDeclName(); 304 return; 305 } 306 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) { 307 if (!CD->getClassInterface()->isDeprecated()) 308 return; 309 ND = CD->getClassInterface(); 310 IsCategory = true; 311 } else 312 return; 313 } 314 S.Diag(ImplLoc, diag::warn_deprecated_def) 315 << (isa<ObjCMethodDecl>(ND) 316 ? /*Method*/ 0 317 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2 318 : /*Class*/ 1); 319 if (isa<ObjCMethodDecl>(ND)) 320 S.Diag(ND->getLocation(), diag::note_method_declared_at) 321 << ND->getDeclName(); 322 else 323 S.Diag(ND->getLocation(), diag::note_previous_decl) 324 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class"); 325 } 326 327 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 328 /// pool. 329 void Sema::AddAnyMethodToGlobalPool(Decl *D) { 330 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 331 332 // If we don't have a valid method decl, simply return. 333 if (!MDecl) 334 return; 335 if (MDecl->isInstanceMethod()) 336 AddInstanceMethodToGlobalPool(MDecl, true); 337 else 338 AddFactoryMethodToGlobalPool(MDecl, true); 339 } 340 341 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer 342 /// has explicit ownership attribute; false otherwise. 343 static bool 344 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { 345 QualType T = Param->getType(); 346 347 if (const PointerType *PT = T->getAs<PointerType>()) { 348 T = PT->getPointeeType(); 349 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 350 T = RT->getPointeeType(); 351 } else { 352 return true; 353 } 354 355 // If we have a lifetime qualifier, but it's local, we must have 356 // inferred it. So, it is implicit. 357 return !T.getLocalQualifiers().hasObjCLifetime(); 358 } 359 360 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 361 /// and user declared, in the method definition's AST. 362 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 363 ImplicitlyRetainedSelfLocs.clear(); 364 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused"); 365 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 366 367 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 368 369 // If we don't have a valid method decl, simply return. 370 if (!MDecl) 371 return; 372 373 QualType ResultType = MDecl->getReturnType(); 374 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 375 !MDecl->isInvalidDecl() && 376 RequireCompleteType(MDecl->getLocation(), ResultType, 377 diag::err_func_def_incomplete_result)) 378 MDecl->setInvalidDecl(); 379 380 // Allow all of Sema to see that we are entering a method definition. 381 PushDeclContext(FnBodyScope, MDecl); 382 PushFunctionScope(); 383 384 // Create Decl objects for each parameter, entrring them in the scope for 385 // binding to their use. 386 387 // Insert the invisible arguments, self and _cmd! 388 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 389 390 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 391 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 392 393 // The ObjC parser requires parameter names so there's no need to check. 394 CheckParmsForFunctionDef(MDecl->parameters(), 395 /*CheckParameterNames=*/false); 396 397 // Introduce all of the other parameters into this scope. 398 for (auto *Param : MDecl->parameters()) { 399 if (!Param->isInvalidDecl() && 400 getLangOpts().ObjCAutoRefCount && 401 !HasExplicitOwnershipAttr(*this, Param)) 402 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << 403 Param->getType(); 404 405 if (Param->getIdentifier()) 406 PushOnScopeChains(Param, FnBodyScope); 407 } 408 409 // In ARC, disallow definition of retain/release/autorelease/retainCount 410 if (getLangOpts().ObjCAutoRefCount) { 411 switch (MDecl->getMethodFamily()) { 412 case OMF_retain: 413 case OMF_retainCount: 414 case OMF_release: 415 case OMF_autorelease: 416 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 417 << 0 << MDecl->getSelector(); 418 break; 419 420 case OMF_None: 421 case OMF_dealloc: 422 case OMF_finalize: 423 case OMF_alloc: 424 case OMF_init: 425 case OMF_mutableCopy: 426 case OMF_copy: 427 case OMF_new: 428 case OMF_self: 429 case OMF_initialize: 430 case OMF_performSelector: 431 break; 432 } 433 } 434 435 // Warn on deprecated methods under -Wdeprecated-implementations, 436 // and prepare for warning on missing super calls. 437 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 438 ObjCMethodDecl *IMD = 439 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); 440 441 if (IMD) { 442 ObjCImplDecl *ImplDeclOfMethodDef = 443 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); 444 ObjCContainerDecl *ContDeclOfMethodDecl = 445 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); 446 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr; 447 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) 448 ImplDeclOfMethodDecl = OID->getImplementation(); 449 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) { 450 if (CD->IsClassExtension()) { 451 if (ObjCInterfaceDecl *OID = CD->getClassInterface()) 452 ImplDeclOfMethodDecl = OID->getImplementation(); 453 } else 454 ImplDeclOfMethodDecl = CD->getImplementation(); 455 } 456 // No need to issue deprecated warning if deprecated mehod in class/category 457 // is being implemented in its own implementation (no overriding is involved). 458 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef) 459 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation()); 460 } 461 462 if (MDecl->getMethodFamily() == OMF_init) { 463 if (MDecl->isDesignatedInitializerForTheInterface()) { 464 getCurFunction()->ObjCIsDesignatedInit = true; 465 getCurFunction()->ObjCWarnForNoDesignatedInitChain = 466 IC->getSuperClass() != nullptr; 467 } else if (IC->hasDesignatedInitializers()) { 468 getCurFunction()->ObjCIsSecondaryInit = true; 469 getCurFunction()->ObjCWarnForNoInitDelegation = true; 470 } 471 } 472 473 // If this is "dealloc" or "finalize", set some bit here. 474 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 475 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 476 // Only do this if the current class actually has a superclass. 477 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) { 478 ObjCMethodFamily Family = MDecl->getMethodFamily(); 479 if (Family == OMF_dealloc) { 480 if (!(getLangOpts().ObjCAutoRefCount || 481 getLangOpts().getGC() == LangOptions::GCOnly)) 482 getCurFunction()->ObjCShouldCallSuper = true; 483 484 } else if (Family == OMF_finalize) { 485 if (Context.getLangOpts().getGC() != LangOptions::NonGC) 486 getCurFunction()->ObjCShouldCallSuper = true; 487 488 } else { 489 const ObjCMethodDecl *SuperMethod = 490 SuperClass->lookupMethod(MDecl->getSelector(), 491 MDecl->isInstanceMethod()); 492 getCurFunction()->ObjCShouldCallSuper = 493 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); 494 } 495 } 496 } 497 } 498 499 namespace { 500 501 // Callback to only accept typo corrections that are Objective-C classes. 502 // If an ObjCInterfaceDecl* is given to the constructor, then the validation 503 // function will reject corrections to that class. 504 class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback { 505 public: 506 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {} 507 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl) 508 : CurrentIDecl(IDecl) {} 509 510 bool ValidateCandidate(const TypoCorrection &candidate) override { 511 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>(); 512 return ID && !declaresSameEntity(ID, CurrentIDecl); 513 } 514 515 std::unique_ptr<CorrectionCandidateCallback> clone() override { 516 return std::make_unique<ObjCInterfaceValidatorCCC>(*this); 517 } 518 519 private: 520 ObjCInterfaceDecl *CurrentIDecl; 521 }; 522 523 } // end anonymous namespace 524 525 static void diagnoseUseOfProtocols(Sema &TheSema, 526 ObjCContainerDecl *CD, 527 ObjCProtocolDecl *const *ProtoRefs, 528 unsigned NumProtoRefs, 529 const SourceLocation *ProtoLocs) { 530 assert(ProtoRefs); 531 // Diagnose availability in the context of the ObjC container. 532 Sema::ContextRAII SavedContext(TheSema, CD); 533 for (unsigned i = 0; i < NumProtoRefs; ++i) { 534 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i], 535 /*UnknownObjCClass=*/nullptr, 536 /*ObjCPropertyAccess=*/false, 537 /*AvoidPartialAvailabilityChecks=*/true); 538 } 539 } 540 541 void Sema:: 542 ActOnSuperClassOfClassInterface(Scope *S, 543 SourceLocation AtInterfaceLoc, 544 ObjCInterfaceDecl *IDecl, 545 IdentifierInfo *ClassName, 546 SourceLocation ClassLoc, 547 IdentifierInfo *SuperName, 548 SourceLocation SuperLoc, 549 ArrayRef<ParsedType> SuperTypeArgs, 550 SourceRange SuperTypeArgsRange) { 551 // Check if a different kind of symbol declared in this scope. 552 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 553 LookupOrdinaryName); 554 555 if (!PrevDecl) { 556 // Try to correct for a typo in the superclass name without correcting 557 // to the class we're defining. 558 ObjCInterfaceValidatorCCC CCC(IDecl); 559 if (TypoCorrection Corrected = CorrectTypo( 560 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, 561 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 562 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest) 563 << SuperName << ClassName); 564 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 565 } 566 } 567 568 if (declaresSameEntity(PrevDecl, IDecl)) { 569 Diag(SuperLoc, diag::err_recursive_superclass) 570 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 571 IDecl->setEndOfDefinitionLoc(ClassLoc); 572 } else { 573 ObjCInterfaceDecl *SuperClassDecl = 574 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 575 QualType SuperClassType; 576 577 // Diagnose classes that inherit from deprecated classes. 578 if (SuperClassDecl) { 579 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 580 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl); 581 } 582 583 if (PrevDecl && !SuperClassDecl) { 584 // The previous declaration was not a class decl. Check if we have a 585 // typedef. If we do, get the underlying class type. 586 if (const TypedefNameDecl *TDecl = 587 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 588 QualType T = TDecl->getUnderlyingType(); 589 if (T->isObjCObjectType()) { 590 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) { 591 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 592 SuperClassType = Context.getTypeDeclType(TDecl); 593 594 // This handles the following case: 595 // @interface NewI @end 596 // typedef NewI DeprI __attribute__((deprecated("blah"))) 597 // @interface SI : DeprI /* warn here */ @end 598 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc); 599 } 600 } 601 } 602 603 // This handles the following case: 604 // 605 // typedef int SuperClass; 606 // @interface MyClass : SuperClass {} @end 607 // 608 if (!SuperClassDecl) { 609 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 610 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 611 } 612 } 613 614 if (!isa_and_nonnull<TypedefNameDecl>(PrevDecl)) { 615 if (!SuperClassDecl) 616 Diag(SuperLoc, diag::err_undef_superclass) 617 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 618 else if (RequireCompleteType(SuperLoc, 619 SuperClassType, 620 diag::err_forward_superclass, 621 SuperClassDecl->getDeclName(), 622 ClassName, 623 SourceRange(AtInterfaceLoc, ClassLoc))) { 624 SuperClassDecl = nullptr; 625 SuperClassType = QualType(); 626 } 627 } 628 629 if (SuperClassType.isNull()) { 630 assert(!SuperClassDecl && "Failed to set SuperClassType?"); 631 return; 632 } 633 634 // Handle type arguments on the superclass. 635 TypeSourceInfo *SuperClassTInfo = nullptr; 636 if (!SuperTypeArgs.empty()) { 637 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers( 638 S, 639 SuperLoc, 640 CreateParsedType(SuperClassType, 641 nullptr), 642 SuperTypeArgsRange.getBegin(), 643 SuperTypeArgs, 644 SuperTypeArgsRange.getEnd(), 645 SourceLocation(), 646 { }, 647 { }, 648 SourceLocation()); 649 if (!fullSuperClassType.isUsable()) 650 return; 651 652 SuperClassType = GetTypeFromParser(fullSuperClassType.get(), 653 &SuperClassTInfo); 654 } 655 656 if (!SuperClassTInfo) { 657 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, 658 SuperLoc); 659 } 660 661 IDecl->setSuperClass(SuperClassTInfo); 662 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc()); 663 } 664 } 665 666 DeclResult Sema::actOnObjCTypeParam(Scope *S, 667 ObjCTypeParamVariance variance, 668 SourceLocation varianceLoc, 669 unsigned index, 670 IdentifierInfo *paramName, 671 SourceLocation paramLoc, 672 SourceLocation colonLoc, 673 ParsedType parsedTypeBound) { 674 // If there was an explicitly-provided type bound, check it. 675 TypeSourceInfo *typeBoundInfo = nullptr; 676 if (parsedTypeBound) { 677 // The type bound can be any Objective-C pointer type. 678 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo); 679 if (typeBound->isObjCObjectPointerType()) { 680 // okay 681 } else if (typeBound->isObjCObjectType()) { 682 // The user forgot the * on an Objective-C pointer type, e.g., 683 // "T : NSView". 684 SourceLocation starLoc = getLocForEndOfToken( 685 typeBoundInfo->getTypeLoc().getEndLoc()); 686 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 687 diag::err_objc_type_param_bound_missing_pointer) 688 << typeBound << paramName 689 << FixItHint::CreateInsertion(starLoc, " *"); 690 691 // Create a new type location builder so we can update the type 692 // location information we have. 693 TypeLocBuilder builder; 694 builder.pushFullCopy(typeBoundInfo->getTypeLoc()); 695 696 // Create the Objective-C pointer type. 697 typeBound = Context.getObjCObjectPointerType(typeBound); 698 ObjCObjectPointerTypeLoc newT 699 = builder.push<ObjCObjectPointerTypeLoc>(typeBound); 700 newT.setStarLoc(starLoc); 701 702 // Form the new type source information. 703 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound); 704 } else { 705 // Not a valid type bound. 706 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 707 diag::err_objc_type_param_bound_nonobject) 708 << typeBound << paramName; 709 710 // Forget the bound; we'll default to id later. 711 typeBoundInfo = nullptr; 712 } 713 714 // Type bounds cannot have qualifiers (even indirectly) or explicit 715 // nullability. 716 if (typeBoundInfo) { 717 QualType typeBound = typeBoundInfo->getType(); 718 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc(); 719 if (qual || typeBound.hasQualifiers()) { 720 bool diagnosed = false; 721 SourceRange rangeToRemove; 722 if (qual) { 723 if (auto attr = qual.getAs<AttributedTypeLoc>()) { 724 rangeToRemove = attr.getLocalSourceRange(); 725 if (attr.getTypePtr()->getImmediateNullability()) { 726 Diag(attr.getBeginLoc(), 727 diag::err_objc_type_param_bound_explicit_nullability) 728 << paramName << typeBound 729 << FixItHint::CreateRemoval(rangeToRemove); 730 diagnosed = true; 731 } 732 } 733 } 734 735 if (!diagnosed) { 736 Diag(qual ? qual.getBeginLoc() 737 : typeBoundInfo->getTypeLoc().getBeginLoc(), 738 diag::err_objc_type_param_bound_qualified) 739 << paramName << typeBound 740 << typeBound.getQualifiers().getAsString() 741 << FixItHint::CreateRemoval(rangeToRemove); 742 } 743 744 // If the type bound has qualifiers other than CVR, we need to strip 745 // them or we'll probably assert later when trying to apply new 746 // qualifiers. 747 Qualifiers quals = typeBound.getQualifiers(); 748 quals.removeCVRQualifiers(); 749 if (!quals.empty()) { 750 typeBoundInfo = 751 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType()); 752 } 753 } 754 } 755 } 756 757 // If there was no explicit type bound (or we removed it due to an error), 758 // use 'id' instead. 759 if (!typeBoundInfo) { 760 colonLoc = SourceLocation(); 761 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType()); 762 } 763 764 // Create the type parameter. 765 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc, 766 index, paramLoc, paramName, colonLoc, 767 typeBoundInfo); 768 } 769 770 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S, 771 SourceLocation lAngleLoc, 772 ArrayRef<Decl *> typeParamsIn, 773 SourceLocation rAngleLoc) { 774 // We know that the array only contains Objective-C type parameters. 775 ArrayRef<ObjCTypeParamDecl *> 776 typeParams( 777 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()), 778 typeParamsIn.size()); 779 780 // Diagnose redeclarations of type parameters. 781 // We do this now because Objective-C type parameters aren't pushed into 782 // scope until later (after the instance variable block), but we want the 783 // diagnostics to occur right after we parse the type parameter list. 784 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams; 785 for (auto *typeParam : typeParams) { 786 auto known = knownParams.find(typeParam->getIdentifier()); 787 if (known != knownParams.end()) { 788 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl) 789 << typeParam->getIdentifier() 790 << SourceRange(known->second->getLocation()); 791 792 typeParam->setInvalidDecl(); 793 } else { 794 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam)); 795 796 // Push the type parameter into scope. 797 PushOnScopeChains(typeParam, S, /*AddToContext=*/false); 798 } 799 } 800 801 // Create the parameter list. 802 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc); 803 } 804 805 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) { 806 for (auto *typeParam : *typeParamList) { 807 if (!typeParam->isInvalidDecl()) { 808 S->RemoveDecl(typeParam); 809 IdResolver.RemoveDecl(typeParam); 810 } 811 } 812 } 813 814 namespace { 815 /// The context in which an Objective-C type parameter list occurs, for use 816 /// in diagnostics. 817 enum class TypeParamListContext { 818 ForwardDeclaration, 819 Definition, 820 Category, 821 Extension 822 }; 823 } // end anonymous namespace 824 825 /// Check consistency between two Objective-C type parameter lists, e.g., 826 /// between a category/extension and an \@interface or between an \@class and an 827 /// \@interface. 828 static bool checkTypeParamListConsistency(Sema &S, 829 ObjCTypeParamList *prevTypeParams, 830 ObjCTypeParamList *newTypeParams, 831 TypeParamListContext newContext) { 832 // If the sizes don't match, complain about that. 833 if (prevTypeParams->size() != newTypeParams->size()) { 834 SourceLocation diagLoc; 835 if (newTypeParams->size() > prevTypeParams->size()) { 836 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation(); 837 } else { 838 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc()); 839 } 840 841 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch) 842 << static_cast<unsigned>(newContext) 843 << (newTypeParams->size() > prevTypeParams->size()) 844 << prevTypeParams->size() 845 << newTypeParams->size(); 846 847 return true; 848 } 849 850 // Match up the type parameters. 851 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) { 852 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i]; 853 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i]; 854 855 // Check for consistency of the variance. 856 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) { 857 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant && 858 newContext != TypeParamListContext::Definition) { 859 // When the new type parameter is invariant and is not part 860 // of the definition, just propagate the variance. 861 newTypeParam->setVariance(prevTypeParam->getVariance()); 862 } else if (prevTypeParam->getVariance() 863 == ObjCTypeParamVariance::Invariant && 864 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) && 865 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) 866 ->getDefinition() == prevTypeParam->getDeclContext())) { 867 // When the old parameter is invariant and was not part of the 868 // definition, just ignore the difference because it doesn't 869 // matter. 870 } else { 871 { 872 // Diagnose the conflict and update the second declaration. 873 SourceLocation diagLoc = newTypeParam->getVarianceLoc(); 874 if (diagLoc.isInvalid()) 875 diagLoc = newTypeParam->getBeginLoc(); 876 877 auto diag = S.Diag(diagLoc, 878 diag::err_objc_type_param_variance_conflict) 879 << static_cast<unsigned>(newTypeParam->getVariance()) 880 << newTypeParam->getDeclName() 881 << static_cast<unsigned>(prevTypeParam->getVariance()) 882 << prevTypeParam->getDeclName(); 883 switch (prevTypeParam->getVariance()) { 884 case ObjCTypeParamVariance::Invariant: 885 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc()); 886 break; 887 888 case ObjCTypeParamVariance::Covariant: 889 case ObjCTypeParamVariance::Contravariant: { 890 StringRef newVarianceStr 891 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant 892 ? "__covariant" 893 : "__contravariant"; 894 if (newTypeParam->getVariance() 895 == ObjCTypeParamVariance::Invariant) { 896 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(), 897 (newVarianceStr + " ").str()); 898 } else { 899 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(), 900 newVarianceStr); 901 } 902 } 903 } 904 } 905 906 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 907 << prevTypeParam->getDeclName(); 908 909 // Override the variance. 910 newTypeParam->setVariance(prevTypeParam->getVariance()); 911 } 912 } 913 914 // If the bound types match, there's nothing to do. 915 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(), 916 newTypeParam->getUnderlyingType())) 917 continue; 918 919 // If the new type parameter's bound was explicit, complain about it being 920 // different from the original. 921 if (newTypeParam->hasExplicitBound()) { 922 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo() 923 ->getTypeLoc().getSourceRange(); 924 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict) 925 << newTypeParam->getUnderlyingType() 926 << newTypeParam->getDeclName() 927 << prevTypeParam->hasExplicitBound() 928 << prevTypeParam->getUnderlyingType() 929 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName()) 930 << prevTypeParam->getDeclName() 931 << FixItHint::CreateReplacement( 932 newBoundRange, 933 prevTypeParam->getUnderlyingType().getAsString( 934 S.Context.getPrintingPolicy())); 935 936 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 937 << prevTypeParam->getDeclName(); 938 939 // Override the new type parameter's bound type with the previous type, 940 // so that it's consistent. 941 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam); 942 continue; 943 } 944 945 // The new type parameter got the implicit bound of 'id'. That's okay for 946 // categories and extensions (overwrite it later), but not for forward 947 // declarations and @interfaces, because those must be standalone. 948 if (newContext == TypeParamListContext::ForwardDeclaration || 949 newContext == TypeParamListContext::Definition) { 950 // Diagnose this problem for forward declarations and definitions. 951 SourceLocation insertionLoc 952 = S.getLocForEndOfToken(newTypeParam->getLocation()); 953 std::string newCode 954 = " : " + prevTypeParam->getUnderlyingType().getAsString( 955 S.Context.getPrintingPolicy()); 956 S.Diag(newTypeParam->getLocation(), 957 diag::err_objc_type_param_bound_missing) 958 << prevTypeParam->getUnderlyingType() 959 << newTypeParam->getDeclName() 960 << (newContext == TypeParamListContext::ForwardDeclaration) 961 << FixItHint::CreateInsertion(insertionLoc, newCode); 962 963 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 964 << prevTypeParam->getDeclName(); 965 } 966 967 // Update the new type parameter's bound to match the previous one. 968 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam); 969 } 970 971 return false; 972 } 973 974 ObjCInterfaceDecl *Sema::ActOnStartClassInterface( 975 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 976 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 977 IdentifierInfo *SuperName, SourceLocation SuperLoc, 978 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, 979 Decl *const *ProtoRefs, unsigned NumProtoRefs, 980 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 981 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) { 982 assert(ClassName && "Missing class identifier"); 983 984 // Check for another declaration kind with the same name. 985 NamedDecl *PrevDecl = 986 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 987 forRedeclarationInCurContext()); 988 989 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 990 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 991 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 992 } 993 994 // Create a declaration to describe this @interface. 995 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 996 997 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 998 // A previous decl with a different name is because of 999 // @compatibility_alias, for example: 1000 // \code 1001 // @class NewImage; 1002 // @compatibility_alias OldImage NewImage; 1003 // \endcode 1004 // A lookup for 'OldImage' will return the 'NewImage' decl. 1005 // 1006 // In such a case use the real declaration name, instead of the alias one, 1007 // otherwise we will break IdentifierResolver and redecls-chain invariants. 1008 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 1009 // has been aliased. 1010 ClassName = PrevIDecl->getIdentifier(); 1011 } 1012 1013 // If there was a forward declaration with type parameters, check 1014 // for consistency. 1015 if (PrevIDecl) { 1016 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) { 1017 if (typeParamList) { 1018 // Both have type parameter lists; check for consistency. 1019 if (checkTypeParamListConsistency(*this, prevTypeParamList, 1020 typeParamList, 1021 TypeParamListContext::Definition)) { 1022 typeParamList = nullptr; 1023 } 1024 } else { 1025 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first) 1026 << ClassName; 1027 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl) 1028 << ClassName; 1029 1030 // Clone the type parameter list. 1031 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams; 1032 for (auto *typeParam : *prevTypeParamList) { 1033 clonedTypeParams.push_back( 1034 ObjCTypeParamDecl::Create( 1035 Context, 1036 CurContext, 1037 typeParam->getVariance(), 1038 SourceLocation(), 1039 typeParam->getIndex(), 1040 SourceLocation(), 1041 typeParam->getIdentifier(), 1042 SourceLocation(), 1043 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType()))); 1044 } 1045 1046 typeParamList = ObjCTypeParamList::create(Context, 1047 SourceLocation(), 1048 clonedTypeParams, 1049 SourceLocation()); 1050 } 1051 } 1052 } 1053 1054 ObjCInterfaceDecl *IDecl 1055 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, 1056 typeParamList, PrevIDecl, ClassLoc); 1057 if (PrevIDecl) { 1058 // Class already seen. Was it a definition? 1059 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 1060 if (SkipBody && !hasVisibleDefinition(Def)) { 1061 SkipBody->CheckSameAsPrevious = true; 1062 SkipBody->New = IDecl; 1063 SkipBody->Previous = Def; 1064 } else { 1065 Diag(AtInterfaceLoc, diag::err_duplicate_class_def) 1066 << PrevIDecl->getDeclName(); 1067 Diag(Def->getLocation(), diag::note_previous_definition); 1068 IDecl->setInvalidDecl(); 1069 } 1070 } 1071 } 1072 1073 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 1074 AddPragmaAttributes(TUScope, IDecl); 1075 1076 // Merge attributes from previous declarations. 1077 if (PrevIDecl) 1078 mergeDeclAttributes(IDecl, PrevIDecl); 1079 1080 PushOnScopeChains(IDecl, TUScope); 1081 1082 // Start the definition of this class. If we're in a redefinition case, there 1083 // may already be a definition, so we'll end up adding to it. 1084 if (SkipBody && SkipBody->CheckSameAsPrevious) 1085 IDecl->startDuplicateDefinitionForComparison(); 1086 else if (!IDecl->hasDefinition()) 1087 IDecl->startDefinition(); 1088 1089 if (SuperName) { 1090 // Diagnose availability in the context of the @interface. 1091 ContextRAII SavedContext(*this, IDecl); 1092 1093 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, 1094 ClassName, ClassLoc, 1095 SuperName, SuperLoc, SuperTypeArgs, 1096 SuperTypeArgsRange); 1097 } else { // we have a root class. 1098 IDecl->setEndOfDefinitionLoc(ClassLoc); 1099 } 1100 1101 // Check then save referenced protocols. 1102 if (NumProtoRefs) { 1103 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1104 NumProtoRefs, ProtoLocs); 1105 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1106 ProtoLocs, Context); 1107 IDecl->setEndOfDefinitionLoc(EndProtoLoc); 1108 } 1109 1110 CheckObjCDeclScope(IDecl); 1111 ActOnObjCContainerStartDefinition(IDecl); 1112 return IDecl; 1113 } 1114 1115 /// ActOnTypedefedProtocols - this action finds protocol list as part of the 1116 /// typedef'ed use for a qualified super class and adds them to the list 1117 /// of the protocols. 1118 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 1119 SmallVectorImpl<SourceLocation> &ProtocolLocs, 1120 IdentifierInfo *SuperName, 1121 SourceLocation SuperLoc) { 1122 if (!SuperName) 1123 return; 1124 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 1125 LookupOrdinaryName); 1126 if (!IDecl) 1127 return; 1128 1129 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { 1130 QualType T = TDecl->getUnderlyingType(); 1131 if (T->isObjCObjectType()) 1132 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) { 1133 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end()); 1134 // FIXME: Consider whether this should be an invalid loc since the loc 1135 // is not actually pointing to a protocol name reference but to the 1136 // typedef reference. Note that the base class name loc is also pointing 1137 // at the typedef. 1138 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc); 1139 } 1140 } 1141 } 1142 1143 /// ActOnCompatibilityAlias - this action is called after complete parsing of 1144 /// a \@compatibility_alias declaration. It sets up the alias relationships. 1145 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc, 1146 IdentifierInfo *AliasName, 1147 SourceLocation AliasLocation, 1148 IdentifierInfo *ClassName, 1149 SourceLocation ClassLocation) { 1150 // Look for previous declaration of alias name 1151 NamedDecl *ADecl = 1152 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName, 1153 forRedeclarationInCurContext()); 1154 if (ADecl) { 1155 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 1156 Diag(ADecl->getLocation(), diag::note_previous_declaration); 1157 return nullptr; 1158 } 1159 // Check for class declaration 1160 NamedDecl *CDeclU = 1161 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName, 1162 forRedeclarationInCurContext()); 1163 if (const TypedefNameDecl *TDecl = 1164 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 1165 QualType T = TDecl->getUnderlyingType(); 1166 if (T->isObjCObjectType()) { 1167 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) { 1168 ClassName = IDecl->getIdentifier(); 1169 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 1170 LookupOrdinaryName, 1171 forRedeclarationInCurContext()); 1172 } 1173 } 1174 } 1175 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 1176 if (!CDecl) { 1177 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 1178 if (CDeclU) 1179 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 1180 return nullptr; 1181 } 1182 1183 // Everything checked out, instantiate a new alias declaration AST. 1184 ObjCCompatibleAliasDecl *AliasDecl = 1185 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 1186 1187 if (!CheckObjCDeclScope(AliasDecl)) 1188 PushOnScopeChains(AliasDecl, TUScope); 1189 1190 return AliasDecl; 1191 } 1192 1193 bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 1194 IdentifierInfo *PName, 1195 SourceLocation &Ploc, SourceLocation PrevLoc, 1196 const ObjCList<ObjCProtocolDecl> &PList) { 1197 1198 bool res = false; 1199 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 1200 E = PList.end(); I != E; ++I) { 1201 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 1202 Ploc)) { 1203 if (PDecl->getIdentifier() == PName) { 1204 Diag(Ploc, diag::err_protocol_has_circular_dependency); 1205 Diag(PrevLoc, diag::note_previous_definition); 1206 res = true; 1207 } 1208 1209 if (!PDecl->hasDefinition()) 1210 continue; 1211 1212 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 1213 PDecl->getLocation(), PDecl->getReferencedProtocols())) 1214 res = true; 1215 } 1216 } 1217 return res; 1218 } 1219 1220 ObjCProtocolDecl *Sema::ActOnStartProtocolInterface( 1221 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, 1222 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, 1223 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 1224 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) { 1225 bool err = false; 1226 // FIXME: Deal with AttrList. 1227 assert(ProtocolName && "Missing protocol identifier"); 1228 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc, 1229 forRedeclarationInCurContext()); 1230 ObjCProtocolDecl *PDecl = nullptr; 1231 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) { 1232 // Create a new protocol that is completely distinct from previous 1233 // declarations, and do not make this protocol available for name lookup. 1234 // That way, we'll end up completely ignoring the duplicate. 1235 // FIXME: Can we turn this into an error? 1236 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1237 ProtocolLoc, AtProtoInterfaceLoc, 1238 /*PrevDecl=*/Def); 1239 1240 if (SkipBody && !hasVisibleDefinition(Def)) { 1241 SkipBody->CheckSameAsPrevious = true; 1242 SkipBody->New = PDecl; 1243 SkipBody->Previous = Def; 1244 } else { 1245 // If we already have a definition, complain. 1246 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 1247 Diag(Def->getLocation(), diag::note_previous_definition); 1248 } 1249 1250 // If we are using modules, add the decl to the context in order to 1251 // serialize something meaningful. 1252 if (getLangOpts().Modules) 1253 PushOnScopeChains(PDecl, TUScope); 1254 PDecl->startDuplicateDefinitionForComparison(); 1255 } else { 1256 if (PrevDecl) { 1257 // Check for circular dependencies among protocol declarations. This can 1258 // only happen if this protocol was forward-declared. 1259 ObjCList<ObjCProtocolDecl> PList; 1260 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 1261 err = CheckForwardProtocolDeclarationForCircularDependency( 1262 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList); 1263 } 1264 1265 // Create the new declaration. 1266 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1267 ProtocolLoc, AtProtoInterfaceLoc, 1268 /*PrevDecl=*/PrevDecl); 1269 1270 PushOnScopeChains(PDecl, TUScope); 1271 PDecl->startDefinition(); 1272 } 1273 1274 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 1275 AddPragmaAttributes(TUScope, PDecl); 1276 1277 // Merge attributes from previous declarations. 1278 if (PrevDecl) 1279 mergeDeclAttributes(PDecl, PrevDecl); 1280 1281 if (!err && NumProtoRefs ) { 1282 /// Check then save referenced protocols. 1283 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1284 NumProtoRefs, ProtoLocs); 1285 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1286 ProtoLocs, Context); 1287 } 1288 1289 CheckObjCDeclScope(PDecl); 1290 ActOnObjCContainerStartDefinition(PDecl); 1291 return PDecl; 1292 } 1293 1294 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl, 1295 ObjCProtocolDecl *&UndefinedProtocol) { 1296 if (!PDecl->hasDefinition() || 1297 !PDecl->getDefinition()->isUnconditionallyVisible()) { 1298 UndefinedProtocol = PDecl; 1299 return true; 1300 } 1301 1302 for (auto *PI : PDecl->protocols()) 1303 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) { 1304 UndefinedProtocol = PI; 1305 return true; 1306 } 1307 return false; 1308 } 1309 1310 /// FindProtocolDeclaration - This routine looks up protocols and 1311 /// issues an error if they are not declared. It returns list of 1312 /// protocol declarations in its 'Protocols' argument. 1313 void 1314 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 1315 ArrayRef<IdentifierLocPair> ProtocolId, 1316 SmallVectorImpl<Decl *> &Protocols) { 1317 for (const IdentifierLocPair &Pair : ProtocolId) { 1318 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second); 1319 if (!PDecl) { 1320 DeclFilterCCC<ObjCProtocolDecl> CCC{}; 1321 TypoCorrection Corrected = CorrectTypo( 1322 DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName, 1323 TUScope, nullptr, CCC, CTK_ErrorRecovery); 1324 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) 1325 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest) 1326 << Pair.first); 1327 } 1328 1329 if (!PDecl) { 1330 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first; 1331 continue; 1332 } 1333 // If this is a forward protocol declaration, get its definition. 1334 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) 1335 PDecl = PDecl->getDefinition(); 1336 1337 // For an objc container, delay protocol reference checking until after we 1338 // can set the objc decl as the availability context, otherwise check now. 1339 if (!ForObjCContainer) { 1340 (void)DiagnoseUseOfDecl(PDecl, Pair.second); 1341 } 1342 1343 // If this is a forward declaration and we are supposed to warn in this 1344 // case, do it. 1345 // FIXME: Recover nicely in the hidden case. 1346 ObjCProtocolDecl *UndefinedProtocol; 1347 1348 if (WarnOnDeclarations && 1349 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) { 1350 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first; 1351 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined) 1352 << UndefinedProtocol; 1353 } 1354 Protocols.push_back(PDecl); 1355 } 1356 } 1357 1358 namespace { 1359 // Callback to only accept typo corrections that are either 1360 // Objective-C protocols or valid Objective-C type arguments. 1361 class ObjCTypeArgOrProtocolValidatorCCC final 1362 : public CorrectionCandidateCallback { 1363 ASTContext &Context; 1364 Sema::LookupNameKind LookupKind; 1365 public: 1366 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context, 1367 Sema::LookupNameKind lookupKind) 1368 : Context(context), LookupKind(lookupKind) { } 1369 1370 bool ValidateCandidate(const TypoCorrection &candidate) override { 1371 // If we're allowed to find protocols and we have a protocol, accept it. 1372 if (LookupKind != Sema::LookupOrdinaryName) { 1373 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>()) 1374 return true; 1375 } 1376 1377 // If we're allowed to find type names and we have one, accept it. 1378 if (LookupKind != Sema::LookupObjCProtocolName) { 1379 // If we have a type declaration, we might accept this result. 1380 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) { 1381 // If we found a tag declaration outside of C++, skip it. This 1382 // can happy because we look for any name when there is no 1383 // bias to protocol or type names. 1384 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus) 1385 return false; 1386 1387 // Make sure the type is something we would accept as a type 1388 // argument. 1389 auto type = Context.getTypeDeclType(typeDecl); 1390 if (type->isObjCObjectPointerType() || 1391 type->isBlockPointerType() || 1392 type->isDependentType() || 1393 type->isObjCObjectType()) 1394 return true; 1395 1396 return false; 1397 } 1398 1399 // If we have an Objective-C class type, accept it; there will 1400 // be another fix to add the '*'. 1401 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>()) 1402 return true; 1403 1404 return false; 1405 } 1406 1407 return false; 1408 } 1409 1410 std::unique_ptr<CorrectionCandidateCallback> clone() override { 1411 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this); 1412 } 1413 }; 1414 } // end anonymous namespace 1415 1416 void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, 1417 SourceLocation ProtocolLoc, 1418 IdentifierInfo *TypeArgId, 1419 SourceLocation TypeArgLoc, 1420 bool SelectProtocolFirst) { 1421 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols) 1422 << SelectProtocolFirst << TypeArgId << ProtocolId 1423 << SourceRange(ProtocolLoc); 1424 } 1425 1426 void Sema::actOnObjCTypeArgsOrProtocolQualifiers( 1427 Scope *S, 1428 ParsedType baseType, 1429 SourceLocation lAngleLoc, 1430 ArrayRef<IdentifierInfo *> identifiers, 1431 ArrayRef<SourceLocation> identifierLocs, 1432 SourceLocation rAngleLoc, 1433 SourceLocation &typeArgsLAngleLoc, 1434 SmallVectorImpl<ParsedType> &typeArgs, 1435 SourceLocation &typeArgsRAngleLoc, 1436 SourceLocation &protocolLAngleLoc, 1437 SmallVectorImpl<Decl *> &protocols, 1438 SourceLocation &protocolRAngleLoc, 1439 bool warnOnIncompleteProtocols) { 1440 // Local function that updates the declaration specifiers with 1441 // protocol information. 1442 unsigned numProtocolsResolved = 0; 1443 auto resolvedAsProtocols = [&] { 1444 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols"); 1445 1446 // Determine whether the base type is a parameterized class, in 1447 // which case we want to warn about typos such as 1448 // "NSArray<NSObject>" (that should be NSArray<NSObject *>). 1449 ObjCInterfaceDecl *baseClass = nullptr; 1450 QualType base = GetTypeFromParser(baseType, nullptr); 1451 bool allAreTypeNames = false; 1452 SourceLocation firstClassNameLoc; 1453 if (!base.isNull()) { 1454 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) { 1455 baseClass = objcObjectType->getInterface(); 1456 if (baseClass) { 1457 if (auto typeParams = baseClass->getTypeParamList()) { 1458 if (typeParams->size() == numProtocolsResolved) { 1459 // Note that we should be looking for type names, too. 1460 allAreTypeNames = true; 1461 } 1462 } 1463 } 1464 } 1465 } 1466 1467 for (unsigned i = 0, n = protocols.size(); i != n; ++i) { 1468 ObjCProtocolDecl *&proto 1469 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]); 1470 // For an objc container, delay protocol reference checking until after we 1471 // can set the objc decl as the availability context, otherwise check now. 1472 if (!warnOnIncompleteProtocols) { 1473 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]); 1474 } 1475 1476 // If this is a forward protocol declaration, get its definition. 1477 if (!proto->isThisDeclarationADefinition() && proto->getDefinition()) 1478 proto = proto->getDefinition(); 1479 1480 // If this is a forward declaration and we are supposed to warn in this 1481 // case, do it. 1482 // FIXME: Recover nicely in the hidden case. 1483 ObjCProtocolDecl *forwardDecl = nullptr; 1484 if (warnOnIncompleteProtocols && 1485 NestedProtocolHasNoDefinition(proto, forwardDecl)) { 1486 Diag(identifierLocs[i], diag::warn_undef_protocolref) 1487 << proto->getDeclName(); 1488 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined) 1489 << forwardDecl; 1490 } 1491 1492 // If everything this far has been a type name (and we care 1493 // about such things), check whether this name refers to a type 1494 // as well. 1495 if (allAreTypeNames) { 1496 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1497 LookupOrdinaryName)) { 1498 if (isa<ObjCInterfaceDecl>(decl)) { 1499 if (firstClassNameLoc.isInvalid()) 1500 firstClassNameLoc = identifierLocs[i]; 1501 } else if (!isa<TypeDecl>(decl)) { 1502 // Not a type. 1503 allAreTypeNames = false; 1504 } 1505 } else { 1506 allAreTypeNames = false; 1507 } 1508 } 1509 } 1510 1511 // All of the protocols listed also have type names, and at least 1512 // one is an Objective-C class name. Check whether all of the 1513 // protocol conformances are declared by the base class itself, in 1514 // which case we warn. 1515 if (allAreTypeNames && firstClassNameLoc.isValid()) { 1516 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols; 1517 Context.CollectInheritedProtocols(baseClass, knownProtocols); 1518 bool allProtocolsDeclared = true; 1519 for (auto *proto : protocols) { 1520 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) { 1521 allProtocolsDeclared = false; 1522 break; 1523 } 1524 } 1525 1526 if (allProtocolsDeclared) { 1527 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type) 1528 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc) 1529 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc), 1530 " *"); 1531 } 1532 } 1533 1534 protocolLAngleLoc = lAngleLoc; 1535 protocolRAngleLoc = rAngleLoc; 1536 assert(protocols.size() == identifierLocs.size()); 1537 }; 1538 1539 // Attempt to resolve all of the identifiers as protocols. 1540 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1541 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]); 1542 protocols.push_back(proto); 1543 if (proto) 1544 ++numProtocolsResolved; 1545 } 1546 1547 // If all of the names were protocols, these were protocol qualifiers. 1548 if (numProtocolsResolved == identifiers.size()) 1549 return resolvedAsProtocols(); 1550 1551 // Attempt to resolve all of the identifiers as type names or 1552 // Objective-C class names. The latter is technically ill-formed, 1553 // but is probably something like \c NSArray<NSView *> missing the 1554 // \c*. 1555 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl; 1556 SmallVector<TypeOrClassDecl, 4> typeDecls; 1557 unsigned numTypeDeclsResolved = 0; 1558 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1559 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1560 LookupOrdinaryName); 1561 if (!decl) { 1562 typeDecls.push_back(TypeOrClassDecl()); 1563 continue; 1564 } 1565 1566 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) { 1567 typeDecls.push_back(typeDecl); 1568 ++numTypeDeclsResolved; 1569 continue; 1570 } 1571 1572 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) { 1573 typeDecls.push_back(objcClass); 1574 ++numTypeDeclsResolved; 1575 continue; 1576 } 1577 1578 typeDecls.push_back(TypeOrClassDecl()); 1579 } 1580 1581 AttributeFactory attrFactory; 1582 1583 // Local function that forms a reference to the given type or 1584 // Objective-C class declaration. 1585 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) 1586 -> TypeResult { 1587 // Form declaration specifiers. They simply refer to the type. 1588 DeclSpec DS(attrFactory); 1589 const char* prevSpec; // unused 1590 unsigned diagID; // unused 1591 QualType type; 1592 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>()) 1593 type = Context.getTypeDeclType(actualTypeDecl); 1594 else 1595 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>()); 1596 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc); 1597 ParsedType parsedType = CreateParsedType(type, parsedTSInfo); 1598 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID, 1599 parsedType, Context.getPrintingPolicy()); 1600 // Use the identifier location for the type source range. 1601 DS.SetRangeStart(loc); 1602 DS.SetRangeEnd(loc); 1603 1604 // Form the declarator. 1605 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); 1606 1607 // If we have a typedef of an Objective-C class type that is missing a '*', 1608 // add the '*'. 1609 if (type->getAs<ObjCInterfaceType>()) { 1610 SourceLocation starLoc = getLocForEndOfToken(loc); 1611 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc, 1612 SourceLocation(), 1613 SourceLocation(), 1614 SourceLocation(), 1615 SourceLocation(), 1616 SourceLocation()), 1617 starLoc); 1618 1619 // Diagnose the missing '*'. 1620 Diag(loc, diag::err_objc_type_arg_missing_star) 1621 << type 1622 << FixItHint::CreateInsertion(starLoc, " *"); 1623 } 1624 1625 // Convert this to a type. 1626 return ActOnTypeName(S, D); 1627 }; 1628 1629 // Local function that updates the declaration specifiers with 1630 // type argument information. 1631 auto resolvedAsTypeDecls = [&] { 1632 // We did not resolve these as protocols. 1633 protocols.clear(); 1634 1635 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl"); 1636 // Map type declarations to type arguments. 1637 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1638 // Map type reference to a type. 1639 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]); 1640 if (!type.isUsable()) { 1641 typeArgs.clear(); 1642 return; 1643 } 1644 1645 typeArgs.push_back(type.get()); 1646 } 1647 1648 typeArgsLAngleLoc = lAngleLoc; 1649 typeArgsRAngleLoc = rAngleLoc; 1650 }; 1651 1652 // If all of the identifiers can be resolved as type names or 1653 // Objective-C class names, we have type arguments. 1654 if (numTypeDeclsResolved == identifiers.size()) 1655 return resolvedAsTypeDecls(); 1656 1657 // Error recovery: some names weren't found, or we have a mix of 1658 // type and protocol names. Go resolve all of the unresolved names 1659 // and complain if we can't find a consistent answer. 1660 LookupNameKind lookupKind = LookupAnyName; 1661 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1662 // If we already have a protocol or type. Check whether it is the 1663 // right thing. 1664 if (protocols[i] || typeDecls[i]) { 1665 // If we haven't figured out whether we want types or protocols 1666 // yet, try to figure it out from this name. 1667 if (lookupKind == LookupAnyName) { 1668 // If this name refers to both a protocol and a type (e.g., \c 1669 // NSObject), don't conclude anything yet. 1670 if (protocols[i] && typeDecls[i]) 1671 continue; 1672 1673 // Otherwise, let this name decide whether we'll be correcting 1674 // toward types or protocols. 1675 lookupKind = protocols[i] ? LookupObjCProtocolName 1676 : LookupOrdinaryName; 1677 continue; 1678 } 1679 1680 // If we want protocols and we have a protocol, there's nothing 1681 // more to do. 1682 if (lookupKind == LookupObjCProtocolName && protocols[i]) 1683 continue; 1684 1685 // If we want types and we have a type declaration, there's 1686 // nothing more to do. 1687 if (lookupKind == LookupOrdinaryName && typeDecls[i]) 1688 continue; 1689 1690 // We have a conflict: some names refer to protocols and others 1691 // refer to types. 1692 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0], 1693 identifiers[i], identifierLocs[i], 1694 protocols[i] != nullptr); 1695 1696 protocols.clear(); 1697 typeArgs.clear(); 1698 return; 1699 } 1700 1701 // Perform typo correction on the name. 1702 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind); 1703 TypoCorrection corrected = 1704 CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]), 1705 lookupKind, S, nullptr, CCC, CTK_ErrorRecovery); 1706 if (corrected) { 1707 // Did we find a protocol? 1708 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) { 1709 diagnoseTypo(corrected, 1710 PDiag(diag::err_undeclared_protocol_suggest) 1711 << identifiers[i]); 1712 lookupKind = LookupObjCProtocolName; 1713 protocols[i] = proto; 1714 ++numProtocolsResolved; 1715 continue; 1716 } 1717 1718 // Did we find a type? 1719 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) { 1720 diagnoseTypo(corrected, 1721 PDiag(diag::err_unknown_typename_suggest) 1722 << identifiers[i]); 1723 lookupKind = LookupOrdinaryName; 1724 typeDecls[i] = typeDecl; 1725 ++numTypeDeclsResolved; 1726 continue; 1727 } 1728 1729 // Did we find an Objective-C class? 1730 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1731 diagnoseTypo(corrected, 1732 PDiag(diag::err_unknown_type_or_class_name_suggest) 1733 << identifiers[i] << true); 1734 lookupKind = LookupOrdinaryName; 1735 typeDecls[i] = objcClass; 1736 ++numTypeDeclsResolved; 1737 continue; 1738 } 1739 } 1740 1741 // We couldn't find anything. 1742 Diag(identifierLocs[i], 1743 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing 1744 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol 1745 : diag::err_unknown_typename)) 1746 << identifiers[i]; 1747 protocols.clear(); 1748 typeArgs.clear(); 1749 return; 1750 } 1751 1752 // If all of the names were (corrected to) protocols, these were 1753 // protocol qualifiers. 1754 if (numProtocolsResolved == identifiers.size()) 1755 return resolvedAsProtocols(); 1756 1757 // Otherwise, all of the names were (corrected to) types. 1758 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?"); 1759 return resolvedAsTypeDecls(); 1760 } 1761 1762 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 1763 /// a class method in its extension. 1764 /// 1765 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 1766 ObjCInterfaceDecl *ID) { 1767 if (!ID) 1768 return; // Possibly due to previous error 1769 1770 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 1771 for (auto *MD : ID->methods()) 1772 MethodMap[MD->getSelector()] = MD; 1773 1774 if (MethodMap.empty()) 1775 return; 1776 for (const auto *Method : CAT->methods()) { 1777 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 1778 if (PrevMethod && 1779 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) && 1780 !MatchTwoMethodDeclarations(Method, PrevMethod)) { 1781 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 1782 << Method->getDeclName(); 1783 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 1784 } 1785 } 1786 } 1787 1788 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo; 1789 Sema::DeclGroupPtrTy 1790 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 1791 ArrayRef<IdentifierLocPair> IdentList, 1792 const ParsedAttributesView &attrList) { 1793 SmallVector<Decl *, 8> DeclsInGroup; 1794 for (const IdentifierLocPair &IdentPair : IdentList) { 1795 IdentifierInfo *Ident = IdentPair.first; 1796 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second, 1797 forRedeclarationInCurContext()); 1798 ObjCProtocolDecl *PDecl 1799 = ObjCProtocolDecl::Create(Context, CurContext, Ident, 1800 IdentPair.second, AtProtocolLoc, 1801 PrevDecl); 1802 1803 PushOnScopeChains(PDecl, TUScope); 1804 CheckObjCDeclScope(PDecl); 1805 1806 ProcessDeclAttributeList(TUScope, PDecl, attrList); 1807 AddPragmaAttributes(TUScope, PDecl); 1808 1809 if (PrevDecl) 1810 mergeDeclAttributes(PDecl, PrevDecl); 1811 1812 DeclsInGroup.push_back(PDecl); 1813 } 1814 1815 return BuildDeclaratorGroup(DeclsInGroup); 1816 } 1817 1818 ObjCCategoryDecl *Sema::ActOnStartCategoryInterface( 1819 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 1820 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 1821 IdentifierInfo *CategoryName, SourceLocation CategoryLoc, 1822 Decl *const *ProtoRefs, unsigned NumProtoRefs, 1823 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 1824 const ParsedAttributesView &AttrList) { 1825 ObjCCategoryDecl *CDecl; 1826 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1827 1828 /// Check that class of this category is already completely declared. 1829 1830 if (!IDecl 1831 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1832 diag::err_category_forward_interface, 1833 CategoryName == nullptr)) { 1834 // Create an invalid ObjCCategoryDecl to serve as context for 1835 // the enclosing method declarations. We mark the decl invalid 1836 // to make it clear that this isn't a valid AST. 1837 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1838 ClassLoc, CategoryLoc, CategoryName, 1839 IDecl, typeParamList); 1840 CDecl->setInvalidDecl(); 1841 CurContext->addDecl(CDecl); 1842 1843 if (!IDecl) 1844 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1845 ActOnObjCContainerStartDefinition(CDecl); 1846 return CDecl; 1847 } 1848 1849 if (!CategoryName && IDecl->getImplementation()) { 1850 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 1851 Diag(IDecl->getImplementation()->getLocation(), 1852 diag::note_implementation_declared); 1853 } 1854 1855 if (CategoryName) { 1856 /// Check for duplicate interface declaration for this category 1857 if (ObjCCategoryDecl *Previous 1858 = IDecl->FindCategoryDeclaration(CategoryName)) { 1859 // Class extensions can be declared multiple times, categories cannot. 1860 Diag(CategoryLoc, diag::warn_dup_category_def) 1861 << ClassName << CategoryName; 1862 Diag(Previous->getLocation(), diag::note_previous_definition); 1863 } 1864 } 1865 1866 // If we have a type parameter list, check it. 1867 if (typeParamList) { 1868 if (auto prevTypeParamList = IDecl->getTypeParamList()) { 1869 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList, 1870 CategoryName 1871 ? TypeParamListContext::Category 1872 : TypeParamListContext::Extension)) 1873 typeParamList = nullptr; 1874 } else { 1875 Diag(typeParamList->getLAngleLoc(), 1876 diag::err_objc_parameterized_category_nonclass) 1877 << (CategoryName != nullptr) 1878 << ClassName 1879 << typeParamList->getSourceRange(); 1880 1881 typeParamList = nullptr; 1882 } 1883 } 1884 1885 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1886 ClassLoc, CategoryLoc, CategoryName, IDecl, 1887 typeParamList); 1888 // FIXME: PushOnScopeChains? 1889 CurContext->addDecl(CDecl); 1890 1891 // Process the attributes before looking at protocols to ensure that the 1892 // availability attribute is attached to the category to provide availability 1893 // checking for protocol uses. 1894 ProcessDeclAttributeList(TUScope, CDecl, AttrList); 1895 AddPragmaAttributes(TUScope, CDecl); 1896 1897 if (NumProtoRefs) { 1898 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1899 NumProtoRefs, ProtoLocs); 1900 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1901 ProtoLocs, Context); 1902 // Protocols in the class extension belong to the class. 1903 if (CDecl->IsClassExtension()) 1904 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 1905 NumProtoRefs, Context); 1906 } 1907 1908 CheckObjCDeclScope(CDecl); 1909 ActOnObjCContainerStartDefinition(CDecl); 1910 return CDecl; 1911 } 1912 1913 /// ActOnStartCategoryImplementation - Perform semantic checks on the 1914 /// category implementation declaration and build an ObjCCategoryImplDecl 1915 /// object. 1916 ObjCCategoryImplDecl *Sema::ActOnStartCategoryImplementation( 1917 SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, 1918 SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, 1919 const ParsedAttributesView &Attrs) { 1920 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1921 ObjCCategoryDecl *CatIDecl = nullptr; 1922 if (IDecl && IDecl->hasDefinition()) { 1923 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 1924 if (!CatIDecl) { 1925 // Category @implementation with no corresponding @interface. 1926 // Create and install one. 1927 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc, 1928 ClassLoc, CatLoc, 1929 CatName, IDecl, 1930 /*typeParamList=*/nullptr); 1931 CatIDecl->setImplicit(); 1932 } 1933 } 1934 1935 ObjCCategoryImplDecl *CDecl = 1936 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl, 1937 ClassLoc, AtCatImplLoc, CatLoc); 1938 /// Check that class of this category is already completely declared. 1939 if (!IDecl) { 1940 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1941 CDecl->setInvalidDecl(); 1942 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1943 diag::err_undef_interface)) { 1944 CDecl->setInvalidDecl(); 1945 } 1946 1947 ProcessDeclAttributeList(TUScope, CDecl, Attrs); 1948 AddPragmaAttributes(TUScope, CDecl); 1949 1950 // FIXME: PushOnScopeChains? 1951 CurContext->addDecl(CDecl); 1952 1953 // If the interface has the objc_runtime_visible attribute, we 1954 // cannot implement a category for it. 1955 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) { 1956 Diag(ClassLoc, diag::err_objc_runtime_visible_category) 1957 << IDecl->getDeclName(); 1958 } 1959 1960 /// Check that CatName, category name, is not used in another implementation. 1961 if (CatIDecl) { 1962 if (CatIDecl->getImplementation()) { 1963 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 1964 << CatName; 1965 Diag(CatIDecl->getImplementation()->getLocation(), 1966 diag::note_previous_definition); 1967 CDecl->setInvalidDecl(); 1968 } else { 1969 CatIDecl->setImplementation(CDecl); 1970 // Warn on implementating category of deprecated class under 1971 // -Wdeprecated-implementations flag. 1972 DiagnoseObjCImplementedDeprecations(*this, CatIDecl, 1973 CDecl->getLocation()); 1974 } 1975 } 1976 1977 CheckObjCDeclScope(CDecl); 1978 ActOnObjCContainerStartDefinition(CDecl); 1979 return CDecl; 1980 } 1981 1982 ObjCImplementationDecl *Sema::ActOnStartClassImplementation( 1983 SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, 1984 SourceLocation ClassLoc, IdentifierInfo *SuperClassname, 1985 SourceLocation SuperClassLoc, const ParsedAttributesView &Attrs) { 1986 ObjCInterfaceDecl *IDecl = nullptr; 1987 // Check for another declaration kind with the same name. 1988 NamedDecl *PrevDecl 1989 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 1990 forRedeclarationInCurContext()); 1991 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1992 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 1993 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1994 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 1995 // FIXME: This will produce an error if the definition of the interface has 1996 // been imported from a module but is not visible. 1997 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1998 diag::warn_undef_interface); 1999 } else { 2000 // We did not find anything with the name ClassName; try to correct for 2001 // typos in the class name. 2002 ObjCInterfaceValidatorCCC CCC{}; 2003 TypoCorrection Corrected = 2004 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc), 2005 LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError); 2006 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 2007 // Suggest the (potentially) correct interface name. Don't provide a 2008 // code-modification hint or use the typo name for recovery, because 2009 // this is just a warning. The program may actually be correct. 2010 diagnoseTypo(Corrected, 2011 PDiag(diag::warn_undef_interface_suggest) << ClassName, 2012 /*ErrorRecovery*/false); 2013 } else { 2014 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 2015 } 2016 } 2017 2018 // Check that super class name is valid class name 2019 ObjCInterfaceDecl *SDecl = nullptr; 2020 if (SuperClassname) { 2021 // Check if a different kind of symbol declared in this scope. 2022 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 2023 LookupOrdinaryName); 2024 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2025 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 2026 << SuperClassname; 2027 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2028 } else { 2029 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2030 if (SDecl && !SDecl->hasDefinition()) 2031 SDecl = nullptr; 2032 if (!SDecl) 2033 Diag(SuperClassLoc, diag::err_undef_superclass) 2034 << SuperClassname << ClassName; 2035 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) { 2036 // This implementation and its interface do not have the same 2037 // super class. 2038 Diag(SuperClassLoc, diag::err_conflicting_super_class) 2039 << SDecl->getDeclName(); 2040 Diag(SDecl->getLocation(), diag::note_previous_definition); 2041 } 2042 } 2043 } 2044 2045 if (!IDecl) { 2046 // Legacy case of @implementation with no corresponding @interface. 2047 // Build, chain & install the interface decl into the identifier. 2048 2049 // FIXME: Do we support attributes on the @implementation? If so we should 2050 // copy them over. 2051 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 2052 ClassName, /*typeParamList=*/nullptr, 2053 /*PrevDecl=*/nullptr, ClassLoc, 2054 true); 2055 AddPragmaAttributes(TUScope, IDecl); 2056 IDecl->startDefinition(); 2057 if (SDecl) { 2058 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo( 2059 Context.getObjCInterfaceType(SDecl), 2060 SuperClassLoc)); 2061 IDecl->setEndOfDefinitionLoc(SuperClassLoc); 2062 } else { 2063 IDecl->setEndOfDefinitionLoc(ClassLoc); 2064 } 2065 2066 PushOnScopeChains(IDecl, TUScope); 2067 } else { 2068 // Mark the interface as being completed, even if it was just as 2069 // @class ....; 2070 // declaration; the user cannot reopen it. 2071 if (!IDecl->hasDefinition()) 2072 IDecl->startDefinition(); 2073 } 2074 2075 ObjCImplementationDecl* IMPDecl = 2076 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl, 2077 ClassLoc, AtClassImplLoc, SuperClassLoc); 2078 2079 ProcessDeclAttributeList(TUScope, IMPDecl, Attrs); 2080 AddPragmaAttributes(TUScope, IMPDecl); 2081 2082 if (CheckObjCDeclScope(IMPDecl)) { 2083 ActOnObjCContainerStartDefinition(IMPDecl); 2084 return IMPDecl; 2085 } 2086 2087 // Check that there is no duplicate implementation of this class. 2088 if (IDecl->getImplementation()) { 2089 // FIXME: Don't leak everything! 2090 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 2091 Diag(IDecl->getImplementation()->getLocation(), 2092 diag::note_previous_definition); 2093 IMPDecl->setInvalidDecl(); 2094 } else { // add it to the list. 2095 IDecl->setImplementation(IMPDecl); 2096 PushOnScopeChains(IMPDecl, TUScope); 2097 // Warn on implementating deprecated class under 2098 // -Wdeprecated-implementations flag. 2099 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation()); 2100 } 2101 2102 // If the superclass has the objc_runtime_visible attribute, we 2103 // cannot implement a subclass of it. 2104 if (IDecl->getSuperClass() && 2105 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) { 2106 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass) 2107 << IDecl->getDeclName() 2108 << IDecl->getSuperClass()->getDeclName(); 2109 } 2110 2111 ActOnObjCContainerStartDefinition(IMPDecl); 2112 return IMPDecl; 2113 } 2114 2115 Sema::DeclGroupPtrTy 2116 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) { 2117 SmallVector<Decl *, 64> DeclsInGroup; 2118 DeclsInGroup.reserve(Decls.size() + 1); 2119 2120 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 2121 Decl *Dcl = Decls[i]; 2122 if (!Dcl) 2123 continue; 2124 if (Dcl->getDeclContext()->isFileContext()) 2125 Dcl->setTopLevelDeclInObjCContainer(); 2126 DeclsInGroup.push_back(Dcl); 2127 } 2128 2129 DeclsInGroup.push_back(ObjCImpDecl); 2130 2131 return BuildDeclaratorGroup(DeclsInGroup); 2132 } 2133 2134 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2135 ObjCIvarDecl **ivars, unsigned numIvars, 2136 SourceLocation RBrace) { 2137 assert(ImpDecl && "missing implementation decl"); 2138 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 2139 if (!IDecl) 2140 return; 2141 /// Check case of non-existing \@interface decl. 2142 /// (legacy objective-c \@implementation decl without an \@interface decl). 2143 /// Add implementations's ivar to the synthesize class's ivar list. 2144 if (IDecl->isImplicitInterfaceDecl()) { 2145 IDecl->setEndOfDefinitionLoc(RBrace); 2146 // Add ivar's to class's DeclContext. 2147 for (unsigned i = 0, e = numIvars; i != e; ++i) { 2148 ivars[i]->setLexicalDeclContext(ImpDecl); 2149 // In a 'fragile' runtime the ivar was added to the implicit 2150 // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is 2151 // only in the ObjCImplementationDecl. In the non-fragile case the ivar 2152 // therefore also needs to be propagated to the ObjCInterfaceDecl. 2153 if (!LangOpts.ObjCRuntime.isFragile()) 2154 IDecl->makeDeclVisibleInContext(ivars[i]); 2155 ImpDecl->addDecl(ivars[i]); 2156 } 2157 2158 return; 2159 } 2160 // If implementation has empty ivar list, just return. 2161 if (numIvars == 0) 2162 return; 2163 2164 assert(ivars && "missing @implementation ivars"); 2165 if (LangOpts.ObjCRuntime.isNonFragile()) { 2166 if (ImpDecl->getSuperClass()) 2167 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 2168 for (unsigned i = 0; i < numIvars; i++) { 2169 ObjCIvarDecl* ImplIvar = ivars[i]; 2170 if (const ObjCIvarDecl *ClsIvar = 2171 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2172 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2173 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2174 continue; 2175 } 2176 // Check class extensions (unnamed categories) for duplicate ivars. 2177 for (const auto *CDecl : IDecl->visible_extensions()) { 2178 if (const ObjCIvarDecl *ClsExtIvar = 2179 CDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2180 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2181 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 2182 continue; 2183 } 2184 } 2185 // Instance ivar to Implementation's DeclContext. 2186 ImplIvar->setLexicalDeclContext(ImpDecl); 2187 IDecl->makeDeclVisibleInContext(ImplIvar); 2188 ImpDecl->addDecl(ImplIvar); 2189 } 2190 return; 2191 } 2192 // Check interface's Ivar list against those in the implementation. 2193 // names and types must match. 2194 // 2195 unsigned j = 0; 2196 ObjCInterfaceDecl::ivar_iterator 2197 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 2198 for (; numIvars > 0 && IVI != IVE; ++IVI) { 2199 ObjCIvarDecl* ImplIvar = ivars[j++]; 2200 ObjCIvarDecl* ClsIvar = *IVI; 2201 assert (ImplIvar && "missing implementation ivar"); 2202 assert (ClsIvar && "missing class ivar"); 2203 2204 // First, make sure the types match. 2205 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) { 2206 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 2207 << ImplIvar->getIdentifier() 2208 << ImplIvar->getType() << ClsIvar->getType(); 2209 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2210 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() && 2211 ImplIvar->getBitWidthValue(Context) != 2212 ClsIvar->getBitWidthValue(Context)) { 2213 Diag(ImplIvar->getBitWidth()->getBeginLoc(), 2214 diag::err_conflicting_ivar_bitwidth) 2215 << ImplIvar->getIdentifier(); 2216 Diag(ClsIvar->getBitWidth()->getBeginLoc(), 2217 diag::note_previous_definition); 2218 } 2219 // Make sure the names are identical. 2220 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 2221 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 2222 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 2223 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2224 } 2225 --numIvars; 2226 } 2227 2228 if (numIvars > 0) 2229 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count); 2230 else if (IVI != IVE) 2231 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count); 2232 } 2233 2234 static void WarnUndefinedMethod(Sema &S, ObjCImplDecl *Impl, 2235 ObjCMethodDecl *method, bool &IncompleteImpl, 2236 unsigned DiagID, 2237 NamedDecl *NeededFor = nullptr) { 2238 // No point warning no definition of method which is 'unavailable'. 2239 if (method->getAvailability() == AR_Unavailable) 2240 return; 2241 2242 // FIXME: For now ignore 'IncompleteImpl'. 2243 // Previously we grouped all unimplemented methods under a single 2244 // warning, but some users strongly voiced that they would prefer 2245 // separate warnings. We will give that approach a try, as that 2246 // matches what we do with protocols. 2247 { 2248 const Sema::SemaDiagnosticBuilder &B = S.Diag(Impl->getLocation(), DiagID); 2249 B << method; 2250 if (NeededFor) 2251 B << NeededFor; 2252 2253 // Add an empty definition at the end of the @implementation. 2254 std::string FixItStr; 2255 llvm::raw_string_ostream Out(FixItStr); 2256 method->print(Out, Impl->getASTContext().getPrintingPolicy()); 2257 Out << " {\n}\n\n"; 2258 2259 SourceLocation Loc = Impl->getAtEndRange().getBegin(); 2260 B << FixItHint::CreateInsertion(Loc, FixItStr); 2261 } 2262 2263 // Issue a note to the original declaration. 2264 SourceLocation MethodLoc = method->getBeginLoc(); 2265 if (MethodLoc.isValid()) 2266 S.Diag(MethodLoc, diag::note_method_declared_at) << method; 2267 } 2268 2269 /// Determines if type B can be substituted for type A. Returns true if we can 2270 /// guarantee that anything that the user will do to an object of type A can 2271 /// also be done to an object of type B. This is trivially true if the two 2272 /// types are the same, or if B is a subclass of A. It becomes more complex 2273 /// in cases where protocols are involved. 2274 /// 2275 /// Object types in Objective-C describe the minimum requirements for an 2276 /// object, rather than providing a complete description of a type. For 2277 /// example, if A is a subclass of B, then B* may refer to an instance of A. 2278 /// The principle of substitutability means that we may use an instance of A 2279 /// anywhere that we may use an instance of B - it will implement all of the 2280 /// ivars of B and all of the methods of B. 2281 /// 2282 /// This substitutability is important when type checking methods, because 2283 /// the implementation may have stricter type definitions than the interface. 2284 /// The interface specifies minimum requirements, but the implementation may 2285 /// have more accurate ones. For example, a method may privately accept 2286 /// instances of B, but only publish that it accepts instances of A. Any 2287 /// object passed to it will be type checked against B, and so will implicitly 2288 /// by a valid A*. Similarly, a method may return a subclass of the class that 2289 /// it is declared as returning. 2290 /// 2291 /// This is most important when considering subclassing. A method in a 2292 /// subclass must accept any object as an argument that its superclass's 2293 /// implementation accepts. It may, however, accept a more general type 2294 /// without breaking substitutability (i.e. you can still use the subclass 2295 /// anywhere that you can use the superclass, but not vice versa). The 2296 /// converse requirement applies to return types: the return type for a 2297 /// subclass method must be a valid object of the kind that the superclass 2298 /// advertises, but it may be specified more accurately. This avoids the need 2299 /// for explicit down-casting by callers. 2300 /// 2301 /// Note: This is a stricter requirement than for assignment. 2302 static bool isObjCTypeSubstitutable(ASTContext &Context, 2303 const ObjCObjectPointerType *A, 2304 const ObjCObjectPointerType *B, 2305 bool rejectId) { 2306 // Reject a protocol-unqualified id. 2307 if (rejectId && B->isObjCIdType()) return false; 2308 2309 // If B is a qualified id, then A must also be a qualified id and it must 2310 // implement all of the protocols in B. It may not be a qualified class. 2311 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 2312 // stricter definition so it is not substitutable for id<A>. 2313 if (B->isObjCQualifiedIdType()) { 2314 return A->isObjCQualifiedIdType() && 2315 Context.ObjCQualifiedIdTypesAreCompatible(A, B, false); 2316 } 2317 2318 /* 2319 // id is a special type that bypasses type checking completely. We want a 2320 // warning when it is used in one place but not another. 2321 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 2322 2323 2324 // If B is a qualified id, then A must also be a qualified id (which it isn't 2325 // if we've got this far) 2326 if (B->isObjCQualifiedIdType()) return false; 2327 */ 2328 2329 // Now we know that A and B are (potentially-qualified) class types. The 2330 // normal rules for assignment apply. 2331 return Context.canAssignObjCInterfaces(A, B); 2332 } 2333 2334 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 2335 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 2336 } 2337 2338 /// Determine whether two set of Objective-C declaration qualifiers conflict. 2339 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x, 2340 Decl::ObjCDeclQualifier y) { 2341 return (x & ~Decl::OBJC_TQ_CSNullability) != 2342 (y & ~Decl::OBJC_TQ_CSNullability); 2343 } 2344 2345 static bool CheckMethodOverrideReturn(Sema &S, 2346 ObjCMethodDecl *MethodImpl, 2347 ObjCMethodDecl *MethodDecl, 2348 bool IsProtocolMethodDecl, 2349 bool IsOverridingMode, 2350 bool Warn) { 2351 if (IsProtocolMethodDecl && 2352 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(), 2353 MethodImpl->getObjCDeclQualifier())) { 2354 if (Warn) { 2355 S.Diag(MethodImpl->getLocation(), 2356 (IsOverridingMode 2357 ? diag::warn_conflicting_overriding_ret_type_modifiers 2358 : diag::warn_conflicting_ret_type_modifiers)) 2359 << MethodImpl->getDeclName() 2360 << MethodImpl->getReturnTypeSourceRange(); 2361 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 2362 << MethodDecl->getReturnTypeSourceRange(); 2363 } 2364 else 2365 return false; 2366 } 2367 if (Warn && IsOverridingMode && 2368 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2369 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(), 2370 MethodDecl->getReturnType(), 2371 false)) { 2372 auto nullabilityMethodImpl = *MethodImpl->getReturnType()->getNullability(); 2373 auto nullabilityMethodDecl = *MethodDecl->getReturnType()->getNullability(); 2374 S.Diag(MethodImpl->getLocation(), 2375 diag::warn_conflicting_nullability_attr_overriding_ret_types) 2376 << DiagNullabilityKind(nullabilityMethodImpl, 2377 ((MethodImpl->getObjCDeclQualifier() & 2378 Decl::OBJC_TQ_CSNullability) != 0)) 2379 << DiagNullabilityKind(nullabilityMethodDecl, 2380 ((MethodDecl->getObjCDeclQualifier() & 2381 Decl::OBJC_TQ_CSNullability) != 0)); 2382 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2383 } 2384 2385 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(), 2386 MethodDecl->getReturnType())) 2387 return true; 2388 if (!Warn) 2389 return false; 2390 2391 unsigned DiagID = 2392 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 2393 : diag::warn_conflicting_ret_types; 2394 2395 // Mismatches between ObjC pointers go into a different warning 2396 // category, and sometimes they're even completely explicitly allowed. 2397 if (const ObjCObjectPointerType *ImplPtrTy = 2398 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2399 if (const ObjCObjectPointerType *IfacePtrTy = 2400 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2401 // Allow non-matching return types as long as they don't violate 2402 // the principle of substitutability. Specifically, we permit 2403 // return types that are subclasses of the declared return type, 2404 // or that are more-qualified versions of the declared type. 2405 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 2406 return false; 2407 2408 DiagID = 2409 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 2410 : diag::warn_non_covariant_ret_types; 2411 } 2412 } 2413 2414 S.Diag(MethodImpl->getLocation(), DiagID) 2415 << MethodImpl->getDeclName() << MethodDecl->getReturnType() 2416 << MethodImpl->getReturnType() 2417 << MethodImpl->getReturnTypeSourceRange(); 2418 S.Diag(MethodDecl->getLocation(), IsOverridingMode 2419 ? diag::note_previous_declaration 2420 : diag::note_previous_definition) 2421 << MethodDecl->getReturnTypeSourceRange(); 2422 return false; 2423 } 2424 2425 static bool CheckMethodOverrideParam(Sema &S, 2426 ObjCMethodDecl *MethodImpl, 2427 ObjCMethodDecl *MethodDecl, 2428 ParmVarDecl *ImplVar, 2429 ParmVarDecl *IfaceVar, 2430 bool IsProtocolMethodDecl, 2431 bool IsOverridingMode, 2432 bool Warn) { 2433 if (IsProtocolMethodDecl && 2434 objcModifiersConflict(ImplVar->getObjCDeclQualifier(), 2435 IfaceVar->getObjCDeclQualifier())) { 2436 if (Warn) { 2437 if (IsOverridingMode) 2438 S.Diag(ImplVar->getLocation(), 2439 diag::warn_conflicting_overriding_param_modifiers) 2440 << getTypeRange(ImplVar->getTypeSourceInfo()) 2441 << MethodImpl->getDeclName(); 2442 else S.Diag(ImplVar->getLocation(), 2443 diag::warn_conflicting_param_modifiers) 2444 << getTypeRange(ImplVar->getTypeSourceInfo()) 2445 << MethodImpl->getDeclName(); 2446 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 2447 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2448 } 2449 else 2450 return false; 2451 } 2452 2453 QualType ImplTy = ImplVar->getType(); 2454 QualType IfaceTy = IfaceVar->getType(); 2455 if (Warn && IsOverridingMode && 2456 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2457 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) { 2458 S.Diag(ImplVar->getLocation(), 2459 diag::warn_conflicting_nullability_attr_overriding_param_types) 2460 << DiagNullabilityKind(*ImplTy->getNullability(), 2461 ((ImplVar->getObjCDeclQualifier() & 2462 Decl::OBJC_TQ_CSNullability) != 0)) 2463 << DiagNullabilityKind(*IfaceTy->getNullability(), 2464 ((IfaceVar->getObjCDeclQualifier() & 2465 Decl::OBJC_TQ_CSNullability) != 0)); 2466 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration); 2467 } 2468 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 2469 return true; 2470 2471 if (!Warn) 2472 return false; 2473 unsigned DiagID = 2474 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 2475 : diag::warn_conflicting_param_types; 2476 2477 // Mismatches between ObjC pointers go into a different warning 2478 // category, and sometimes they're even completely explicitly allowed.. 2479 if (const ObjCObjectPointerType *ImplPtrTy = 2480 ImplTy->getAs<ObjCObjectPointerType>()) { 2481 if (const ObjCObjectPointerType *IfacePtrTy = 2482 IfaceTy->getAs<ObjCObjectPointerType>()) { 2483 // Allow non-matching argument types as long as they don't 2484 // violate the principle of substitutability. Specifically, the 2485 // implementation must accept any objects that the superclass 2486 // accepts, however it may also accept others. 2487 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 2488 return false; 2489 2490 DiagID = 2491 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 2492 : diag::warn_non_contravariant_param_types; 2493 } 2494 } 2495 2496 S.Diag(ImplVar->getLocation(), DiagID) 2497 << getTypeRange(ImplVar->getTypeSourceInfo()) 2498 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 2499 S.Diag(IfaceVar->getLocation(), 2500 (IsOverridingMode ? diag::note_previous_declaration 2501 : diag::note_previous_definition)) 2502 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2503 return false; 2504 } 2505 2506 /// In ARC, check whether the conventional meanings of the two methods 2507 /// match. If they don't, it's a hard error. 2508 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 2509 ObjCMethodDecl *decl) { 2510 ObjCMethodFamily implFamily = impl->getMethodFamily(); 2511 ObjCMethodFamily declFamily = decl->getMethodFamily(); 2512 if (implFamily == declFamily) return false; 2513 2514 // Since conventions are sorted by selector, the only possibility is 2515 // that the types differ enough to cause one selector or the other 2516 // to fall out of the family. 2517 assert(implFamily == OMF_None || declFamily == OMF_None); 2518 2519 // No further diagnostics required on invalid declarations. 2520 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 2521 2522 const ObjCMethodDecl *unmatched = impl; 2523 ObjCMethodFamily family = declFamily; 2524 unsigned errorID = diag::err_arc_lost_method_convention; 2525 unsigned noteID = diag::note_arc_lost_method_convention; 2526 if (declFamily == OMF_None) { 2527 unmatched = decl; 2528 family = implFamily; 2529 errorID = diag::err_arc_gained_method_convention; 2530 noteID = diag::note_arc_gained_method_convention; 2531 } 2532 2533 // Indexes into a %select clause in the diagnostic. 2534 enum FamilySelector { 2535 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 2536 }; 2537 FamilySelector familySelector = FamilySelector(); 2538 2539 switch (family) { 2540 case OMF_None: llvm_unreachable("logic error, no method convention"); 2541 case OMF_retain: 2542 case OMF_release: 2543 case OMF_autorelease: 2544 case OMF_dealloc: 2545 case OMF_finalize: 2546 case OMF_retainCount: 2547 case OMF_self: 2548 case OMF_initialize: 2549 case OMF_performSelector: 2550 // Mismatches for these methods don't change ownership 2551 // conventions, so we don't care. 2552 return false; 2553 2554 case OMF_init: familySelector = F_init; break; 2555 case OMF_alloc: familySelector = F_alloc; break; 2556 case OMF_copy: familySelector = F_copy; break; 2557 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 2558 case OMF_new: familySelector = F_new; break; 2559 } 2560 2561 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 2562 ReasonSelector reasonSelector; 2563 2564 // The only reason these methods don't fall within their families is 2565 // due to unusual result types. 2566 if (unmatched->getReturnType()->isObjCObjectPointerType()) { 2567 reasonSelector = R_UnrelatedReturn; 2568 } else { 2569 reasonSelector = R_NonObjectReturn; 2570 } 2571 2572 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector); 2573 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector); 2574 2575 return true; 2576 } 2577 2578 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2579 ObjCMethodDecl *MethodDecl, 2580 bool IsProtocolMethodDecl) { 2581 if (getLangOpts().ObjCAutoRefCount && 2582 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 2583 return; 2584 2585 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2586 IsProtocolMethodDecl, false, 2587 true); 2588 2589 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2590 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2591 EF = MethodDecl->param_end(); 2592 IM != EM && IF != EF; ++IM, ++IF) { 2593 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 2594 IsProtocolMethodDecl, false, true); 2595 } 2596 2597 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 2598 Diag(ImpMethodDecl->getLocation(), 2599 diag::warn_conflicting_variadic); 2600 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2601 } 2602 } 2603 2604 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2605 ObjCMethodDecl *Overridden, 2606 bool IsProtocolMethodDecl) { 2607 2608 CheckMethodOverrideReturn(*this, Method, Overridden, 2609 IsProtocolMethodDecl, true, 2610 true); 2611 2612 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 2613 IF = Overridden->param_begin(), EM = Method->param_end(), 2614 EF = Overridden->param_end(); 2615 IM != EM && IF != EF; ++IM, ++IF) { 2616 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 2617 IsProtocolMethodDecl, true, true); 2618 } 2619 2620 if (Method->isVariadic() != Overridden->isVariadic()) { 2621 Diag(Method->getLocation(), 2622 diag::warn_conflicting_overriding_variadic); 2623 Diag(Overridden->getLocation(), diag::note_previous_declaration); 2624 } 2625 } 2626 2627 /// WarnExactTypedMethods - This routine issues a warning if method 2628 /// implementation declaration matches exactly that of its declaration. 2629 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2630 ObjCMethodDecl *MethodDecl, 2631 bool IsProtocolMethodDecl) { 2632 // don't issue warning when protocol method is optional because primary 2633 // class is not required to implement it and it is safe for protocol 2634 // to implement it. 2635 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 2636 return; 2637 // don't issue warning when primary class's method is 2638 // deprecated/unavailable. 2639 if (MethodDecl->hasAttr<UnavailableAttr>() || 2640 MethodDecl->hasAttr<DeprecatedAttr>()) 2641 return; 2642 2643 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2644 IsProtocolMethodDecl, false, false); 2645 if (match) 2646 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2647 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2648 EF = MethodDecl->param_end(); 2649 IM != EM && IF != EF; ++IM, ++IF) { 2650 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 2651 *IM, *IF, 2652 IsProtocolMethodDecl, false, false); 2653 if (!match) 2654 break; 2655 } 2656 if (match) 2657 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 2658 if (match) 2659 match = !(MethodDecl->isClassMethod() && 2660 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 2661 2662 if (match) { 2663 Diag(ImpMethodDecl->getLocation(), 2664 diag::warn_category_method_impl_match); 2665 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 2666 << MethodDecl->getDeclName(); 2667 } 2668 } 2669 2670 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 2671 /// improve the efficiency of selector lookups and type checking by associating 2672 /// with each protocol / interface / category the flattened instance tables. If 2673 /// we used an immutable set to keep the table then it wouldn't add significant 2674 /// memory cost and it would be handy for lookups. 2675 2676 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet; 2677 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet; 2678 2679 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl, 2680 ProtocolNameSet &PNS) { 2681 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 2682 PNS.insert(PDecl->getIdentifier()); 2683 for (const auto *PI : PDecl->protocols()) 2684 findProtocolsWithExplicitImpls(PI, PNS); 2685 } 2686 2687 /// Recursively populates a set with all conformed protocols in a class 2688 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation' 2689 /// attribute. 2690 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super, 2691 ProtocolNameSet &PNS) { 2692 if (!Super) 2693 return; 2694 2695 for (const auto *I : Super->all_referenced_protocols()) 2696 findProtocolsWithExplicitImpls(I, PNS); 2697 2698 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS); 2699 } 2700 2701 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 2702 /// Declared in protocol, and those referenced by it. 2703 static void CheckProtocolMethodDefs( 2704 Sema &S, ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool &IncompleteImpl, 2705 const Sema::SelectorSet &InsMap, const Sema::SelectorSet &ClsMap, 2706 ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) { 2707 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 2708 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 2709 : dyn_cast<ObjCInterfaceDecl>(CDecl); 2710 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 2711 2712 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 2713 ObjCInterfaceDecl *NSIDecl = nullptr; 2714 2715 // If this protocol is marked 'objc_protocol_requires_explicit_implementation' 2716 // then we should check if any class in the super class hierarchy also 2717 // conforms to this protocol, either directly or via protocol inheritance. 2718 // If so, we can skip checking this protocol completely because we 2719 // know that a parent class already satisfies this protocol. 2720 // 2721 // Note: we could generalize this logic for all protocols, and merely 2722 // add the limit on looking at the super class chain for just 2723 // specially marked protocols. This may be a good optimization. This 2724 // change is restricted to 'objc_protocol_requires_explicit_implementation' 2725 // protocols for now for controlled evaluation. 2726 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) { 2727 if (!ProtocolsExplictImpl) { 2728 ProtocolsExplictImpl.reset(new ProtocolNameSet); 2729 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl); 2730 } 2731 if (ProtocolsExplictImpl->contains(PDecl->getIdentifier())) 2732 return; 2733 2734 // If no super class conforms to the protocol, we should not search 2735 // for methods in the super class to implicitly satisfy the protocol. 2736 Super = nullptr; 2737 } 2738 2739 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) { 2740 // check to see if class implements forwardInvocation method and objects 2741 // of this class are derived from 'NSProxy' so that to forward requests 2742 // from one object to another. 2743 // Under such conditions, which means that every method possible is 2744 // implemented in the class, we should not issue "Method definition not 2745 // found" warnings. 2746 // FIXME: Use a general GetUnarySelector method for this. 2747 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation"); 2748 Selector fISelector = S.Context.Selectors.getSelector(1, &II); 2749 if (InsMap.count(fISelector)) 2750 // Is IDecl derived from 'NSProxy'? If so, no instance methods 2751 // need be implemented in the implementation. 2752 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy")); 2753 } 2754 2755 // If this is a forward protocol declaration, get its definition. 2756 if (!PDecl->isThisDeclarationADefinition() && 2757 PDecl->getDefinition()) 2758 PDecl = PDecl->getDefinition(); 2759 2760 // If a method lookup fails locally we still need to look and see if 2761 // the method was implemented by a base class or an inherited 2762 // protocol. This lookup is slow, but occurs rarely in correct code 2763 // and otherwise would terminate in a warning. 2764 2765 // check unimplemented instance methods. 2766 if (!NSIDecl) 2767 for (auto *method : PDecl->instance_methods()) { 2768 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2769 !method->isPropertyAccessor() && 2770 !InsMap.count(method->getSelector()) && 2771 (!Super || !Super->lookupMethod(method->getSelector(), 2772 true /* instance */, 2773 false /* shallowCategory */, 2774 true /* followsSuper */, 2775 nullptr /* category */))) { 2776 // If a method is not implemented in the category implementation but 2777 // has been declared in its primary class, superclass, 2778 // or in one of their protocols, no need to issue the warning. 2779 // This is because method will be implemented in the primary class 2780 // or one of its super class implementation. 2781 2782 // Ugly, but necessary. Method declared in protocol might have 2783 // have been synthesized due to a property declared in the class which 2784 // uses the protocol. 2785 if (ObjCMethodDecl *MethodInClass = 2786 IDecl->lookupMethod(method->getSelector(), 2787 true /* instance */, 2788 true /* shallowCategoryLookup */, 2789 false /* followSuper */)) 2790 if (C || MethodInClass->isPropertyAccessor()) 2791 continue; 2792 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2793 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) { 2794 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl); 2795 } 2796 } 2797 } 2798 // check unimplemented class methods 2799 for (auto *method : PDecl->class_methods()) { 2800 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2801 !ClsMap.count(method->getSelector()) && 2802 (!Super || !Super->lookupMethod(method->getSelector(), 2803 false /* class method */, 2804 false /* shallowCategoryLookup */, 2805 true /* followSuper */, 2806 nullptr /* category */))) { 2807 // See above comment for instance method lookups. 2808 if (C && IDecl->lookupMethod(method->getSelector(), 2809 false /* class */, 2810 true /* shallowCategoryLookup */, 2811 false /* followSuper */)) 2812 continue; 2813 2814 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2815 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) { 2816 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl); 2817 } 2818 } 2819 } 2820 // Check on this protocols's referenced protocols, recursively. 2821 for (auto *PI : PDecl->protocols()) 2822 CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl, 2823 ProtocolsExplictImpl); 2824 } 2825 2826 /// MatchAllMethodDeclarations - Check methods declared in interface 2827 /// or protocol against those declared in their implementations. 2828 /// 2829 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 2830 const SelectorSet &ClsMap, 2831 SelectorSet &InsMapSeen, 2832 SelectorSet &ClsMapSeen, 2833 ObjCImplDecl* IMPDecl, 2834 ObjCContainerDecl* CDecl, 2835 bool &IncompleteImpl, 2836 bool ImmediateClass, 2837 bool WarnCategoryMethodImpl) { 2838 // Check and see if instance methods in class interface have been 2839 // implemented in the implementation class. If so, their types match. 2840 for (auto *I : CDecl->instance_methods()) { 2841 if (!InsMapSeen.insert(I->getSelector()).second) 2842 continue; 2843 if (!I->isPropertyAccessor() && 2844 !InsMap.count(I->getSelector())) { 2845 if (ImmediateClass) 2846 WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl, 2847 diag::warn_undef_method_impl); 2848 continue; 2849 } else { 2850 ObjCMethodDecl *ImpMethodDecl = 2851 IMPDecl->getInstanceMethod(I->getSelector()); 2852 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) && 2853 "Expected to find the method through lookup as well"); 2854 // ImpMethodDecl may be null as in a @dynamic property. 2855 if (ImpMethodDecl) { 2856 // Skip property accessor function stubs. 2857 if (ImpMethodDecl->isSynthesizedAccessorStub()) 2858 continue; 2859 if (!WarnCategoryMethodImpl) 2860 WarnConflictingTypedMethods(ImpMethodDecl, I, 2861 isa<ObjCProtocolDecl>(CDecl)); 2862 else if (!I->isPropertyAccessor()) 2863 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl)); 2864 } 2865 } 2866 } 2867 2868 // Check and see if class methods in class interface have been 2869 // implemented in the implementation class. If so, their types match. 2870 for (auto *I : CDecl->class_methods()) { 2871 if (!ClsMapSeen.insert(I->getSelector()).second) 2872 continue; 2873 if (!I->isPropertyAccessor() && 2874 !ClsMap.count(I->getSelector())) { 2875 if (ImmediateClass) 2876 WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl, 2877 diag::warn_undef_method_impl); 2878 } else { 2879 ObjCMethodDecl *ImpMethodDecl = 2880 IMPDecl->getClassMethod(I->getSelector()); 2881 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) && 2882 "Expected to find the method through lookup as well"); 2883 // ImpMethodDecl may be null as in a @dynamic property. 2884 if (ImpMethodDecl) { 2885 // Skip property accessor function stubs. 2886 if (ImpMethodDecl->isSynthesizedAccessorStub()) 2887 continue; 2888 if (!WarnCategoryMethodImpl) 2889 WarnConflictingTypedMethods(ImpMethodDecl, I, 2890 isa<ObjCProtocolDecl>(CDecl)); 2891 else if (!I->isPropertyAccessor()) 2892 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl)); 2893 } 2894 } 2895 } 2896 2897 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { 2898 // Also, check for methods declared in protocols inherited by 2899 // this protocol. 2900 for (auto *PI : PD->protocols()) 2901 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2902 IMPDecl, PI, IncompleteImpl, false, 2903 WarnCategoryMethodImpl); 2904 } 2905 2906 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2907 // when checking that methods in implementation match their declaration, 2908 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 2909 // extension; as well as those in categories. 2910 if (!WarnCategoryMethodImpl) { 2911 for (auto *Cat : I->visible_categories()) 2912 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2913 IMPDecl, Cat, IncompleteImpl, 2914 ImmediateClass && Cat->IsClassExtension(), 2915 WarnCategoryMethodImpl); 2916 } else { 2917 // Also methods in class extensions need be looked at next. 2918 for (auto *Ext : I->visible_extensions()) 2919 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2920 IMPDecl, Ext, IncompleteImpl, false, 2921 WarnCategoryMethodImpl); 2922 } 2923 2924 // Check for any implementation of a methods declared in protocol. 2925 for (auto *PI : I->all_referenced_protocols()) 2926 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2927 IMPDecl, PI, IncompleteImpl, false, 2928 WarnCategoryMethodImpl); 2929 2930 // FIXME. For now, we are not checking for exact match of methods 2931 // in category implementation and its primary class's super class. 2932 if (!WarnCategoryMethodImpl && I->getSuperClass()) 2933 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2934 IMPDecl, 2935 I->getSuperClass(), IncompleteImpl, false); 2936 } 2937 } 2938 2939 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2940 /// category matches with those implemented in its primary class and 2941 /// warns each time an exact match is found. 2942 void Sema::CheckCategoryVsClassMethodMatches( 2943 ObjCCategoryImplDecl *CatIMPDecl) { 2944 // Get category's primary class. 2945 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 2946 if (!CatDecl) 2947 return; 2948 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 2949 if (!IDecl) 2950 return; 2951 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 2952 SelectorSet InsMap, ClsMap; 2953 2954 for (const auto *I : CatIMPDecl->instance_methods()) { 2955 Selector Sel = I->getSelector(); 2956 // When checking for methods implemented in the category, skip over 2957 // those declared in category class's super class. This is because 2958 // the super class must implement the method. 2959 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 2960 continue; 2961 InsMap.insert(Sel); 2962 } 2963 2964 for (const auto *I : CatIMPDecl->class_methods()) { 2965 Selector Sel = I->getSelector(); 2966 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 2967 continue; 2968 ClsMap.insert(Sel); 2969 } 2970 if (InsMap.empty() && ClsMap.empty()) 2971 return; 2972 2973 SelectorSet InsMapSeen, ClsMapSeen; 2974 bool IncompleteImpl = false; 2975 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2976 CatIMPDecl, IDecl, 2977 IncompleteImpl, false, 2978 true /*WarnCategoryMethodImpl*/); 2979 } 2980 2981 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2982 ObjCContainerDecl* CDecl, 2983 bool IncompleteImpl) { 2984 SelectorSet InsMap; 2985 // Check and see if instance methods in class interface have been 2986 // implemented in the implementation class. 2987 for (const auto *I : IMPDecl->instance_methods()) 2988 InsMap.insert(I->getSelector()); 2989 2990 // Add the selectors for getters/setters of @dynamic properties. 2991 for (const auto *PImpl : IMPDecl->property_impls()) { 2992 // We only care about @dynamic implementations. 2993 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic) 2994 continue; 2995 2996 const auto *P = PImpl->getPropertyDecl(); 2997 if (!P) continue; 2998 2999 InsMap.insert(P->getGetterName()); 3000 if (!P->getSetterName().isNull()) 3001 InsMap.insert(P->getSetterName()); 3002 } 3003 3004 // Check and see if properties declared in the interface have either 1) 3005 // an implementation or 2) there is a @synthesize/@dynamic implementation 3006 // of the property in the @implementation. 3007 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 3008 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties && 3009 LangOpts.ObjCRuntime.isNonFragile() && 3010 !IDecl->isObjCRequiresPropertyDefs(); 3011 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties); 3012 } 3013 3014 // Diagnose null-resettable synthesized setters. 3015 diagnoseNullResettableSynthesizedSetters(IMPDecl); 3016 3017 SelectorSet ClsMap; 3018 for (const auto *I : IMPDecl->class_methods()) 3019 ClsMap.insert(I->getSelector()); 3020 3021 // Check for type conflict of methods declared in a class/protocol and 3022 // its implementation; if any. 3023 SelectorSet InsMapSeen, ClsMapSeen; 3024 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 3025 IMPDecl, CDecl, 3026 IncompleteImpl, true); 3027 3028 // check all methods implemented in category against those declared 3029 // in its primary class. 3030 if (ObjCCategoryImplDecl *CatDecl = 3031 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 3032 CheckCategoryVsClassMethodMatches(CatDecl); 3033 3034 // Check the protocol list for unimplemented methods in the @implementation 3035 // class. 3036 // Check and see if class methods in class interface have been 3037 // implemented in the implementation class. 3038 3039 LazyProtocolNameSet ExplicitImplProtocols; 3040 3041 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 3042 for (auto *PI : I->all_referenced_protocols()) 3043 CheckProtocolMethodDefs(*this, IMPDecl, PI, IncompleteImpl, InsMap, 3044 ClsMap, I, ExplicitImplProtocols); 3045 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 3046 // For extended class, unimplemented methods in its protocols will 3047 // be reported in the primary class. 3048 if (!C->IsClassExtension()) { 3049 for (auto *P : C->protocols()) 3050 CheckProtocolMethodDefs(*this, IMPDecl, P, IncompleteImpl, InsMap, 3051 ClsMap, CDecl, ExplicitImplProtocols); 3052 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, 3053 /*SynthesizeProperties=*/false); 3054 } 3055 } else 3056 llvm_unreachable("invalid ObjCContainerDecl type."); 3057 } 3058 3059 Sema::DeclGroupPtrTy 3060 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 3061 IdentifierInfo **IdentList, 3062 SourceLocation *IdentLocs, 3063 ArrayRef<ObjCTypeParamList *> TypeParamLists, 3064 unsigned NumElts) { 3065 SmallVector<Decl *, 8> DeclsInGroup; 3066 for (unsigned i = 0; i != NumElts; ++i) { 3067 // Check for another declaration kind with the same name. 3068 NamedDecl *PrevDecl 3069 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 3070 LookupOrdinaryName, forRedeclarationInCurContext()); 3071 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 3072 // GCC apparently allows the following idiom: 3073 // 3074 // typedef NSObject < XCElementTogglerP > XCElementToggler; 3075 // @class XCElementToggler; 3076 // 3077 // Here we have chosen to ignore the forward class declaration 3078 // with a warning. Since this is the implied behavior. 3079 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 3080 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 3081 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 3082 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3083 } else { 3084 // a forward class declaration matching a typedef name of a class refers 3085 // to the underlying class. Just ignore the forward class with a warning 3086 // as this will force the intended behavior which is to lookup the 3087 // typedef name. 3088 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 3089 Diag(AtClassLoc, diag::warn_forward_class_redefinition) 3090 << IdentList[i]; 3091 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3092 continue; 3093 } 3094 } 3095 } 3096 3097 // Create a declaration to describe this forward declaration. 3098 ObjCInterfaceDecl *PrevIDecl 3099 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 3100 3101 IdentifierInfo *ClassName = IdentList[i]; 3102 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 3103 // A previous decl with a different name is because of 3104 // @compatibility_alias, for example: 3105 // \code 3106 // @class NewImage; 3107 // @compatibility_alias OldImage NewImage; 3108 // \endcode 3109 // A lookup for 'OldImage' will return the 'NewImage' decl. 3110 // 3111 // In such a case use the real declaration name, instead of the alias one, 3112 // otherwise we will break IdentifierResolver and redecls-chain invariants. 3113 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 3114 // has been aliased. 3115 ClassName = PrevIDecl->getIdentifier(); 3116 } 3117 3118 // If this forward declaration has type parameters, compare them with the 3119 // type parameters of the previous declaration. 3120 ObjCTypeParamList *TypeParams = TypeParamLists[i]; 3121 if (PrevIDecl && TypeParams) { 3122 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) { 3123 // Check for consistency with the previous declaration. 3124 if (checkTypeParamListConsistency( 3125 *this, PrevTypeParams, TypeParams, 3126 TypeParamListContext::ForwardDeclaration)) { 3127 TypeParams = nullptr; 3128 } 3129 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 3130 // The @interface does not have type parameters. Complain. 3131 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class) 3132 << ClassName 3133 << TypeParams->getSourceRange(); 3134 Diag(Def->getLocation(), diag::note_defined_here) 3135 << ClassName; 3136 3137 TypeParams = nullptr; 3138 } 3139 } 3140 3141 ObjCInterfaceDecl *IDecl 3142 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 3143 ClassName, TypeParams, PrevIDecl, 3144 IdentLocs[i]); 3145 IDecl->setAtEndRange(IdentLocs[i]); 3146 3147 if (PrevIDecl) 3148 mergeDeclAttributes(IDecl, PrevIDecl); 3149 3150 PushOnScopeChains(IDecl, TUScope); 3151 CheckObjCDeclScope(IDecl); 3152 DeclsInGroup.push_back(IDecl); 3153 } 3154 3155 return BuildDeclaratorGroup(DeclsInGroup); 3156 } 3157 3158 static bool tryMatchRecordTypes(ASTContext &Context, 3159 Sema::MethodMatchStrategy strategy, 3160 const Type *left, const Type *right); 3161 3162 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 3163 QualType leftQT, QualType rightQT) { 3164 const Type *left = 3165 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 3166 const Type *right = 3167 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 3168 3169 if (left == right) return true; 3170 3171 // If we're doing a strict match, the types have to match exactly. 3172 if (strategy == Sema::MMS_strict) return false; 3173 3174 if (left->isIncompleteType() || right->isIncompleteType()) return false; 3175 3176 // Otherwise, use this absurdly complicated algorithm to try to 3177 // validate the basic, low-level compatibility of the two types. 3178 3179 // As a minimum, require the sizes and alignments to match. 3180 TypeInfo LeftTI = Context.getTypeInfo(left); 3181 TypeInfo RightTI = Context.getTypeInfo(right); 3182 if (LeftTI.Width != RightTI.Width) 3183 return false; 3184 3185 if (LeftTI.Align != RightTI.Align) 3186 return false; 3187 3188 // Consider all the kinds of non-dependent canonical types: 3189 // - functions and arrays aren't possible as return and parameter types 3190 3191 // - vector types of equal size can be arbitrarily mixed 3192 if (isa<VectorType>(left)) return isa<VectorType>(right); 3193 if (isa<VectorType>(right)) return false; 3194 3195 // - references should only match references of identical type 3196 // - structs, unions, and Objective-C objects must match more-or-less 3197 // exactly 3198 // - everything else should be a scalar 3199 if (!left->isScalarType() || !right->isScalarType()) 3200 return tryMatchRecordTypes(Context, strategy, left, right); 3201 3202 // Make scalars agree in kind, except count bools as chars, and group 3203 // all non-member pointers together. 3204 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 3205 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 3206 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 3207 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 3208 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 3209 leftSK = Type::STK_ObjCObjectPointer; 3210 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 3211 rightSK = Type::STK_ObjCObjectPointer; 3212 3213 // Note that data member pointers and function member pointers don't 3214 // intermix because of the size differences. 3215 3216 return (leftSK == rightSK); 3217 } 3218 3219 static bool tryMatchRecordTypes(ASTContext &Context, 3220 Sema::MethodMatchStrategy strategy, 3221 const Type *lt, const Type *rt) { 3222 assert(lt && rt && lt != rt); 3223 3224 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 3225 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 3226 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 3227 3228 // Require union-hood to match. 3229 if (left->isUnion() != right->isUnion()) return false; 3230 3231 // Require an exact match if either is non-POD. 3232 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 3233 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 3234 return false; 3235 3236 // Require size and alignment to match. 3237 TypeInfo LeftTI = Context.getTypeInfo(lt); 3238 TypeInfo RightTI = Context.getTypeInfo(rt); 3239 if (LeftTI.Width != RightTI.Width) 3240 return false; 3241 3242 if (LeftTI.Align != RightTI.Align) 3243 return false; 3244 3245 // Require fields to match. 3246 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 3247 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 3248 for (; li != le && ri != re; ++li, ++ri) { 3249 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 3250 return false; 3251 } 3252 return (li == le && ri == re); 3253 } 3254 3255 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 3256 /// returns true, or false, accordingly. 3257 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 3258 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 3259 const ObjCMethodDecl *right, 3260 MethodMatchStrategy strategy) { 3261 if (!matchTypes(Context, strategy, left->getReturnType(), 3262 right->getReturnType())) 3263 return false; 3264 3265 // If either is hidden, it is not considered to match. 3266 if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible()) 3267 return false; 3268 3269 if (left->isDirectMethod() != right->isDirectMethod()) 3270 return false; 3271 3272 if (getLangOpts().ObjCAutoRefCount && 3273 (left->hasAttr<NSReturnsRetainedAttr>() 3274 != right->hasAttr<NSReturnsRetainedAttr>() || 3275 left->hasAttr<NSConsumesSelfAttr>() 3276 != right->hasAttr<NSConsumesSelfAttr>())) 3277 return false; 3278 3279 ObjCMethodDecl::param_const_iterator 3280 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 3281 re = right->param_end(); 3282 3283 for (; li != le && ri != re; ++li, ++ri) { 3284 assert(ri != right->param_end() && "Param mismatch"); 3285 const ParmVarDecl *lparm = *li, *rparm = *ri; 3286 3287 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 3288 return false; 3289 3290 if (getLangOpts().ObjCAutoRefCount && 3291 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 3292 return false; 3293 } 3294 return true; 3295 } 3296 3297 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method, 3298 ObjCMethodDecl *MethodInList) { 3299 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext()); 3300 auto *MethodInListProtocol = 3301 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext()); 3302 // If this method belongs to a protocol but the method in list does not, or 3303 // vice versa, we say the context is not the same. 3304 if ((MethodProtocol && !MethodInListProtocol) || 3305 (!MethodProtocol && MethodInListProtocol)) 3306 return false; 3307 3308 if (MethodProtocol && MethodInListProtocol) 3309 return true; 3310 3311 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface(); 3312 ObjCInterfaceDecl *MethodInListInterface = 3313 MethodInList->getClassInterface(); 3314 return MethodInterface == MethodInListInterface; 3315 } 3316 3317 void Sema::addMethodToGlobalList(ObjCMethodList *List, 3318 ObjCMethodDecl *Method) { 3319 // Record at the head of the list whether there were 0, 1, or >= 2 methods 3320 // inside categories. 3321 if (ObjCCategoryDecl *CD = 3322 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 3323 if (!CD->IsClassExtension() && List->getBits() < 2) 3324 List->setBits(List->getBits() + 1); 3325 3326 // If the list is empty, make it a singleton list. 3327 if (List->getMethod() == nullptr) { 3328 List->setMethod(Method); 3329 List->setNext(nullptr); 3330 return; 3331 } 3332 3333 // We've seen a method with this name, see if we have already seen this type 3334 // signature. 3335 ObjCMethodList *Previous = List; 3336 ObjCMethodList *ListWithSameDeclaration = nullptr; 3337 for (; List; Previous = List, List = List->getNext()) { 3338 // If we are building a module, keep all of the methods. 3339 if (getLangOpts().isCompilingModule()) 3340 continue; 3341 3342 bool SameDeclaration = MatchTwoMethodDeclarations(Method, 3343 List->getMethod()); 3344 // Looking for method with a type bound requires the correct context exists. 3345 // We need to insert a method into the list if the context is different. 3346 // If the method's declaration matches the list 3347 // a> the method belongs to a different context: we need to insert it, in 3348 // order to emit the availability message, we need to prioritize over 3349 // availability among the methods with the same declaration. 3350 // b> the method belongs to the same context: there is no need to insert a 3351 // new entry. 3352 // If the method's declaration does not match the list, we insert it to the 3353 // end. 3354 if (!SameDeclaration || 3355 !isMethodContextSameForKindofLookup(Method, List->getMethod())) { 3356 // Even if two method types do not match, we would like to say 3357 // there is more than one declaration so unavailability/deprecated 3358 // warning is not too noisy. 3359 if (!Method->isDefined()) 3360 List->setHasMoreThanOneDecl(true); 3361 3362 // For methods with the same declaration, the one that is deprecated 3363 // should be put in the front for better diagnostics. 3364 if (Method->isDeprecated() && SameDeclaration && 3365 !ListWithSameDeclaration && !List->getMethod()->isDeprecated()) 3366 ListWithSameDeclaration = List; 3367 3368 if (Method->isUnavailable() && SameDeclaration && 3369 !ListWithSameDeclaration && 3370 List->getMethod()->getAvailability() < AR_Deprecated) 3371 ListWithSameDeclaration = List; 3372 continue; 3373 } 3374 3375 ObjCMethodDecl *PrevObjCMethod = List->getMethod(); 3376 3377 // Propagate the 'defined' bit. 3378 if (Method->isDefined()) 3379 PrevObjCMethod->setDefined(true); 3380 else { 3381 // Objective-C doesn't allow an @interface for a class after its 3382 // @implementation. So if Method is not defined and there already is 3383 // an entry for this type signature, Method has to be for a different 3384 // class than PrevObjCMethod. 3385 List->setHasMoreThanOneDecl(true); 3386 } 3387 3388 // If a method is deprecated, push it in the global pool. 3389 // This is used for better diagnostics. 3390 if (Method->isDeprecated()) { 3391 if (!PrevObjCMethod->isDeprecated()) 3392 List->setMethod(Method); 3393 } 3394 // If the new method is unavailable, push it into global pool 3395 // unless previous one is deprecated. 3396 if (Method->isUnavailable()) { 3397 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 3398 List->setMethod(Method); 3399 } 3400 3401 return; 3402 } 3403 3404 // We have a new signature for an existing method - add it. 3405 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 3406 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 3407 3408 // We insert it right before ListWithSameDeclaration. 3409 if (ListWithSameDeclaration) { 3410 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration); 3411 // FIXME: should we clear the other bits in ListWithSameDeclaration? 3412 ListWithSameDeclaration->setMethod(Method); 3413 ListWithSameDeclaration->setNext(List); 3414 return; 3415 } 3416 3417 Previous->setNext(new (Mem) ObjCMethodList(Method)); 3418 } 3419 3420 /// Read the contents of the method pool for a given selector from 3421 /// external storage. 3422 void Sema::ReadMethodPool(Selector Sel) { 3423 assert(ExternalSource && "We need an external AST source"); 3424 ExternalSource->ReadMethodPool(Sel); 3425 } 3426 3427 void Sema::updateOutOfDateSelector(Selector Sel) { 3428 if (!ExternalSource) 3429 return; 3430 ExternalSource->updateOutOfDateSelector(Sel); 3431 } 3432 3433 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 3434 bool instance) { 3435 // Ignore methods of invalid containers. 3436 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 3437 return; 3438 3439 if (ExternalSource) 3440 ReadMethodPool(Method->getSelector()); 3441 3442 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 3443 if (Pos == MethodPool.end()) 3444 Pos = MethodPool 3445 .insert(std::make_pair(Method->getSelector(), 3446 GlobalMethodPool::Lists())) 3447 .first; 3448 3449 Method->setDefined(impl); 3450 3451 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 3452 addMethodToGlobalList(&Entry, Method); 3453 } 3454 3455 /// Determines if this is an "acceptable" loose mismatch in the global 3456 /// method pool. This exists mostly as a hack to get around certain 3457 /// global mismatches which we can't afford to make warnings / errors. 3458 /// Really, what we want is a way to take a method out of the global 3459 /// method pool. 3460 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 3461 ObjCMethodDecl *other) { 3462 if (!chosen->isInstanceMethod()) 3463 return false; 3464 3465 if (chosen->isDirectMethod() != other->isDirectMethod()) 3466 return false; 3467 3468 Selector sel = chosen->getSelector(); 3469 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 3470 return false; 3471 3472 // Don't complain about mismatches for -length if the method we 3473 // chose has an integral result type. 3474 return (chosen->getReturnType()->isIntegerType()); 3475 } 3476 3477 /// Return true if the given method is wthin the type bound. 3478 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method, 3479 const ObjCObjectType *TypeBound) { 3480 if (!TypeBound) 3481 return true; 3482 3483 if (TypeBound->isObjCId()) 3484 // FIXME: should we handle the case of bounding to id<A, B> differently? 3485 return true; 3486 3487 auto *BoundInterface = TypeBound->getInterface(); 3488 assert(BoundInterface && "unexpected object type!"); 3489 3490 // Check if the Method belongs to a protocol. We should allow any method 3491 // defined in any protocol, because any subclass could adopt the protocol. 3492 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext()); 3493 if (MethodProtocol) { 3494 return true; 3495 } 3496 3497 // If the Method belongs to a class, check if it belongs to the class 3498 // hierarchy of the class bound. 3499 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) { 3500 // We allow methods declared within classes that are part of the hierarchy 3501 // of the class bound (superclass of, subclass of, or the same as the class 3502 // bound). 3503 return MethodInterface == BoundInterface || 3504 MethodInterface->isSuperClassOf(BoundInterface) || 3505 BoundInterface->isSuperClassOf(MethodInterface); 3506 } 3507 llvm_unreachable("unknown method context"); 3508 } 3509 3510 /// We first select the type of the method: Instance or Factory, then collect 3511 /// all methods with that type. 3512 bool Sema::CollectMultipleMethodsInGlobalPool( 3513 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, 3514 bool InstanceFirst, bool CheckTheOther, 3515 const ObjCObjectType *TypeBound) { 3516 if (ExternalSource) 3517 ReadMethodPool(Sel); 3518 3519 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3520 if (Pos == MethodPool.end()) 3521 return false; 3522 3523 // Gather the non-hidden methods. 3524 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first : 3525 Pos->second.second; 3526 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) 3527 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) { 3528 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound)) 3529 Methods.push_back(M->getMethod()); 3530 } 3531 3532 // Return if we find any method with the desired kind. 3533 if (!Methods.empty()) 3534 return Methods.size() > 1; 3535 3536 if (!CheckTheOther) 3537 return false; 3538 3539 // Gather the other kind. 3540 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second : 3541 Pos->second.first; 3542 for (ObjCMethodList *M = &MethList2; M; M = M->getNext()) 3543 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) { 3544 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound)) 3545 Methods.push_back(M->getMethod()); 3546 } 3547 3548 return Methods.size() > 1; 3549 } 3550 3551 bool Sema::AreMultipleMethodsInGlobalPool( 3552 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, 3553 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) { 3554 // Diagnose finding more than one method in global pool. 3555 SmallVector<ObjCMethodDecl *, 4> FilteredMethods; 3556 FilteredMethods.push_back(BestMethod); 3557 3558 for (auto *M : Methods) 3559 if (M != BestMethod && !M->hasAttr<UnavailableAttr>()) 3560 FilteredMethods.push_back(M); 3561 3562 if (FilteredMethods.size() > 1) 3563 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R, 3564 receiverIdOrClass); 3565 3566 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3567 // Test for no method in the pool which should not trigger any warning by 3568 // caller. 3569 if (Pos == MethodPool.end()) 3570 return true; 3571 ObjCMethodList &MethList = 3572 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second; 3573 return MethList.hasMoreThanOneDecl(); 3574 } 3575 3576 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 3577 bool receiverIdOrClass, 3578 bool instance) { 3579 if (ExternalSource) 3580 ReadMethodPool(Sel); 3581 3582 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3583 if (Pos == MethodPool.end()) 3584 return nullptr; 3585 3586 // Gather the non-hidden methods. 3587 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3588 SmallVector<ObjCMethodDecl *, 4> Methods; 3589 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 3590 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) 3591 return M->getMethod(); 3592 } 3593 return nullptr; 3594 } 3595 3596 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 3597 Selector Sel, SourceRange R, 3598 bool receiverIdOrClass) { 3599 // We found multiple methods, so we may have to complain. 3600 bool issueDiagnostic = false, issueError = false; 3601 3602 // We support a warning which complains about *any* difference in 3603 // method signature. 3604 bool strictSelectorMatch = 3605 receiverIdOrClass && 3606 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin()); 3607 if (strictSelectorMatch) { 3608 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3609 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 3610 issueDiagnostic = true; 3611 break; 3612 } 3613 } 3614 } 3615 3616 // If we didn't see any strict differences, we won't see any loose 3617 // differences. In ARC, however, we also need to check for loose 3618 // mismatches, because most of them are errors. 3619 if (!strictSelectorMatch || 3620 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 3621 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3622 // This checks if the methods differ in type mismatch. 3623 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 3624 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 3625 issueDiagnostic = true; 3626 if (getLangOpts().ObjCAutoRefCount) 3627 issueError = true; 3628 break; 3629 } 3630 } 3631 3632 if (issueDiagnostic) { 3633 if (issueError) 3634 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 3635 else if (strictSelectorMatch) 3636 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 3637 else 3638 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 3639 3640 Diag(Methods[0]->getBeginLoc(), 3641 issueError ? diag::note_possibility : diag::note_using) 3642 << Methods[0]->getSourceRange(); 3643 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3644 Diag(Methods[I]->getBeginLoc(), diag::note_also_found) 3645 << Methods[I]->getSourceRange(); 3646 } 3647 } 3648 } 3649 3650 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 3651 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3652 if (Pos == MethodPool.end()) 3653 return nullptr; 3654 3655 GlobalMethodPool::Lists &Methods = Pos->second; 3656 for (const ObjCMethodList *Method = &Methods.first; Method; 3657 Method = Method->getNext()) 3658 if (Method->getMethod() && 3659 (Method->getMethod()->isDefined() || 3660 Method->getMethod()->isPropertyAccessor())) 3661 return Method->getMethod(); 3662 3663 for (const ObjCMethodList *Method = &Methods.second; Method; 3664 Method = Method->getNext()) 3665 if (Method->getMethod() && 3666 (Method->getMethod()->isDefined() || 3667 Method->getMethod()->isPropertyAccessor())) 3668 return Method->getMethod(); 3669 return nullptr; 3670 } 3671 3672 static void 3673 HelperSelectorsForTypoCorrection( 3674 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 3675 StringRef Typo, const ObjCMethodDecl * Method) { 3676 const unsigned MaxEditDistance = 1; 3677 unsigned BestEditDistance = MaxEditDistance + 1; 3678 std::string MethodName = Method->getSelector().getAsString(); 3679 3680 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 3681 if (MinPossibleEditDistance > 0 && 3682 Typo.size() / MinPossibleEditDistance < 1) 3683 return; 3684 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 3685 if (EditDistance > MaxEditDistance) 3686 return; 3687 if (EditDistance == BestEditDistance) 3688 BestMethod.push_back(Method); 3689 else if (EditDistance < BestEditDistance) { 3690 BestMethod.clear(); 3691 BestMethod.push_back(Method); 3692 } 3693 } 3694 3695 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 3696 QualType ObjectType) { 3697 if (ObjectType.isNull()) 3698 return true; 3699 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 3700 return true; 3701 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 3702 nullptr; 3703 } 3704 3705 const ObjCMethodDecl * 3706 Sema::SelectorsForTypoCorrection(Selector Sel, 3707 QualType ObjectType) { 3708 unsigned NumArgs = Sel.getNumArgs(); 3709 SmallVector<const ObjCMethodDecl *, 8> Methods; 3710 bool ObjectIsId = true, ObjectIsClass = true; 3711 if (ObjectType.isNull()) 3712 ObjectIsId = ObjectIsClass = false; 3713 else if (!ObjectType->isObjCObjectPointerType()) 3714 return nullptr; 3715 else if (const ObjCObjectPointerType *ObjCPtr = 3716 ObjectType->getAsObjCInterfacePointerType()) { 3717 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 3718 ObjectIsId = ObjectIsClass = false; 3719 } 3720 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 3721 ObjectIsClass = false; 3722 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 3723 ObjectIsId = false; 3724 else 3725 return nullptr; 3726 3727 for (GlobalMethodPool::iterator b = MethodPool.begin(), 3728 e = MethodPool.end(); b != e; b++) { 3729 // instance methods 3730 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 3731 if (M->getMethod() && 3732 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3733 (M->getMethod()->getSelector() != Sel)) { 3734 if (ObjectIsId) 3735 Methods.push_back(M->getMethod()); 3736 else if (!ObjectIsClass && 3737 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3738 ObjectType)) 3739 Methods.push_back(M->getMethod()); 3740 } 3741 // class methods 3742 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 3743 if (M->getMethod() && 3744 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3745 (M->getMethod()->getSelector() != Sel)) { 3746 if (ObjectIsClass) 3747 Methods.push_back(M->getMethod()); 3748 else if (!ObjectIsId && 3749 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3750 ObjectType)) 3751 Methods.push_back(M->getMethod()); 3752 } 3753 } 3754 3755 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 3756 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 3757 HelperSelectorsForTypoCorrection(SelectedMethods, 3758 Sel.getAsString(), Methods[i]); 3759 } 3760 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr; 3761 } 3762 3763 /// DiagnoseDuplicateIvars - 3764 /// Check for duplicate ivars in the entire class at the start of 3765 /// \@implementation. This becomes necessary because class extension can 3766 /// add ivars to a class in random order which will not be known until 3767 /// class's \@implementation is seen. 3768 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 3769 ObjCInterfaceDecl *SID) { 3770 for (auto *Ivar : ID->ivars()) { 3771 if (Ivar->isInvalidDecl()) 3772 continue; 3773 if (IdentifierInfo *II = Ivar->getIdentifier()) { 3774 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 3775 if (prevIvar) { 3776 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3777 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3778 Ivar->setInvalidDecl(); 3779 } 3780 } 3781 } 3782 } 3783 3784 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled. 3785 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) { 3786 if (S.getLangOpts().ObjCWeak) return; 3787 3788 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin(); 3789 ivar; ivar = ivar->getNextIvar()) { 3790 if (ivar->isInvalidDecl()) continue; 3791 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 3792 if (S.getLangOpts().ObjCWeakRuntime) { 3793 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled); 3794 } else { 3795 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime); 3796 } 3797 } 3798 } 3799 } 3800 3801 /// Diagnose attempts to use flexible array member with retainable object type. 3802 static void DiagnoseRetainableFlexibleArrayMember(Sema &S, 3803 ObjCInterfaceDecl *ID) { 3804 if (!S.getLangOpts().ObjCAutoRefCount) 3805 return; 3806 3807 for (auto ivar = ID->all_declared_ivar_begin(); ivar; 3808 ivar = ivar->getNextIvar()) { 3809 if (ivar->isInvalidDecl()) 3810 continue; 3811 QualType IvarTy = ivar->getType(); 3812 if (IvarTy->isIncompleteArrayType() && 3813 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) && 3814 IvarTy->isObjCLifetimeType()) { 3815 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable); 3816 ivar->setInvalidDecl(); 3817 } 3818 } 3819 } 3820 3821 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 3822 switch (CurContext->getDeclKind()) { 3823 case Decl::ObjCInterface: 3824 return Sema::OCK_Interface; 3825 case Decl::ObjCProtocol: 3826 return Sema::OCK_Protocol; 3827 case Decl::ObjCCategory: 3828 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 3829 return Sema::OCK_ClassExtension; 3830 return Sema::OCK_Category; 3831 case Decl::ObjCImplementation: 3832 return Sema::OCK_Implementation; 3833 case Decl::ObjCCategoryImpl: 3834 return Sema::OCK_CategoryImplementation; 3835 3836 default: 3837 return Sema::OCK_None; 3838 } 3839 } 3840 3841 static bool IsVariableSizedType(QualType T) { 3842 if (T->isIncompleteArrayType()) 3843 return true; 3844 const auto *RecordTy = T->getAs<RecordType>(); 3845 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember()); 3846 } 3847 3848 static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) { 3849 ObjCInterfaceDecl *IntfDecl = nullptr; 3850 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range( 3851 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator()); 3852 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) { 3853 Ivars = IntfDecl->ivars(); 3854 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) { 3855 IntfDecl = ImplDecl->getClassInterface(); 3856 Ivars = ImplDecl->ivars(); 3857 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) { 3858 if (CategoryDecl->IsClassExtension()) { 3859 IntfDecl = CategoryDecl->getClassInterface(); 3860 Ivars = CategoryDecl->ivars(); 3861 } 3862 } 3863 3864 // Check if variable sized ivar is in interface and visible to subclasses. 3865 if (!isa<ObjCInterfaceDecl>(OCD)) { 3866 for (auto *ivar : Ivars) { 3867 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) { 3868 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility) 3869 << ivar->getDeclName() << ivar->getType(); 3870 } 3871 } 3872 } 3873 3874 // Subsequent checks require interface decl. 3875 if (!IntfDecl) 3876 return; 3877 3878 // Check if variable sized ivar is followed by another ivar. 3879 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar; 3880 ivar = ivar->getNextIvar()) { 3881 if (ivar->isInvalidDecl() || !ivar->getNextIvar()) 3882 continue; 3883 QualType IvarTy = ivar->getType(); 3884 bool IsInvalidIvar = false; 3885 if (IvarTy->isIncompleteArrayType()) { 3886 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end) 3887 << ivar->getDeclName() << IvarTy 3888 << TTK_Class; // Use "class" for Obj-C. 3889 IsInvalidIvar = true; 3890 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) { 3891 if (RecordTy->getDecl()->hasFlexibleArrayMember()) { 3892 S.Diag(ivar->getLocation(), 3893 diag::err_objc_variable_sized_type_not_at_end) 3894 << ivar->getDeclName() << IvarTy; 3895 IsInvalidIvar = true; 3896 } 3897 } 3898 if (IsInvalidIvar) { 3899 S.Diag(ivar->getNextIvar()->getLocation(), 3900 diag::note_next_ivar_declaration) 3901 << ivar->getNextIvar()->getSynthesize(); 3902 ivar->setInvalidDecl(); 3903 } 3904 } 3905 3906 // Check if ObjC container adds ivars after variable sized ivar in superclass. 3907 // Perform the check only if OCD is the first container to declare ivars to 3908 // avoid multiple warnings for the same ivar. 3909 ObjCIvarDecl *FirstIvar = 3910 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin(); 3911 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) { 3912 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass(); 3913 while (SuperClass && SuperClass->ivar_empty()) 3914 SuperClass = SuperClass->getSuperClass(); 3915 if (SuperClass) { 3916 auto IvarIter = SuperClass->ivar_begin(); 3917 std::advance(IvarIter, SuperClass->ivar_size() - 1); 3918 const ObjCIvarDecl *LastIvar = *IvarIter; 3919 if (IsVariableSizedType(LastIvar->getType())) { 3920 S.Diag(FirstIvar->getLocation(), 3921 diag::warn_superclass_variable_sized_type_not_at_end) 3922 << FirstIvar->getDeclName() << LastIvar->getDeclName() 3923 << LastIvar->getType() << SuperClass->getDeclName(); 3924 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at) 3925 << LastIvar->getDeclName(); 3926 } 3927 } 3928 } 3929 } 3930 3931 static void DiagnoseCategoryDirectMembersProtocolConformance( 3932 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl); 3933 3934 static void DiagnoseCategoryDirectMembersProtocolConformance( 3935 Sema &S, ObjCCategoryDecl *CDecl, 3936 const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) { 3937 for (auto *PI : Protocols) 3938 DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl); 3939 } 3940 3941 static void DiagnoseCategoryDirectMembersProtocolConformance( 3942 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) { 3943 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) 3944 PDecl = PDecl->getDefinition(); 3945 3946 llvm::SmallVector<const Decl *, 4> DirectMembers; 3947 const auto *IDecl = CDecl->getClassInterface(); 3948 for (auto *MD : PDecl->methods()) { 3949 if (!MD->isPropertyAccessor()) { 3950 if (const auto *CMD = 3951 IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) { 3952 if (CMD->isDirectMethod()) 3953 DirectMembers.push_back(CMD); 3954 } 3955 } 3956 } 3957 for (auto *PD : PDecl->properties()) { 3958 if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass( 3959 PD->getIdentifier(), 3960 PD->isClassProperty() 3961 ? ObjCPropertyQueryKind::OBJC_PR_query_class 3962 : ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 3963 if (CPD->isDirectProperty()) 3964 DirectMembers.push_back(CPD); 3965 } 3966 } 3967 if (!DirectMembers.empty()) { 3968 S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance) 3969 << CDecl->IsClassExtension() << CDecl << PDecl << IDecl; 3970 for (const auto *MD : DirectMembers) 3971 S.Diag(MD->getLocation(), diag::note_direct_member_here); 3972 return; 3973 } 3974 3975 // Check on this protocols's referenced protocols, recursively. 3976 DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl, 3977 PDecl->protocols()); 3978 } 3979 3980 // Note: For class/category implementations, allMethods is always null. 3981 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 3982 ArrayRef<DeclGroupPtrTy> allTUVars) { 3983 if (getObjCContainerKind() == Sema::OCK_None) 3984 return nullptr; 3985 3986 assert(AtEnd.isValid() && "Invalid location for '@end'"); 3987 3988 auto *OCD = cast<ObjCContainerDecl>(CurContext); 3989 Decl *ClassDecl = OCD; 3990 3991 bool isInterfaceDeclKind = 3992 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 3993 || isa<ObjCProtocolDecl>(ClassDecl); 3994 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 3995 3996 // Make synthesized accessor stub functions visible. 3997 // ActOnPropertyImplDecl() creates them as not visible in case 3998 // they are overridden by an explicit method that is encountered 3999 // later. 4000 if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) { 4001 for (auto *PropImpl : OID->property_impls()) { 4002 if (auto *Getter = PropImpl->getGetterMethodDecl()) 4003 if (Getter->isSynthesizedAccessorStub()) 4004 OID->addDecl(Getter); 4005 if (auto *Setter = PropImpl->getSetterMethodDecl()) 4006 if (Setter->isSynthesizedAccessorStub()) 4007 OID->addDecl(Setter); 4008 } 4009 } 4010 4011 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 4012 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 4013 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 4014 4015 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 4016 ObjCMethodDecl *Method = 4017 cast_or_null<ObjCMethodDecl>(allMethods[i]); 4018 4019 if (!Method) continue; // Already issued a diagnostic. 4020 if (Method->isInstanceMethod()) { 4021 /// Check for instance method of the same name with incompatible types 4022 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 4023 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 4024 : false; 4025 if ((isInterfaceDeclKind && PrevMethod && !match) 4026 || (checkIdenticalMethods && match)) { 4027 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 4028 << Method->getDeclName(); 4029 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4030 Method->setInvalidDecl(); 4031 } else { 4032 if (PrevMethod) { 4033 Method->setAsRedeclaration(PrevMethod); 4034 if (!Context.getSourceManager().isInSystemHeader( 4035 Method->getLocation())) 4036 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 4037 << Method->getDeclName(); 4038 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4039 } 4040 InsMap[Method->getSelector()] = Method; 4041 /// The following allows us to typecheck messages to "id". 4042 AddInstanceMethodToGlobalPool(Method); 4043 } 4044 } else { 4045 /// Check for class method of the same name with incompatible types 4046 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 4047 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 4048 : false; 4049 if ((isInterfaceDeclKind && PrevMethod && !match) 4050 || (checkIdenticalMethods && match)) { 4051 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 4052 << Method->getDeclName(); 4053 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4054 Method->setInvalidDecl(); 4055 } else { 4056 if (PrevMethod) { 4057 Method->setAsRedeclaration(PrevMethod); 4058 if (!Context.getSourceManager().isInSystemHeader( 4059 Method->getLocation())) 4060 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 4061 << Method->getDeclName(); 4062 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4063 } 4064 ClsMap[Method->getSelector()] = Method; 4065 AddFactoryMethodToGlobalPool(Method); 4066 } 4067 } 4068 } 4069 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 4070 // Nothing to do here. 4071 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 4072 // Categories are used to extend the class by declaring new methods. 4073 // By the same token, they are also used to add new properties. No 4074 // need to compare the added property to those in the class. 4075 4076 if (C->IsClassExtension()) { 4077 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 4078 DiagnoseClassExtensionDupMethods(C, CCPrimary); 4079 } 4080 4081 DiagnoseCategoryDirectMembersProtocolConformance(*this, C, C->protocols()); 4082 } 4083 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 4084 if (CDecl->getIdentifier()) 4085 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 4086 // user-defined setter/getter. It also synthesizes setter/getter methods 4087 // and adds them to the DeclContext and global method pools. 4088 for (auto *I : CDecl->properties()) 4089 ProcessPropertyDecl(I); 4090 CDecl->setAtEndRange(AtEnd); 4091 } 4092 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 4093 IC->setAtEndRange(AtEnd); 4094 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 4095 // Any property declared in a class extension might have user 4096 // declared setter or getter in current class extension or one 4097 // of the other class extensions. Mark them as synthesized as 4098 // property will be synthesized when property with same name is 4099 // seen in the @implementation. 4100 for (const auto *Ext : IDecl->visible_extensions()) { 4101 for (const auto *Property : Ext->instance_properties()) { 4102 // Skip over properties declared @dynamic 4103 if (const ObjCPropertyImplDecl *PIDecl 4104 = IC->FindPropertyImplDecl(Property->getIdentifier(), 4105 Property->getQueryKind())) 4106 if (PIDecl->getPropertyImplementation() 4107 == ObjCPropertyImplDecl::Dynamic) 4108 continue; 4109 4110 for (const auto *Ext : IDecl->visible_extensions()) { 4111 if (ObjCMethodDecl *GetterMethod = 4112 Ext->getInstanceMethod(Property->getGetterName())) 4113 GetterMethod->setPropertyAccessor(true); 4114 if (!Property->isReadOnly()) 4115 if (ObjCMethodDecl *SetterMethod 4116 = Ext->getInstanceMethod(Property->getSetterName())) 4117 SetterMethod->setPropertyAccessor(true); 4118 } 4119 } 4120 } 4121 ImplMethodsVsClassMethods(S, IC, IDecl); 4122 AtomicPropertySetterGetterRules(IC, IDecl); 4123 DiagnoseOwningPropertyGetterSynthesis(IC); 4124 DiagnoseUnusedBackingIvarInAccessor(S, IC); 4125 if (IDecl->hasDesignatedInitializers()) 4126 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 4127 DiagnoseWeakIvars(*this, IC); 4128 DiagnoseRetainableFlexibleArrayMember(*this, IDecl); 4129 4130 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 4131 if (IDecl->getSuperClass() == nullptr) { 4132 // This class has no superclass, so check that it has been marked with 4133 // __attribute((objc_root_class)). 4134 if (!HasRootClassAttr) { 4135 SourceLocation DeclLoc(IDecl->getLocation()); 4136 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc)); 4137 Diag(DeclLoc, diag::warn_objc_root_class_missing) 4138 << IDecl->getIdentifier(); 4139 // See if NSObject is in the current scope, and if it is, suggest 4140 // adding " : NSObject " to the class declaration. 4141 NamedDecl *IF = LookupSingleName(TUScope, 4142 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 4143 DeclLoc, LookupOrdinaryName); 4144 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 4145 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 4146 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 4147 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 4148 } else { 4149 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 4150 } 4151 } 4152 } else if (HasRootClassAttr) { 4153 // Complain that only root classes may have this attribute. 4154 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 4155 } 4156 4157 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) { 4158 // An interface can subclass another interface with a 4159 // objc_subclassing_restricted attribute when it has that attribute as 4160 // well (because of interfaces imported from Swift). Therefore we have 4161 // to check if we can subclass in the implementation as well. 4162 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() && 4163 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) { 4164 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch); 4165 Diag(Super->getLocation(), diag::note_class_declared); 4166 } 4167 } 4168 4169 if (IDecl->hasAttr<ObjCClassStubAttr>()) 4170 Diag(IC->getLocation(), diag::err_implementation_of_class_stub); 4171 4172 if (LangOpts.ObjCRuntime.isNonFragile()) { 4173 while (IDecl->getSuperClass()) { 4174 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 4175 IDecl = IDecl->getSuperClass(); 4176 } 4177 } 4178 } 4179 SetIvarInitializers(IC); 4180 } else if (ObjCCategoryImplDecl* CatImplClass = 4181 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 4182 CatImplClass->setAtEndRange(AtEnd); 4183 4184 // Find category interface decl and then check that all methods declared 4185 // in this interface are implemented in the category @implementation. 4186 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 4187 if (ObjCCategoryDecl *Cat 4188 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 4189 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 4190 } 4191 } 4192 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) { 4193 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) { 4194 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() && 4195 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) { 4196 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch); 4197 Diag(Super->getLocation(), diag::note_class_declared); 4198 } 4199 } 4200 4201 if (IntfDecl->hasAttr<ObjCClassStubAttr>() && 4202 !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>()) 4203 Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch); 4204 } 4205 DiagnoseVariableSizedIvars(*this, OCD); 4206 if (isInterfaceDeclKind) { 4207 // Reject invalid vardecls. 4208 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 4209 DeclGroupRef DG = allTUVars[i].get(); 4210 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 4211 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 4212 if (!VDecl->hasExternalStorage()) 4213 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 4214 } 4215 } 4216 } 4217 ActOnObjCContainerFinishDefinition(); 4218 4219 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 4220 DeclGroupRef DG = allTUVars[i].get(); 4221 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 4222 (*I)->setTopLevelDeclInObjCContainer(); 4223 Consumer.HandleTopLevelDeclInObjCContainer(DG); 4224 } 4225 4226 ActOnDocumentableDecl(ClassDecl); 4227 return ClassDecl; 4228 } 4229 4230 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 4231 /// objective-c's type qualifier from the parser version of the same info. 4232 static Decl::ObjCDeclQualifier 4233 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 4234 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 4235 } 4236 4237 /// Check whether the declared result type of the given Objective-C 4238 /// method declaration is compatible with the method's class. 4239 /// 4240 static Sema::ResultTypeCompatibilityKind 4241 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 4242 ObjCInterfaceDecl *CurrentClass) { 4243 QualType ResultType = Method->getReturnType(); 4244 4245 // If an Objective-C method inherits its related result type, then its 4246 // declared result type must be compatible with its own class type. The 4247 // declared result type is compatible if: 4248 if (const ObjCObjectPointerType *ResultObjectType 4249 = ResultType->getAs<ObjCObjectPointerType>()) { 4250 // - it is id or qualified id, or 4251 if (ResultObjectType->isObjCIdType() || 4252 ResultObjectType->isObjCQualifiedIdType()) 4253 return Sema::RTC_Compatible; 4254 4255 if (CurrentClass) { 4256 if (ObjCInterfaceDecl *ResultClass 4257 = ResultObjectType->getInterfaceDecl()) { 4258 // - it is the same as the method's class type, or 4259 if (declaresSameEntity(CurrentClass, ResultClass)) 4260 return Sema::RTC_Compatible; 4261 4262 // - it is a superclass of the method's class type 4263 if (ResultClass->isSuperClassOf(CurrentClass)) 4264 return Sema::RTC_Compatible; 4265 } 4266 } else { 4267 // Any Objective-C pointer type might be acceptable for a protocol 4268 // method; we just don't know. 4269 return Sema::RTC_Unknown; 4270 } 4271 } 4272 4273 return Sema::RTC_Incompatible; 4274 } 4275 4276 namespace { 4277 /// A helper class for searching for methods which a particular method 4278 /// overrides. 4279 class OverrideSearch { 4280 public: 4281 const ObjCMethodDecl *Method; 4282 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden; 4283 bool Recursive; 4284 4285 public: 4286 OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) { 4287 Selector selector = method->getSelector(); 4288 4289 // Bypass this search if we've never seen an instance/class method 4290 // with this selector before. 4291 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 4292 if (it == S.MethodPool.end()) { 4293 if (!S.getExternalSource()) return; 4294 S.ReadMethodPool(selector); 4295 4296 it = S.MethodPool.find(selector); 4297 if (it == S.MethodPool.end()) 4298 return; 4299 } 4300 const ObjCMethodList &list = 4301 method->isInstanceMethod() ? it->second.first : it->second.second; 4302 if (!list.getMethod()) return; 4303 4304 const ObjCContainerDecl *container 4305 = cast<ObjCContainerDecl>(method->getDeclContext()); 4306 4307 // Prevent the search from reaching this container again. This is 4308 // important with categories, which override methods from the 4309 // interface and each other. 4310 if (const ObjCCategoryDecl *Category = 4311 dyn_cast<ObjCCategoryDecl>(container)) { 4312 searchFromContainer(container); 4313 if (const ObjCInterfaceDecl *Interface = Category->getClassInterface()) 4314 searchFromContainer(Interface); 4315 } else { 4316 searchFromContainer(container); 4317 } 4318 } 4319 4320 typedef decltype(Overridden)::iterator iterator; 4321 iterator begin() const { return Overridden.begin(); } 4322 iterator end() const { return Overridden.end(); } 4323 4324 private: 4325 void searchFromContainer(const ObjCContainerDecl *container) { 4326 if (container->isInvalidDecl()) return; 4327 4328 switch (container->getDeclKind()) { 4329 #define OBJCCONTAINER(type, base) \ 4330 case Decl::type: \ 4331 searchFrom(cast<type##Decl>(container)); \ 4332 break; 4333 #define ABSTRACT_DECL(expansion) 4334 #define DECL(type, base) \ 4335 case Decl::type: 4336 #include "clang/AST/DeclNodes.inc" 4337 llvm_unreachable("not an ObjC container!"); 4338 } 4339 } 4340 4341 void searchFrom(const ObjCProtocolDecl *protocol) { 4342 if (!protocol->hasDefinition()) 4343 return; 4344 4345 // A method in a protocol declaration overrides declarations from 4346 // referenced ("parent") protocols. 4347 search(protocol->getReferencedProtocols()); 4348 } 4349 4350 void searchFrom(const ObjCCategoryDecl *category) { 4351 // A method in a category declaration overrides declarations from 4352 // the main class and from protocols the category references. 4353 // The main class is handled in the constructor. 4354 search(category->getReferencedProtocols()); 4355 } 4356 4357 void searchFrom(const ObjCCategoryImplDecl *impl) { 4358 // A method in a category definition that has a category 4359 // declaration overrides declarations from the category 4360 // declaration. 4361 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 4362 search(category); 4363 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 4364 search(Interface); 4365 4366 // Otherwise it overrides declarations from the class. 4367 } else if (const auto *Interface = impl->getClassInterface()) { 4368 search(Interface); 4369 } 4370 } 4371 4372 void searchFrom(const ObjCInterfaceDecl *iface) { 4373 // A method in a class declaration overrides declarations from 4374 if (!iface->hasDefinition()) 4375 return; 4376 4377 // - categories, 4378 for (auto *Cat : iface->known_categories()) 4379 search(Cat); 4380 4381 // - the super class, and 4382 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 4383 search(super); 4384 4385 // - any referenced protocols. 4386 search(iface->getReferencedProtocols()); 4387 } 4388 4389 void searchFrom(const ObjCImplementationDecl *impl) { 4390 // A method in a class implementation overrides declarations from 4391 // the class interface. 4392 if (const auto *Interface = impl->getClassInterface()) 4393 search(Interface); 4394 } 4395 4396 void search(const ObjCProtocolList &protocols) { 4397 for (const auto *Proto : protocols) 4398 search(Proto); 4399 } 4400 4401 void search(const ObjCContainerDecl *container) { 4402 // Check for a method in this container which matches this selector. 4403 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 4404 Method->isInstanceMethod(), 4405 /*AllowHidden=*/true); 4406 4407 // If we find one, record it and bail out. 4408 if (meth) { 4409 Overridden.insert(meth); 4410 return; 4411 } 4412 4413 // Otherwise, search for methods that a hypothetical method here 4414 // would have overridden. 4415 4416 // Note that we're now in a recursive case. 4417 Recursive = true; 4418 4419 searchFromContainer(container); 4420 } 4421 }; 4422 } // end anonymous namespace 4423 4424 void Sema::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, 4425 ObjCMethodDecl *overridden) { 4426 if (overridden->isDirectMethod()) { 4427 const auto *attr = overridden->getAttr<ObjCDirectAttr>(); 4428 Diag(method->getLocation(), diag::err_objc_override_direct_method); 4429 Diag(attr->getLocation(), diag::note_previous_declaration); 4430 } else if (method->isDirectMethod()) { 4431 const auto *attr = method->getAttr<ObjCDirectAttr>(); 4432 Diag(attr->getLocation(), diag::err_objc_direct_on_override) 4433 << isa<ObjCProtocolDecl>(overridden->getDeclContext()); 4434 Diag(overridden->getLocation(), diag::note_previous_declaration); 4435 } 4436 } 4437 4438 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 4439 ObjCInterfaceDecl *CurrentClass, 4440 ResultTypeCompatibilityKind RTC) { 4441 if (!ObjCMethod) 4442 return; 4443 auto IsMethodInCurrentClass = [CurrentClass](const ObjCMethodDecl *M) { 4444 // Checking canonical decl works across modules. 4445 return M->getClassInterface()->getCanonicalDecl() == 4446 CurrentClass->getCanonicalDecl(); 4447 }; 4448 // Search for overridden methods and merge information down from them. 4449 OverrideSearch overrides(*this, ObjCMethod); 4450 // Keep track if the method overrides any method in the class's base classes, 4451 // its protocols, or its categories' protocols; we will keep that info 4452 // in the ObjCMethodDecl. 4453 // For this info, a method in an implementation is not considered as 4454 // overriding the same method in the interface or its categories. 4455 bool hasOverriddenMethodsInBaseOrProtocol = false; 4456 for (ObjCMethodDecl *overridden : overrides) { 4457 if (!hasOverriddenMethodsInBaseOrProtocol) { 4458 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 4459 !IsMethodInCurrentClass(overridden) || overridden->isOverriding()) { 4460 CheckObjCMethodDirectOverrides(ObjCMethod, overridden); 4461 hasOverriddenMethodsInBaseOrProtocol = true; 4462 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 4463 // OverrideSearch will return as "overridden" the same method in the 4464 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 4465 // check whether a category of a base class introduced a method with the 4466 // same selector, after the interface method declaration. 4467 // To avoid unnecessary lookups in the majority of cases, we use the 4468 // extra info bits in GlobalMethodPool to check whether there were any 4469 // category methods with this selector. 4470 GlobalMethodPool::iterator It = 4471 MethodPool.find(ObjCMethod->getSelector()); 4472 if (It != MethodPool.end()) { 4473 ObjCMethodList &List = 4474 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 4475 unsigned CategCount = List.getBits(); 4476 if (CategCount > 0) { 4477 // If the method is in a category we'll do lookup if there were at 4478 // least 2 category methods recorded, otherwise only one will do. 4479 if (CategCount > 1 || 4480 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 4481 OverrideSearch overrides(*this, overridden); 4482 for (ObjCMethodDecl *SuperOverridden : overrides) { 4483 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 4484 !IsMethodInCurrentClass(SuperOverridden)) { 4485 CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden); 4486 hasOverriddenMethodsInBaseOrProtocol = true; 4487 overridden->setOverriding(true); 4488 break; 4489 } 4490 } 4491 } 4492 } 4493 } 4494 } 4495 } 4496 4497 // Propagate down the 'related result type' bit from overridden methods. 4498 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 4499 ObjCMethod->setRelatedResultType(); 4500 4501 // Then merge the declarations. 4502 mergeObjCMethodDecls(ObjCMethod, overridden); 4503 4504 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 4505 continue; // Conflicting properties are detected elsewhere. 4506 4507 // Check for overriding methods 4508 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 4509 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 4510 CheckConflictingOverridingMethod(ObjCMethod, overridden, 4511 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 4512 4513 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 4514 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 4515 !overridden->isImplicit() /* not meant for properties */) { 4516 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 4517 E = ObjCMethod->param_end(); 4518 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 4519 PrevE = overridden->param_end(); 4520 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 4521 assert(PrevI != overridden->param_end() && "Param mismatch"); 4522 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 4523 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 4524 // If type of argument of method in this class does not match its 4525 // respective argument type in the super class method, issue warning; 4526 if (!Context.typesAreCompatible(T1, T2)) { 4527 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 4528 << T1 << T2; 4529 Diag(overridden->getLocation(), diag::note_previous_declaration); 4530 break; 4531 } 4532 } 4533 } 4534 } 4535 4536 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 4537 } 4538 4539 /// Merge type nullability from for a redeclaration of the same entity, 4540 /// producing the updated type of the redeclared entity. 4541 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc, 4542 QualType type, 4543 bool usesCSKeyword, 4544 SourceLocation prevLoc, 4545 QualType prevType, 4546 bool prevUsesCSKeyword) { 4547 // Determine the nullability of both types. 4548 auto nullability = type->getNullability(); 4549 auto prevNullability = prevType->getNullability(); 4550 4551 // Easy case: both have nullability. 4552 if (nullability.has_value() == prevNullability.has_value()) { 4553 // Neither has nullability; continue. 4554 if (!nullability) 4555 return type; 4556 4557 // The nullabilities are equivalent; do nothing. 4558 if (*nullability == *prevNullability) 4559 return type; 4560 4561 // Complain about mismatched nullability. 4562 S.Diag(loc, diag::err_nullability_conflicting) 4563 << DiagNullabilityKind(*nullability, usesCSKeyword) 4564 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword); 4565 return type; 4566 } 4567 4568 // If it's the redeclaration that has nullability, don't change anything. 4569 if (nullability) 4570 return type; 4571 4572 // Otherwise, provide the result with the same nullability. 4573 return S.Context.getAttributedType( 4574 AttributedType::getNullabilityAttrKind(*prevNullability), 4575 type, type); 4576 } 4577 4578 /// Merge information from the declaration of a method in the \@interface 4579 /// (or a category/extension) into the corresponding method in the 4580 /// @implementation (for a class or category). 4581 static void mergeInterfaceMethodToImpl(Sema &S, 4582 ObjCMethodDecl *method, 4583 ObjCMethodDecl *prevMethod) { 4584 // Merge the objc_requires_super attribute. 4585 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() && 4586 !method->hasAttr<ObjCRequiresSuperAttr>()) { 4587 // merge the attribute into implementation. 4588 method->addAttr( 4589 ObjCRequiresSuperAttr::CreateImplicit(S.Context, 4590 method->getLocation())); 4591 } 4592 4593 // Merge nullability of the result type. 4594 QualType newReturnType 4595 = mergeTypeNullabilityForRedecl( 4596 S, method->getReturnTypeSourceRange().getBegin(), 4597 method->getReturnType(), 4598 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4599 prevMethod->getReturnTypeSourceRange().getBegin(), 4600 prevMethod->getReturnType(), 4601 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4602 method->setReturnType(newReturnType); 4603 4604 // Handle each of the parameters. 4605 unsigned numParams = method->param_size(); 4606 unsigned numPrevParams = prevMethod->param_size(); 4607 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) { 4608 ParmVarDecl *param = method->param_begin()[i]; 4609 ParmVarDecl *prevParam = prevMethod->param_begin()[i]; 4610 4611 // Merge nullability. 4612 QualType newParamType 4613 = mergeTypeNullabilityForRedecl( 4614 S, param->getLocation(), param->getType(), 4615 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4616 prevParam->getLocation(), prevParam->getType(), 4617 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4618 param->setType(newParamType); 4619 } 4620 } 4621 4622 /// Verify that the method parameters/return value have types that are supported 4623 /// by the x86 target. 4624 static void checkObjCMethodX86VectorTypes(Sema &SemaRef, 4625 const ObjCMethodDecl *Method) { 4626 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() == 4627 llvm::Triple::x86 && 4628 "x86-specific check invoked for a different target"); 4629 SourceLocation Loc; 4630 QualType T; 4631 for (const ParmVarDecl *P : Method->parameters()) { 4632 if (P->getType()->isVectorType()) { 4633 Loc = P->getBeginLoc(); 4634 T = P->getType(); 4635 break; 4636 } 4637 } 4638 if (Loc.isInvalid()) { 4639 if (Method->getReturnType()->isVectorType()) { 4640 Loc = Method->getReturnTypeSourceRange().getBegin(); 4641 T = Method->getReturnType(); 4642 } else 4643 return; 4644 } 4645 4646 // Vector parameters/return values are not supported by objc_msgSend on x86 in 4647 // iOS < 9 and macOS < 10.11. 4648 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple(); 4649 VersionTuple AcceptedInVersion; 4650 if (Triple.getOS() == llvm::Triple::IOS) 4651 AcceptedInVersion = VersionTuple(/*Major=*/9); 4652 else if (Triple.isMacOSX()) 4653 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11); 4654 else 4655 return; 4656 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >= 4657 AcceptedInVersion) 4658 return; 4659 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type) 4660 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1 4661 : /*parameter*/ 0) 4662 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9"); 4663 } 4664 4665 static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) { 4666 if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() && 4667 CD->hasAttr<ObjCDirectMembersAttr>()) { 4668 Method->addAttr( 4669 ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation())); 4670 } 4671 } 4672 4673 static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl, 4674 ObjCMethodDecl *Method, 4675 ObjCImplDecl *ImpDecl = nullptr) { 4676 auto Sel = Method->getSelector(); 4677 bool isInstance = Method->isInstanceMethod(); 4678 bool diagnosed = false; 4679 4680 auto diagClash = [&](const ObjCMethodDecl *IMD) { 4681 if (diagnosed || IMD->isImplicit()) 4682 return; 4683 if (Method->isDirectMethod() || IMD->isDirectMethod()) { 4684 S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl) 4685 << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod() 4686 << Method->getDeclName(); 4687 S.Diag(IMD->getLocation(), diag::note_previous_declaration); 4688 diagnosed = true; 4689 } 4690 }; 4691 4692 // Look for any other declaration of this method anywhere we can see in this 4693 // compilation unit. 4694 // 4695 // We do not use IDecl->lookupMethod() because we have specific needs: 4696 // 4697 // - we absolutely do not need to walk protocols, because 4698 // diag::err_objc_direct_on_protocol has already been emitted 4699 // during parsing if there's a conflict, 4700 // 4701 // - when we do not find a match in a given @interface container, 4702 // we need to attempt looking it up in the @implementation block if the 4703 // translation unit sees it to find more clashes. 4704 4705 if (auto *IMD = IDecl->getMethod(Sel, isInstance)) 4706 diagClash(IMD); 4707 else if (auto *Impl = IDecl->getImplementation()) 4708 if (Impl != ImpDecl) 4709 if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance)) 4710 diagClash(IMD); 4711 4712 for (const auto *Cat : IDecl->visible_categories()) 4713 if (auto *IMD = Cat->getMethod(Sel, isInstance)) 4714 diagClash(IMD); 4715 else if (auto CatImpl = Cat->getImplementation()) 4716 if (CatImpl != ImpDecl) 4717 if (auto *IMD = Cat->getMethod(Sel, isInstance)) 4718 diagClash(IMD); 4719 } 4720 4721 Decl *Sema::ActOnMethodDeclaration( 4722 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc, 4723 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 4724 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 4725 // optional arguments. The number of types/arguments is obtained 4726 // from the Sel.getNumArgs(). 4727 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, 4728 unsigned CNumArgs, // c-style args 4729 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind, 4730 bool isVariadic, bool MethodDefinition) { 4731 // Make sure we can establish a context for the method. 4732 if (!CurContext->isObjCContainer()) { 4733 Diag(MethodLoc, diag::err_missing_method_context); 4734 return nullptr; 4735 } 4736 4737 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext); 4738 QualType resultDeclType; 4739 4740 bool HasRelatedResultType = false; 4741 TypeSourceInfo *ReturnTInfo = nullptr; 4742 if (ReturnType) { 4743 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo); 4744 4745 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 4746 return nullptr; 4747 4748 QualType bareResultType = resultDeclType; 4749 (void)AttributedType::stripOuterNullability(bareResultType); 4750 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType()); 4751 } else { // get the type for "id". 4752 resultDeclType = Context.getObjCIdType(); 4753 Diag(MethodLoc, diag::warn_missing_method_return_type) 4754 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 4755 } 4756 4757 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create( 4758 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext, 4759 MethodType == tok::minus, isVariadic, 4760 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false, 4761 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 4762 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional 4763 : ObjCMethodDecl::Required, 4764 HasRelatedResultType); 4765 4766 SmallVector<ParmVarDecl*, 16> Params; 4767 4768 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 4769 QualType ArgType; 4770 TypeSourceInfo *DI; 4771 4772 if (!ArgInfo[i].Type) { 4773 ArgType = Context.getObjCIdType(); 4774 DI = nullptr; 4775 } else { 4776 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 4777 } 4778 4779 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 4780 LookupOrdinaryName, forRedeclarationInCurContext()); 4781 LookupName(R, S); 4782 if (R.isSingleResult()) { 4783 NamedDecl *PrevDecl = R.getFoundDecl(); 4784 if (S->isDeclScope(PrevDecl)) { 4785 Diag(ArgInfo[i].NameLoc, 4786 (MethodDefinition ? diag::warn_method_param_redefinition 4787 : diag::warn_method_param_declaration)) 4788 << ArgInfo[i].Name; 4789 Diag(PrevDecl->getLocation(), 4790 diag::note_previous_declaration); 4791 } 4792 } 4793 4794 SourceLocation StartLoc = DI 4795 ? DI->getTypeLoc().getBeginLoc() 4796 : ArgInfo[i].NameLoc; 4797 4798 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 4799 ArgInfo[i].NameLoc, ArgInfo[i].Name, 4800 ArgType, DI, SC_None); 4801 4802 Param->setObjCMethodScopeInfo(i); 4803 4804 Param->setObjCDeclQualifier( 4805 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 4806 4807 // Apply the attributes to the parameter. 4808 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 4809 AddPragmaAttributes(TUScope, Param); 4810 4811 if (Param->hasAttr<BlocksAttr>()) { 4812 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 4813 Param->setInvalidDecl(); 4814 } 4815 S->AddDecl(Param); 4816 IdResolver.AddDecl(Param); 4817 4818 Params.push_back(Param); 4819 } 4820 4821 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 4822 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 4823 QualType ArgType = Param->getType(); 4824 if (ArgType.isNull()) 4825 ArgType = Context.getObjCIdType(); 4826 else 4827 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 4828 ArgType = Context.getAdjustedParameterType(ArgType); 4829 4830 Param->setDeclContext(ObjCMethod); 4831 Params.push_back(Param); 4832 } 4833 4834 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 4835 ObjCMethod->setObjCDeclQualifier( 4836 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 4837 4838 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 4839 AddPragmaAttributes(TUScope, ObjCMethod); 4840 4841 // Add the method now. 4842 const ObjCMethodDecl *PrevMethod = nullptr; 4843 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 4844 if (MethodType == tok::minus) { 4845 PrevMethod = ImpDecl->getInstanceMethod(Sel); 4846 ImpDecl->addInstanceMethod(ObjCMethod); 4847 } else { 4848 PrevMethod = ImpDecl->getClassMethod(Sel); 4849 ImpDecl->addClassMethod(ObjCMethod); 4850 } 4851 4852 // If this method overrides a previous @synthesize declaration, 4853 // register it with the property. Linear search through all 4854 // properties here, because the autosynthesized stub hasn't been 4855 // made visible yet, so it can be overridden by a later 4856 // user-specified implementation. 4857 for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) { 4858 if (auto *Setter = PropertyImpl->getSetterMethodDecl()) 4859 if (Setter->getSelector() == Sel && 4860 Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) { 4861 assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected"); 4862 PropertyImpl->setSetterMethodDecl(ObjCMethod); 4863 } 4864 if (auto *Getter = PropertyImpl->getGetterMethodDecl()) 4865 if (Getter->getSelector() == Sel && 4866 Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) { 4867 assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected"); 4868 PropertyImpl->setGetterMethodDecl(ObjCMethod); 4869 break; 4870 } 4871 } 4872 4873 // A method is either tagged direct explicitly, or inherits it from its 4874 // canonical declaration. 4875 // 4876 // We have to do the merge upfront and not in mergeInterfaceMethodToImpl() 4877 // because IDecl->lookupMethod() returns more possible matches than just 4878 // the canonical declaration. 4879 if (!ObjCMethod->isDirectMethod()) { 4880 const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl(); 4881 if (CanonicalMD->isDirectMethod()) { 4882 const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>(); 4883 ObjCMethod->addAttr( 4884 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation())); 4885 } 4886 } 4887 4888 // Merge information from the @interface declaration into the 4889 // @implementation. 4890 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) { 4891 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 4892 ObjCMethod->isInstanceMethod())) { 4893 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD); 4894 4895 // The Idecl->lookupMethod() above will find declarations for ObjCMethod 4896 // in one of these places: 4897 // 4898 // (1) the canonical declaration in an @interface container paired 4899 // with the ImplDecl, 4900 // (2) non canonical declarations in @interface not paired with the 4901 // ImplDecl for the same Class, 4902 // (3) any superclass container. 4903 // 4904 // Direct methods only allow for canonical declarations in the matching 4905 // container (case 1). 4906 // 4907 // Direct methods overriding a superclass declaration (case 3) is 4908 // handled during overrides checks in CheckObjCMethodOverrides(). 4909 // 4910 // We deal with same-class container mismatches (Case 2) here. 4911 if (IDecl == IMD->getClassInterface()) { 4912 auto diagContainerMismatch = [&] { 4913 int decl = 0, impl = 0; 4914 4915 if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext())) 4916 decl = Cat->IsClassExtension() ? 1 : 2; 4917 4918 if (isa<ObjCCategoryImplDecl>(ImpDecl)) 4919 impl = 1 + (decl != 0); 4920 4921 Diag(ObjCMethod->getLocation(), 4922 diag::err_objc_direct_impl_decl_mismatch) 4923 << decl << impl; 4924 Diag(IMD->getLocation(), diag::note_previous_declaration); 4925 }; 4926 4927 if (ObjCMethod->isDirectMethod()) { 4928 const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>(); 4929 if (ObjCMethod->getCanonicalDecl() != IMD) { 4930 diagContainerMismatch(); 4931 } else if (!IMD->isDirectMethod()) { 4932 Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl); 4933 Diag(IMD->getLocation(), diag::note_previous_declaration); 4934 } 4935 } else if (IMD->isDirectMethod()) { 4936 const auto *attr = IMD->getAttr<ObjCDirectAttr>(); 4937 if (ObjCMethod->getCanonicalDecl() != IMD) { 4938 diagContainerMismatch(); 4939 } else { 4940 ObjCMethod->addAttr( 4941 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation())); 4942 } 4943 } 4944 } 4945 4946 // Warn about defining -dealloc in a category. 4947 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() && 4948 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) { 4949 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 4950 << ObjCMethod->getDeclName(); 4951 } 4952 } else { 4953 mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod); 4954 checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl); 4955 } 4956 4957 // Warn if a method declared in a protocol to which a category or 4958 // extension conforms is non-escaping and the implementation's method is 4959 // escaping. 4960 for (auto *C : IDecl->visible_categories()) 4961 for (auto &P : C->protocols()) 4962 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(), 4963 ObjCMethod->isInstanceMethod())) { 4964 assert(ObjCMethod->parameters().size() == 4965 IMD->parameters().size() && 4966 "Methods have different number of parameters"); 4967 auto OI = IMD->param_begin(), OE = IMD->param_end(); 4968 auto NI = ObjCMethod->param_begin(); 4969 for (; OI != OE; ++OI, ++NI) 4970 diagnoseNoescape(*NI, *OI, C, P, *this); 4971 } 4972 } 4973 } else { 4974 if (!isa<ObjCProtocolDecl>(ClassDecl)) { 4975 mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod); 4976 4977 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 4978 if (!IDecl) 4979 IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface(); 4980 // For valid code, we should always know the primary interface 4981 // declaration by now, however for invalid code we'll keep parsing 4982 // but we won't find the primary interface and IDecl will be nil. 4983 if (IDecl) 4984 checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod); 4985 } 4986 4987 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 4988 } 4989 4990 if (PrevMethod) { 4991 // You can never have two method definitions with the same name. 4992 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 4993 << ObjCMethod->getDeclName(); 4994 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4995 ObjCMethod->setInvalidDecl(); 4996 return ObjCMethod; 4997 } 4998 4999 // If this Objective-C method does not have a related result type, but we 5000 // are allowed to infer related result types, try to do so based on the 5001 // method family. 5002 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 5003 if (!CurrentClass) { 5004 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 5005 CurrentClass = Cat->getClassInterface(); 5006 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 5007 CurrentClass = Impl->getClassInterface(); 5008 else if (ObjCCategoryImplDecl *CatImpl 5009 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 5010 CurrentClass = CatImpl->getClassInterface(); 5011 } 5012 5013 ResultTypeCompatibilityKind RTC 5014 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 5015 5016 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 5017 5018 bool ARCError = false; 5019 if (getLangOpts().ObjCAutoRefCount) 5020 ARCError = CheckARCMethodDecl(ObjCMethod); 5021 5022 // Infer the related result type when possible. 5023 if (!ARCError && RTC == Sema::RTC_Compatible && 5024 !ObjCMethod->hasRelatedResultType() && 5025 LangOpts.ObjCInferRelatedResultType) { 5026 bool InferRelatedResultType = false; 5027 switch (ObjCMethod->getMethodFamily()) { 5028 case OMF_None: 5029 case OMF_copy: 5030 case OMF_dealloc: 5031 case OMF_finalize: 5032 case OMF_mutableCopy: 5033 case OMF_release: 5034 case OMF_retainCount: 5035 case OMF_initialize: 5036 case OMF_performSelector: 5037 break; 5038 5039 case OMF_alloc: 5040 case OMF_new: 5041 InferRelatedResultType = ObjCMethod->isClassMethod(); 5042 break; 5043 5044 case OMF_init: 5045 case OMF_autorelease: 5046 case OMF_retain: 5047 case OMF_self: 5048 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 5049 break; 5050 } 5051 5052 if (InferRelatedResultType && 5053 !ObjCMethod->getReturnType()->isObjCIndependentClassType()) 5054 ObjCMethod->setRelatedResultType(); 5055 } 5056 5057 if (MethodDefinition && 5058 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 5059 checkObjCMethodX86VectorTypes(*this, ObjCMethod); 5060 5061 // + load method cannot have availability attributes. It get called on 5062 // startup, so it has to have the availability of the deployment target. 5063 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) { 5064 if (ObjCMethod->isClassMethod() && 5065 ObjCMethod->getSelector().getAsString() == "load") { 5066 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 5067 << 0; 5068 ObjCMethod->dropAttr<AvailabilityAttr>(); 5069 } 5070 } 5071 5072 // Insert the invisible arguments, self and _cmd! 5073 ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface()); 5074 5075 ActOnDocumentableDecl(ObjCMethod); 5076 5077 return ObjCMethod; 5078 } 5079 5080 bool Sema::CheckObjCDeclScope(Decl *D) { 5081 // Following is also an error. But it is caused by a missing @end 5082 // and diagnostic is issued elsewhere. 5083 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 5084 return false; 5085 5086 // If we switched context to translation unit while we are still lexically in 5087 // an objc container, it means the parser missed emitting an error. 5088 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 5089 return false; 5090 5091 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 5092 D->setInvalidDecl(); 5093 5094 return true; 5095 } 5096 5097 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 5098 /// instance variables of ClassName into Decls. 5099 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 5100 IdentifierInfo *ClassName, 5101 SmallVectorImpl<Decl*> &Decls) { 5102 // Check that ClassName is a valid class 5103 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 5104 if (!Class) { 5105 Diag(DeclStart, diag::err_undef_interface) << ClassName; 5106 return; 5107 } 5108 if (LangOpts.ObjCRuntime.isNonFragile()) { 5109 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 5110 return; 5111 } 5112 5113 // Collect the instance variables 5114 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5115 Context.DeepCollectObjCIvars(Class, true, Ivars); 5116 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 5117 for (unsigned i = 0; i < Ivars.size(); i++) { 5118 const FieldDecl* ID = Ivars[i]; 5119 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 5120 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 5121 /*FIXME: StartL=*/ID->getLocation(), 5122 ID->getLocation(), 5123 ID->getIdentifier(), ID->getType(), 5124 ID->getBitWidth()); 5125 Decls.push_back(FD); 5126 } 5127 5128 // Introduce all of these fields into the appropriate scope. 5129 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 5130 D != Decls.end(); ++D) { 5131 FieldDecl *FD = cast<FieldDecl>(*D); 5132 if (getLangOpts().CPlusPlus) 5133 PushOnScopeChains(FD, S); 5134 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 5135 Record->addDecl(FD); 5136 } 5137 } 5138 5139 /// Build a type-check a new Objective-C exception variable declaration. 5140 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 5141 SourceLocation StartLoc, 5142 SourceLocation IdLoc, 5143 IdentifierInfo *Id, 5144 bool Invalid) { 5145 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 5146 // duration shall not be qualified by an address-space qualifier." 5147 // Since all parameters have automatic store duration, they can not have 5148 // an address space. 5149 if (T.getAddressSpace() != LangAS::Default) { 5150 Diag(IdLoc, diag::err_arg_with_address_space); 5151 Invalid = true; 5152 } 5153 5154 // An @catch parameter must be an unqualified object pointer type; 5155 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 5156 if (Invalid) { 5157 // Don't do any further checking. 5158 } else if (T->isDependentType()) { 5159 // Okay: we don't know what this type will instantiate to. 5160 } else if (T->isObjCQualifiedIdType()) { 5161 Invalid = true; 5162 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 5163 } else if (T->isObjCIdType()) { 5164 // Okay: we don't know what this type will instantiate to. 5165 } else if (!T->isObjCObjectPointerType()) { 5166 Invalid = true; 5167 Diag(IdLoc, diag::err_catch_param_not_objc_type); 5168 } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) { 5169 Invalid = true; 5170 Diag(IdLoc, diag::err_catch_param_not_objc_type); 5171 } 5172 5173 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 5174 T, TInfo, SC_None); 5175 New->setExceptionVariable(true); 5176 5177 // In ARC, infer 'retaining' for variables of retainable type. 5178 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 5179 Invalid = true; 5180 5181 if (Invalid) 5182 New->setInvalidDecl(); 5183 return New; 5184 } 5185 5186 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 5187 const DeclSpec &DS = D.getDeclSpec(); 5188 5189 // We allow the "register" storage class on exception variables because 5190 // GCC did, but we drop it completely. Any other storage class is an error. 5191 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 5192 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 5193 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 5194 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5195 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 5196 << DeclSpec::getSpecifierName(SCS); 5197 } 5198 if (DS.isInlineSpecified()) 5199 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 5200 << getLangOpts().CPlusPlus17; 5201 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 5202 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5203 diag::err_invalid_thread) 5204 << DeclSpec::getSpecifierName(TSCS); 5205 D.getMutableDeclSpec().ClearStorageClassSpecs(); 5206 5207 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5208 5209 // Check that there are no default arguments inside the type of this 5210 // exception object (C++ only). 5211 if (getLangOpts().CPlusPlus) 5212 CheckExtraCXXDefaultArguments(D); 5213 5214 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5215 QualType ExceptionType = TInfo->getType(); 5216 5217 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 5218 D.getSourceRange().getBegin(), 5219 D.getIdentifierLoc(), 5220 D.getIdentifier(), 5221 D.isInvalidType()); 5222 5223 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 5224 if (D.getCXXScopeSpec().isSet()) { 5225 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 5226 << D.getCXXScopeSpec().getRange(); 5227 New->setInvalidDecl(); 5228 } 5229 5230 // Add the parameter declaration into this scope. 5231 S->AddDecl(New); 5232 if (D.getIdentifier()) 5233 IdResolver.AddDecl(New); 5234 5235 ProcessDeclAttributes(S, New, D); 5236 5237 if (New->hasAttr<BlocksAttr>()) 5238 Diag(New->getLocation(), diag::err_block_on_nonlocal); 5239 return New; 5240 } 5241 5242 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 5243 /// initialization. 5244 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 5245 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 5246 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 5247 Iv= Iv->getNextIvar()) { 5248 QualType QT = Context.getBaseElementType(Iv->getType()); 5249 if (QT->isRecordType()) 5250 Ivars.push_back(Iv); 5251 } 5252 } 5253 5254 void Sema::DiagnoseUseOfUnimplementedSelectors() { 5255 // Load referenced selectors from the external source. 5256 if (ExternalSource) { 5257 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 5258 ExternalSource->ReadReferencedSelectors(Sels); 5259 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 5260 ReferencedSelectors[Sels[I].first] = Sels[I].second; 5261 } 5262 5263 // Warning will be issued only when selector table is 5264 // generated (which means there is at lease one implementation 5265 // in the TU). This is to match gcc's behavior. 5266 if (ReferencedSelectors.empty() || 5267 !Context.AnyObjCImplementation()) 5268 return; 5269 for (auto &SelectorAndLocation : ReferencedSelectors) { 5270 Selector Sel = SelectorAndLocation.first; 5271 SourceLocation Loc = SelectorAndLocation.second; 5272 if (!LookupImplementedMethodInGlobalPool(Sel)) 5273 Diag(Loc, diag::warn_unimplemented_selector) << Sel; 5274 } 5275 } 5276 5277 ObjCIvarDecl * 5278 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 5279 const ObjCPropertyDecl *&PDecl) const { 5280 if (Method->isClassMethod()) 5281 return nullptr; 5282 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 5283 if (!IDecl) 5284 return nullptr; 5285 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 5286 /*shallowCategoryLookup=*/false, 5287 /*followSuper=*/false); 5288 if (!Method || !Method->isPropertyAccessor()) 5289 return nullptr; 5290 if ((PDecl = Method->findPropertyDecl())) 5291 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) { 5292 // property backing ivar must belong to property's class 5293 // or be a private ivar in class's implementation. 5294 // FIXME. fix the const-ness issue. 5295 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable( 5296 IV->getIdentifier()); 5297 return IV; 5298 } 5299 return nullptr; 5300 } 5301 5302 namespace { 5303 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 5304 /// accessor references the backing ivar. 5305 class UnusedBackingIvarChecker : 5306 public RecursiveASTVisitor<UnusedBackingIvarChecker> { 5307 public: 5308 Sema &S; 5309 const ObjCMethodDecl *Method; 5310 const ObjCIvarDecl *IvarD; 5311 bool AccessedIvar; 5312 bool InvokedSelfMethod; 5313 5314 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 5315 const ObjCIvarDecl *IvarD) 5316 : S(S), Method(Method), IvarD(IvarD), 5317 AccessedIvar(false), InvokedSelfMethod(false) { 5318 assert(IvarD); 5319 } 5320 5321 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 5322 if (E->getDecl() == IvarD) { 5323 AccessedIvar = true; 5324 return false; 5325 } 5326 return true; 5327 } 5328 5329 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 5330 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 5331 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 5332 InvokedSelfMethod = true; 5333 } 5334 return true; 5335 } 5336 }; 5337 } // end anonymous namespace 5338 5339 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 5340 const ObjCImplementationDecl *ImplD) { 5341 if (S->hasUnrecoverableErrorOccurred()) 5342 return; 5343 5344 for (const auto *CurMethod : ImplD->instance_methods()) { 5345 unsigned DIAG = diag::warn_unused_property_backing_ivar; 5346 SourceLocation Loc = CurMethod->getLocation(); 5347 if (Diags.isIgnored(DIAG, Loc)) 5348 continue; 5349 5350 const ObjCPropertyDecl *PDecl; 5351 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 5352 if (!IV) 5353 continue; 5354 5355 if (CurMethod->isSynthesizedAccessorStub()) 5356 continue; 5357 5358 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 5359 Checker.TraverseStmt(CurMethod->getBody()); 5360 if (Checker.AccessedIvar) 5361 continue; 5362 5363 // Do not issue this warning if backing ivar is used somewhere and accessor 5364 // implementation makes a self call. This is to prevent false positive in 5365 // cases where the ivar is accessed by another method that the accessor 5366 // delegates to. 5367 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 5368 Diag(Loc, DIAG) << IV; 5369 Diag(PDecl->getLocation(), diag::note_property_declare); 5370 } 5371 } 5372 } 5373