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