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 "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/DataRecursiveASTVisitor.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Sema/DeclSpec.h" 24 #include "clang/Sema/ExternalSemaSource.h" 25 #include "clang/Sema/Lookup.h" 26 #include "clang/Sema/Scope.h" 27 #include "clang/Sema/ScopeInfo.h" 28 #include "llvm/ADT/DenseSet.h" 29 30 using namespace clang; 31 32 /// Check whether the given method, which must be in the 'init' 33 /// family, is a valid member of that family. 34 /// 35 /// \param receiverTypeIfCall - if null, check this as if declaring it; 36 /// if non-null, check this as if making a call to it with the given 37 /// receiver type 38 /// 39 /// \return true to indicate that there was an error and appropriate 40 /// actions were taken 41 bool Sema::checkInitMethod(ObjCMethodDecl *method, 42 QualType receiverTypeIfCall) { 43 if (method->isInvalidDecl()) return true; 44 45 // This castAs is safe: methods that don't return an object 46 // pointer won't be inferred as inits and will reject an explicit 47 // objc_method_family(init). 48 49 // We ignore protocols here. Should we? What about Class? 50 51 const ObjCObjectType *result = 52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType(); 53 54 if (result->isObjCId()) { 55 return false; 56 } else if (result->isObjCClass()) { 57 // fall through: always an error 58 } else { 59 ObjCInterfaceDecl *resultClass = result->getInterface(); 60 assert(resultClass && "unexpected object type!"); 61 62 // It's okay for the result type to still be a forward declaration 63 // if we're checking an interface declaration. 64 if (!resultClass->hasDefinition()) { 65 if (receiverTypeIfCall.isNull() && 66 !isa<ObjCImplementationDecl>(method->getDeclContext())) 67 return false; 68 69 // Otherwise, we try to compare class types. 70 } else { 71 // If this method was declared in a protocol, we can't check 72 // anything unless we have a receiver type that's an interface. 73 const ObjCInterfaceDecl *receiverClass = nullptr; 74 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 75 if (receiverTypeIfCall.isNull()) 76 return false; 77 78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 79 ->getInterfaceDecl(); 80 81 // This can be null for calls to e.g. id<Foo>. 82 if (!receiverClass) return false; 83 } else { 84 receiverClass = method->getClassInterface(); 85 assert(receiverClass && "method not associated with a class!"); 86 } 87 88 // If either class is a subclass of the other, it's fine. 89 if (receiverClass->isSuperClassOf(resultClass) || 90 resultClass->isSuperClassOf(receiverClass)) 91 return false; 92 } 93 } 94 95 SourceLocation loc = method->getLocation(); 96 97 // If we're in a system header, and this is not a call, just make 98 // the method unusable. 99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 100 method->addAttr(UnavailableAttr::CreateImplicit(Context, 101 "init method returns a type unrelated to its receiver type", 102 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 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() != 161 Overridden->hasAttr<NSReturnsRetainedAttr>())) { 162 Diag(NewMethod->getLocation(), 163 diag::err_nsreturns_retained_attribute_mismatch) << 1; 164 Diag(Overridden->getLocation(), diag::note_previous_decl) 165 << "method"; 166 } 167 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() != 168 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) { 169 Diag(NewMethod->getLocation(), 170 diag::err_nsreturns_retained_attribute_mismatch) << 0; 171 Diag(Overridden->getLocation(), diag::note_previous_decl) 172 << "method"; 173 } 174 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 175 oe = Overridden->param_end(); 176 for (ObjCMethodDecl::param_iterator 177 ni = NewMethod->param_begin(), ne = NewMethod->param_end(); 178 ni != ne && oi != oe; ++ni, ++oi) { 179 const ParmVarDecl *oldDecl = (*oi); 180 ParmVarDecl *newDecl = (*ni); 181 if (newDecl->hasAttr<NSConsumedAttr>() != 182 oldDecl->hasAttr<NSConsumedAttr>()) { 183 Diag(newDecl->getLocation(), 184 diag::err_nsconsumed_attribute_mismatch); 185 Diag(oldDecl->getLocation(), diag::note_previous_decl) 186 << "parameter"; 187 } 188 } 189 } 190 } 191 192 /// \brief Check a method declaration for compatibility with the Objective-C 193 /// ARC conventions. 194 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { 195 ObjCMethodFamily family = method->getMethodFamily(); 196 switch (family) { 197 case OMF_None: 198 case OMF_finalize: 199 case OMF_retain: 200 case OMF_release: 201 case OMF_autorelease: 202 case OMF_retainCount: 203 case OMF_self: 204 case OMF_initialize: 205 case OMF_performSelector: 206 return false; 207 208 case OMF_dealloc: 209 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) { 210 SourceRange ResultTypeRange = method->getReturnTypeSourceRange(); 211 if (ResultTypeRange.isInvalid()) 212 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 213 << method->getReturnType() 214 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 215 else 216 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 217 << method->getReturnType() 218 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 219 return true; 220 } 221 return false; 222 223 case OMF_init: 224 // If the method doesn't obey the init rules, don't bother annotating it. 225 if (checkInitMethod(method, QualType())) 226 return true; 227 228 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context)); 229 230 // Don't add a second copy of this attribute, but otherwise don't 231 // let it be suppressed. 232 if (method->hasAttr<NSReturnsRetainedAttr>()) 233 return false; 234 break; 235 236 case OMF_alloc: 237 case OMF_copy: 238 case OMF_mutableCopy: 239 case OMF_new: 240 if (method->hasAttr<NSReturnsRetainedAttr>() || 241 method->hasAttr<NSReturnsNotRetainedAttr>() || 242 method->hasAttr<NSReturnsAutoreleasedAttr>()) 243 return false; 244 break; 245 } 246 247 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context)); 248 return false; 249 } 250 251 static void DiagnoseObjCImplementedDeprecations(Sema &S, 252 NamedDecl *ND, 253 SourceLocation ImplLoc, 254 int select) { 255 if (ND && ND->isDeprecated()) { 256 S.Diag(ImplLoc, diag::warn_deprecated_def) << select; 257 if (select == 0) 258 S.Diag(ND->getLocation(), diag::note_method_declared_at) 259 << ND->getDeclName(); 260 else 261 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class"; 262 } 263 } 264 265 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 266 /// pool. 267 void Sema::AddAnyMethodToGlobalPool(Decl *D) { 268 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 269 270 // If we don't have a valid method decl, simply return. 271 if (!MDecl) 272 return; 273 if (MDecl->isInstanceMethod()) 274 AddInstanceMethodToGlobalPool(MDecl, true); 275 else 276 AddFactoryMethodToGlobalPool(MDecl, true); 277 } 278 279 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer 280 /// has explicit ownership attribute; false otherwise. 281 static bool 282 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { 283 QualType T = Param->getType(); 284 285 if (const PointerType *PT = T->getAs<PointerType>()) { 286 T = PT->getPointeeType(); 287 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 288 T = RT->getPointeeType(); 289 } else { 290 return true; 291 } 292 293 // If we have a lifetime qualifier, but it's local, we must have 294 // inferred it. So, it is implicit. 295 return !T.getLocalQualifiers().hasObjCLifetime(); 296 } 297 298 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 299 /// and user declared, in the method definition's AST. 300 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 301 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused"); 302 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 303 304 // If we don't have a valid method decl, simply return. 305 if (!MDecl) 306 return; 307 308 // Allow all of Sema to see that we are entering a method definition. 309 PushDeclContext(FnBodyScope, MDecl); 310 PushFunctionScope(); 311 312 // Create Decl objects for each parameter, entrring them in the scope for 313 // binding to their use. 314 315 // Insert the invisible arguments, self and _cmd! 316 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 317 318 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 319 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 320 321 // The ObjC parser requires parameter names so there's no need to check. 322 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(), 323 /*CheckParameterNames=*/false); 324 325 // Introduce all of the other parameters into this scope. 326 for (auto *Param : MDecl->params()) { 327 if (!Param->isInvalidDecl() && 328 getLangOpts().ObjCAutoRefCount && 329 !HasExplicitOwnershipAttr(*this, Param)) 330 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << 331 Param->getType(); 332 333 if (Param->getIdentifier()) 334 PushOnScopeChains(Param, FnBodyScope); 335 } 336 337 // In ARC, disallow definition of retain/release/autorelease/retainCount 338 if (getLangOpts().ObjCAutoRefCount) { 339 switch (MDecl->getMethodFamily()) { 340 case OMF_retain: 341 case OMF_retainCount: 342 case OMF_release: 343 case OMF_autorelease: 344 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 345 << 0 << MDecl->getSelector(); 346 break; 347 348 case OMF_None: 349 case OMF_dealloc: 350 case OMF_finalize: 351 case OMF_alloc: 352 case OMF_init: 353 case OMF_mutableCopy: 354 case OMF_copy: 355 case OMF_new: 356 case OMF_self: 357 case OMF_initialize: 358 case OMF_performSelector: 359 break; 360 } 361 } 362 363 // Warn on deprecated methods under -Wdeprecated-implementations, 364 // and prepare for warning on missing super calls. 365 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 366 ObjCMethodDecl *IMD = 367 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); 368 369 if (IMD) { 370 ObjCImplDecl *ImplDeclOfMethodDef = 371 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); 372 ObjCContainerDecl *ContDeclOfMethodDecl = 373 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); 374 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr; 375 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) 376 ImplDeclOfMethodDecl = OID->getImplementation(); 377 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) { 378 if (CD->IsClassExtension()) { 379 if (ObjCInterfaceDecl *OID = CD->getClassInterface()) 380 ImplDeclOfMethodDecl = OID->getImplementation(); 381 } else 382 ImplDeclOfMethodDecl = CD->getImplementation(); 383 } 384 // No need to issue deprecated warning if deprecated mehod in class/category 385 // is being implemented in its own implementation (no overriding is involved). 386 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef) 387 DiagnoseObjCImplementedDeprecations(*this, 388 dyn_cast<NamedDecl>(IMD), 389 MDecl->getLocation(), 0); 390 } 391 392 if (MDecl->getMethodFamily() == OMF_init) { 393 if (MDecl->isDesignatedInitializerForTheInterface()) { 394 getCurFunction()->ObjCIsDesignatedInit = true; 395 getCurFunction()->ObjCWarnForNoDesignatedInitChain = 396 IC->getSuperClass() != nullptr; 397 } else if (IC->hasDesignatedInitializers()) { 398 getCurFunction()->ObjCIsSecondaryInit = true; 399 getCurFunction()->ObjCWarnForNoInitDelegation = true; 400 } 401 } 402 403 // If this is "dealloc" or "finalize", set some bit here. 404 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 405 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 406 // Only do this if the current class actually has a superclass. 407 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) { 408 ObjCMethodFamily Family = MDecl->getMethodFamily(); 409 if (Family == OMF_dealloc) { 410 if (!(getLangOpts().ObjCAutoRefCount || 411 getLangOpts().getGC() == LangOptions::GCOnly)) 412 getCurFunction()->ObjCShouldCallSuper = true; 413 414 } else if (Family == OMF_finalize) { 415 if (Context.getLangOpts().getGC() != LangOptions::NonGC) 416 getCurFunction()->ObjCShouldCallSuper = true; 417 418 } else { 419 const ObjCMethodDecl *SuperMethod = 420 SuperClass->lookupMethod(MDecl->getSelector(), 421 MDecl->isInstanceMethod()); 422 getCurFunction()->ObjCShouldCallSuper = 423 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); 424 } 425 } 426 } 427 } 428 429 namespace { 430 431 // Callback to only accept typo corrections that are Objective-C classes. 432 // If an ObjCInterfaceDecl* is given to the constructor, then the validation 433 // function will reject corrections to that class. 434 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback { 435 public: 436 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {} 437 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl) 438 : CurrentIDecl(IDecl) {} 439 440 bool ValidateCandidate(const TypoCorrection &candidate) override { 441 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>(); 442 return ID && !declaresSameEntity(ID, CurrentIDecl); 443 } 444 445 private: 446 ObjCInterfaceDecl *CurrentIDecl; 447 }; 448 449 } 450 451 Decl *Sema:: 452 ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 453 IdentifierInfo *ClassName, SourceLocation ClassLoc, 454 IdentifierInfo *SuperName, SourceLocation SuperLoc, 455 Decl * const *ProtoRefs, unsigned NumProtoRefs, 456 const SourceLocation *ProtoLocs, 457 SourceLocation EndProtoLoc, AttributeList *AttrList) { 458 assert(ClassName && "Missing class identifier"); 459 460 // Check for another declaration kind with the same name. 461 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc, 462 LookupOrdinaryName, ForRedeclaration); 463 464 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 465 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 466 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 467 } 468 469 // Create a declaration to describe this @interface. 470 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 471 472 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 473 // A previous decl with a different name is because of 474 // @compatibility_alias, for example: 475 // \code 476 // @class NewImage; 477 // @compatibility_alias OldImage NewImage; 478 // \endcode 479 // A lookup for 'OldImage' will return the 'NewImage' decl. 480 // 481 // In such a case use the real declaration name, instead of the alias one, 482 // otherwise we will break IdentifierResolver and redecls-chain invariants. 483 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 484 // has been aliased. 485 ClassName = PrevIDecl->getIdentifier(); 486 } 487 488 ObjCInterfaceDecl *IDecl 489 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, 490 PrevIDecl, ClassLoc); 491 492 if (PrevIDecl) { 493 // Class already seen. Was it a definition? 494 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 495 Diag(AtInterfaceLoc, diag::err_duplicate_class_def) 496 << PrevIDecl->getDeclName(); 497 Diag(Def->getLocation(), diag::note_previous_definition); 498 IDecl->setInvalidDecl(); 499 } 500 } 501 502 if (AttrList) 503 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 504 PushOnScopeChains(IDecl, TUScope); 505 506 // Start the definition of this class. If we're in a redefinition case, there 507 // may already be a definition, so we'll end up adding to it. 508 if (!IDecl->hasDefinition()) 509 IDecl->startDefinition(); 510 511 if (SuperName) { 512 // Check if a different kind of symbol declared in this scope. 513 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 514 LookupOrdinaryName); 515 516 if (!PrevDecl) { 517 // Try to correct for a typo in the superclass name without correcting 518 // to the class we're defining. 519 if (TypoCorrection Corrected = 520 CorrectTypo(DeclarationNameInfo(SuperName, SuperLoc), 521 LookupOrdinaryName, TUScope, nullptr, 522 llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl), 523 CTK_ErrorRecovery)) { 524 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest) 525 << SuperName << ClassName); 526 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 527 } 528 } 529 530 if (declaresSameEntity(PrevDecl, IDecl)) { 531 Diag(SuperLoc, diag::err_recursive_superclass) 532 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 533 IDecl->setEndOfDefinitionLoc(ClassLoc); 534 } else { 535 ObjCInterfaceDecl *SuperClassDecl = 536 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 537 538 // Diagnose classes that inherit from deprecated classes. 539 if (SuperClassDecl) 540 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 541 542 if (PrevDecl && !SuperClassDecl) { 543 // The previous declaration was not a class decl. Check if we have a 544 // typedef. If we do, get the underlying class type. 545 if (const TypedefNameDecl *TDecl = 546 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 547 QualType T = TDecl->getUnderlyingType(); 548 if (T->isObjCObjectType()) { 549 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 550 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 551 // This handles the following case: 552 // @interface NewI @end 553 // typedef NewI DeprI __attribute__((deprecated("blah"))) 554 // @interface SI : DeprI /* warn here */ @end 555 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc); 556 } 557 } 558 } 559 560 // This handles the following case: 561 // 562 // typedef int SuperClass; 563 // @interface MyClass : SuperClass {} @end 564 // 565 if (!SuperClassDecl) { 566 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 567 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 568 } 569 } 570 571 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 572 if (!SuperClassDecl) 573 Diag(SuperLoc, diag::err_undef_superclass) 574 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 575 else if (RequireCompleteType(SuperLoc, 576 Context.getObjCInterfaceType(SuperClassDecl), 577 diag::err_forward_superclass, 578 SuperClassDecl->getDeclName(), 579 ClassName, 580 SourceRange(AtInterfaceLoc, ClassLoc))) { 581 SuperClassDecl = nullptr; 582 } 583 } 584 IDecl->setSuperClass(SuperClassDecl); 585 IDecl->setSuperClassLoc(SuperLoc); 586 IDecl->setEndOfDefinitionLoc(SuperLoc); 587 } 588 } else { // we have a root class. 589 IDecl->setEndOfDefinitionLoc(ClassLoc); 590 } 591 592 // Check then save referenced protocols. 593 if (NumProtoRefs) { 594 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 595 ProtoLocs, Context); 596 IDecl->setEndOfDefinitionLoc(EndProtoLoc); 597 } 598 599 CheckObjCDeclScope(IDecl); 600 return ActOnObjCContainerStartDefinition(IDecl); 601 } 602 603 /// ActOnTypedefedProtocols - this action finds protocol list as part of the 604 /// typedef'ed use for a qualified super class and adds them to the list 605 /// of the protocols. 606 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 607 IdentifierInfo *SuperName, 608 SourceLocation SuperLoc) { 609 if (!SuperName) 610 return; 611 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 612 LookupOrdinaryName); 613 if (!IDecl) 614 return; 615 616 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { 617 QualType T = TDecl->getUnderlyingType(); 618 if (T->isObjCObjectType()) 619 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) 620 for (auto *I : OPT->quals()) 621 ProtocolRefs.push_back(I); 622 } 623 } 624 625 /// ActOnCompatibilityAlias - this action is called after complete parsing of 626 /// a \@compatibility_alias declaration. It sets up the alias relationships. 627 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc, 628 IdentifierInfo *AliasName, 629 SourceLocation AliasLocation, 630 IdentifierInfo *ClassName, 631 SourceLocation ClassLocation) { 632 // Look for previous declaration of alias name 633 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation, 634 LookupOrdinaryName, ForRedeclaration); 635 if (ADecl) { 636 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 637 Diag(ADecl->getLocation(), diag::note_previous_declaration); 638 return nullptr; 639 } 640 // Check for class declaration 641 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 642 LookupOrdinaryName, ForRedeclaration); 643 if (const TypedefNameDecl *TDecl = 644 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 645 QualType T = TDecl->getUnderlyingType(); 646 if (T->isObjCObjectType()) { 647 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 648 ClassName = IDecl->getIdentifier(); 649 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 650 LookupOrdinaryName, ForRedeclaration); 651 } 652 } 653 } 654 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 655 if (!CDecl) { 656 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 657 if (CDeclU) 658 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 659 return nullptr; 660 } 661 662 // Everything checked out, instantiate a new alias declaration AST. 663 ObjCCompatibleAliasDecl *AliasDecl = 664 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 665 666 if (!CheckObjCDeclScope(AliasDecl)) 667 PushOnScopeChains(AliasDecl, TUScope); 668 669 return AliasDecl; 670 } 671 672 bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 673 IdentifierInfo *PName, 674 SourceLocation &Ploc, SourceLocation PrevLoc, 675 const ObjCList<ObjCProtocolDecl> &PList) { 676 677 bool res = false; 678 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 679 E = PList.end(); I != E; ++I) { 680 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 681 Ploc)) { 682 if (PDecl->getIdentifier() == PName) { 683 Diag(Ploc, diag::err_protocol_has_circular_dependency); 684 Diag(PrevLoc, diag::note_previous_definition); 685 res = true; 686 } 687 688 if (!PDecl->hasDefinition()) 689 continue; 690 691 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 692 PDecl->getLocation(), PDecl->getReferencedProtocols())) 693 res = true; 694 } 695 } 696 return res; 697 } 698 699 Decl * 700 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, 701 IdentifierInfo *ProtocolName, 702 SourceLocation ProtocolLoc, 703 Decl * const *ProtoRefs, 704 unsigned NumProtoRefs, 705 const SourceLocation *ProtoLocs, 706 SourceLocation EndProtoLoc, 707 AttributeList *AttrList) { 708 bool err = false; 709 // FIXME: Deal with AttrList. 710 assert(ProtocolName && "Missing protocol identifier"); 711 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc, 712 ForRedeclaration); 713 ObjCProtocolDecl *PDecl = nullptr; 714 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) { 715 // If we already have a definition, complain. 716 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 717 Diag(Def->getLocation(), diag::note_previous_definition); 718 719 // Create a new protocol that is completely distinct from previous 720 // declarations, and do not make this protocol available for name lookup. 721 // That way, we'll end up completely ignoring the duplicate. 722 // FIXME: Can we turn this into an error? 723 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 724 ProtocolLoc, AtProtoInterfaceLoc, 725 /*PrevDecl=*/nullptr); 726 PDecl->startDefinition(); 727 } else { 728 if (PrevDecl) { 729 // Check for circular dependencies among protocol declarations. This can 730 // only happen if this protocol was forward-declared. 731 ObjCList<ObjCProtocolDecl> PList; 732 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 733 err = CheckForwardProtocolDeclarationForCircularDependency( 734 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList); 735 } 736 737 // Create the new declaration. 738 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 739 ProtocolLoc, AtProtoInterfaceLoc, 740 /*PrevDecl=*/PrevDecl); 741 742 PushOnScopeChains(PDecl, TUScope); 743 PDecl->startDefinition(); 744 } 745 746 if (AttrList) 747 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 748 749 // Merge attributes from previous declarations. 750 if (PrevDecl) 751 mergeDeclAttributes(PDecl, PrevDecl); 752 753 if (!err && NumProtoRefs ) { 754 /// Check then save referenced protocols. 755 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 756 ProtoLocs, Context); 757 } 758 759 CheckObjCDeclScope(PDecl); 760 return ActOnObjCContainerStartDefinition(PDecl); 761 } 762 763 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl, 764 ObjCProtocolDecl *&UndefinedProtocol) { 765 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) { 766 UndefinedProtocol = PDecl; 767 return true; 768 } 769 770 for (auto *PI : PDecl->protocols()) 771 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) { 772 UndefinedProtocol = PI; 773 return true; 774 } 775 return false; 776 } 777 778 /// FindProtocolDeclaration - This routine looks up protocols and 779 /// issues an error if they are not declared. It returns list of 780 /// protocol declarations in its 'Protocols' argument. 781 void 782 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, 783 const IdentifierLocPair *ProtocolId, 784 unsigned NumProtocols, 785 SmallVectorImpl<Decl *> &Protocols) { 786 for (unsigned i = 0; i != NumProtocols; ++i) { 787 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first, 788 ProtocolId[i].second); 789 if (!PDecl) { 790 TypoCorrection Corrected = CorrectTypo( 791 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second), 792 LookupObjCProtocolName, TUScope, nullptr, 793 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(), 794 CTK_ErrorRecovery); 795 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) 796 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest) 797 << ProtocolId[i].first); 798 } 799 800 if (!PDecl) { 801 Diag(ProtocolId[i].second, diag::err_undeclared_protocol) 802 << ProtocolId[i].first; 803 continue; 804 } 805 // If this is a forward protocol declaration, get its definition. 806 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) 807 PDecl = PDecl->getDefinition(); 808 809 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second); 810 811 // If this is a forward declaration and we are supposed to warn in this 812 // case, do it. 813 // FIXME: Recover nicely in the hidden case. 814 ObjCProtocolDecl *UndefinedProtocol; 815 816 if (WarnOnDeclarations && 817 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) { 818 Diag(ProtocolId[i].second, diag::warn_undef_protocolref) 819 << ProtocolId[i].first; 820 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined) 821 << UndefinedProtocol; 822 } 823 Protocols.push_back(PDecl); 824 } 825 } 826 827 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 828 /// a class method in its extension. 829 /// 830 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 831 ObjCInterfaceDecl *ID) { 832 if (!ID) 833 return; // Possibly due to previous error 834 835 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 836 for (auto *MD : ID->methods()) 837 MethodMap[MD->getSelector()] = MD; 838 839 if (MethodMap.empty()) 840 return; 841 for (const auto *Method : CAT->methods()) { 842 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 843 if (PrevMethod && 844 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) && 845 !MatchTwoMethodDeclarations(Method, PrevMethod)) { 846 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 847 << Method->getDeclName(); 848 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 849 } 850 } 851 } 852 853 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo; 854 Sema::DeclGroupPtrTy 855 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 856 const IdentifierLocPair *IdentList, 857 unsigned NumElts, 858 AttributeList *attrList) { 859 SmallVector<Decl *, 8> DeclsInGroup; 860 for (unsigned i = 0; i != NumElts; ++i) { 861 IdentifierInfo *Ident = IdentList[i].first; 862 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second, 863 ForRedeclaration); 864 ObjCProtocolDecl *PDecl 865 = ObjCProtocolDecl::Create(Context, CurContext, Ident, 866 IdentList[i].second, AtProtocolLoc, 867 PrevDecl); 868 869 PushOnScopeChains(PDecl, TUScope); 870 CheckObjCDeclScope(PDecl); 871 872 if (attrList) 873 ProcessDeclAttributeList(TUScope, PDecl, attrList); 874 875 if (PrevDecl) 876 mergeDeclAttributes(PDecl, PrevDecl); 877 878 DeclsInGroup.push_back(PDecl); 879 } 880 881 return BuildDeclaratorGroup(DeclsInGroup, false); 882 } 883 884 Decl *Sema:: 885 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 886 IdentifierInfo *ClassName, SourceLocation ClassLoc, 887 IdentifierInfo *CategoryName, 888 SourceLocation CategoryLoc, 889 Decl * const *ProtoRefs, 890 unsigned NumProtoRefs, 891 const SourceLocation *ProtoLocs, 892 SourceLocation EndProtoLoc) { 893 ObjCCategoryDecl *CDecl; 894 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 895 896 /// Check that class of this category is already completely declared. 897 898 if (!IDecl 899 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 900 diag::err_category_forward_interface, 901 CategoryName == nullptr)) { 902 // Create an invalid ObjCCategoryDecl to serve as context for 903 // the enclosing method declarations. We mark the decl invalid 904 // to make it clear that this isn't a valid AST. 905 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 906 ClassLoc, CategoryLoc, CategoryName,IDecl); 907 CDecl->setInvalidDecl(); 908 CurContext->addDecl(CDecl); 909 910 if (!IDecl) 911 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 912 return ActOnObjCContainerStartDefinition(CDecl); 913 } 914 915 if (!CategoryName && IDecl->getImplementation()) { 916 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 917 Diag(IDecl->getImplementation()->getLocation(), 918 diag::note_implementation_declared); 919 } 920 921 if (CategoryName) { 922 /// Check for duplicate interface declaration for this category 923 if (ObjCCategoryDecl *Previous 924 = IDecl->FindCategoryDeclaration(CategoryName)) { 925 // Class extensions can be declared multiple times, categories cannot. 926 Diag(CategoryLoc, diag::warn_dup_category_def) 927 << ClassName << CategoryName; 928 Diag(Previous->getLocation(), diag::note_previous_definition); 929 } 930 } 931 932 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 933 ClassLoc, CategoryLoc, CategoryName, IDecl); 934 // FIXME: PushOnScopeChains? 935 CurContext->addDecl(CDecl); 936 937 if (NumProtoRefs) { 938 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 939 ProtoLocs, Context); 940 // Protocols in the class extension belong to the class. 941 if (CDecl->IsClassExtension()) 942 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 943 NumProtoRefs, Context); 944 } 945 946 CheckObjCDeclScope(CDecl); 947 return ActOnObjCContainerStartDefinition(CDecl); 948 } 949 950 /// ActOnStartCategoryImplementation - Perform semantic checks on the 951 /// category implementation declaration and build an ObjCCategoryImplDecl 952 /// object. 953 Decl *Sema::ActOnStartCategoryImplementation( 954 SourceLocation AtCatImplLoc, 955 IdentifierInfo *ClassName, SourceLocation ClassLoc, 956 IdentifierInfo *CatName, SourceLocation CatLoc) { 957 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 958 ObjCCategoryDecl *CatIDecl = nullptr; 959 if (IDecl && IDecl->hasDefinition()) { 960 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 961 if (!CatIDecl) { 962 // Category @implementation with no corresponding @interface. 963 // Create and install one. 964 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc, 965 ClassLoc, CatLoc, 966 CatName, IDecl); 967 CatIDecl->setImplicit(); 968 } 969 } 970 971 ObjCCategoryImplDecl *CDecl = 972 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl, 973 ClassLoc, AtCatImplLoc, CatLoc); 974 /// Check that class of this category is already completely declared. 975 if (!IDecl) { 976 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 977 CDecl->setInvalidDecl(); 978 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 979 diag::err_undef_interface)) { 980 CDecl->setInvalidDecl(); 981 } 982 983 // FIXME: PushOnScopeChains? 984 CurContext->addDecl(CDecl); 985 986 // If the interface is deprecated/unavailable, warn/error about it. 987 if (IDecl) 988 DiagnoseUseOfDecl(IDecl, ClassLoc); 989 990 /// Check that CatName, category name, is not used in another implementation. 991 if (CatIDecl) { 992 if (CatIDecl->getImplementation()) { 993 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 994 << CatName; 995 Diag(CatIDecl->getImplementation()->getLocation(), 996 diag::note_previous_definition); 997 CDecl->setInvalidDecl(); 998 } else { 999 CatIDecl->setImplementation(CDecl); 1000 // Warn on implementating category of deprecated class under 1001 // -Wdeprecated-implementations flag. 1002 DiagnoseObjCImplementedDeprecations(*this, 1003 dyn_cast<NamedDecl>(IDecl), 1004 CDecl->getLocation(), 2); 1005 } 1006 } 1007 1008 CheckObjCDeclScope(CDecl); 1009 return ActOnObjCContainerStartDefinition(CDecl); 1010 } 1011 1012 Decl *Sema::ActOnStartClassImplementation( 1013 SourceLocation AtClassImplLoc, 1014 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1015 IdentifierInfo *SuperClassname, 1016 SourceLocation SuperClassLoc) { 1017 ObjCInterfaceDecl *IDecl = nullptr; 1018 // Check for another declaration kind with the same name. 1019 NamedDecl *PrevDecl 1020 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 1021 ForRedeclaration); 1022 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1023 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 1024 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1025 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 1026 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1027 diag::warn_undef_interface); 1028 } else { 1029 // We did not find anything with the name ClassName; try to correct for 1030 // typos in the class name. 1031 TypoCorrection Corrected = CorrectTypo( 1032 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope, 1033 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError); 1034 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1035 // Suggest the (potentially) correct interface name. Don't provide a 1036 // code-modification hint or use the typo name for recovery, because 1037 // this is just a warning. The program may actually be correct. 1038 diagnoseTypo(Corrected, 1039 PDiag(diag::warn_undef_interface_suggest) << ClassName, 1040 /*ErrorRecovery*/false); 1041 } else { 1042 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 1043 } 1044 } 1045 1046 // Check that super class name is valid class name 1047 ObjCInterfaceDecl *SDecl = nullptr; 1048 if (SuperClassname) { 1049 // Check if a different kind of symbol declared in this scope. 1050 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 1051 LookupOrdinaryName); 1052 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1053 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 1054 << SuperClassname; 1055 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1056 } else { 1057 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 1058 if (SDecl && !SDecl->hasDefinition()) 1059 SDecl = nullptr; 1060 if (!SDecl) 1061 Diag(SuperClassLoc, diag::err_undef_superclass) 1062 << SuperClassname << ClassName; 1063 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) { 1064 // This implementation and its interface do not have the same 1065 // super class. 1066 Diag(SuperClassLoc, diag::err_conflicting_super_class) 1067 << SDecl->getDeclName(); 1068 Diag(SDecl->getLocation(), diag::note_previous_definition); 1069 } 1070 } 1071 } 1072 1073 if (!IDecl) { 1074 // Legacy case of @implementation with no corresponding @interface. 1075 // Build, chain & install the interface decl into the identifier. 1076 1077 // FIXME: Do we support attributes on the @implementation? If so we should 1078 // copy them over. 1079 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 1080 ClassName, /*PrevDecl=*/nullptr, ClassLoc, 1081 true); 1082 IDecl->startDefinition(); 1083 if (SDecl) { 1084 IDecl->setSuperClass(SDecl); 1085 IDecl->setSuperClassLoc(SuperClassLoc); 1086 IDecl->setEndOfDefinitionLoc(SuperClassLoc); 1087 } else { 1088 IDecl->setEndOfDefinitionLoc(ClassLoc); 1089 } 1090 1091 PushOnScopeChains(IDecl, TUScope); 1092 } else { 1093 // Mark the interface as being completed, even if it was just as 1094 // @class ....; 1095 // declaration; the user cannot reopen it. 1096 if (!IDecl->hasDefinition()) 1097 IDecl->startDefinition(); 1098 } 1099 1100 ObjCImplementationDecl* IMPDecl = 1101 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl, 1102 ClassLoc, AtClassImplLoc, SuperClassLoc); 1103 1104 if (CheckObjCDeclScope(IMPDecl)) 1105 return ActOnObjCContainerStartDefinition(IMPDecl); 1106 1107 // Check that there is no duplicate implementation of this class. 1108 if (IDecl->getImplementation()) { 1109 // FIXME: Don't leak everything! 1110 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 1111 Diag(IDecl->getImplementation()->getLocation(), 1112 diag::note_previous_definition); 1113 IMPDecl->setInvalidDecl(); 1114 } else { // add it to the list. 1115 IDecl->setImplementation(IMPDecl); 1116 PushOnScopeChains(IMPDecl, TUScope); 1117 // Warn on implementating deprecated class under 1118 // -Wdeprecated-implementations flag. 1119 DiagnoseObjCImplementedDeprecations(*this, 1120 dyn_cast<NamedDecl>(IDecl), 1121 IMPDecl->getLocation(), 1); 1122 } 1123 return ActOnObjCContainerStartDefinition(IMPDecl); 1124 } 1125 1126 Sema::DeclGroupPtrTy 1127 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) { 1128 SmallVector<Decl *, 64> DeclsInGroup; 1129 DeclsInGroup.reserve(Decls.size() + 1); 1130 1131 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 1132 Decl *Dcl = Decls[i]; 1133 if (!Dcl) 1134 continue; 1135 if (Dcl->getDeclContext()->isFileContext()) 1136 Dcl->setTopLevelDeclInObjCContainer(); 1137 DeclsInGroup.push_back(Dcl); 1138 } 1139 1140 DeclsInGroup.push_back(ObjCImpDecl); 1141 1142 return BuildDeclaratorGroup(DeclsInGroup, false); 1143 } 1144 1145 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1146 ObjCIvarDecl **ivars, unsigned numIvars, 1147 SourceLocation RBrace) { 1148 assert(ImpDecl && "missing implementation decl"); 1149 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 1150 if (!IDecl) 1151 return; 1152 /// Check case of non-existing \@interface decl. 1153 /// (legacy objective-c \@implementation decl without an \@interface decl). 1154 /// Add implementations's ivar to the synthesize class's ivar list. 1155 if (IDecl->isImplicitInterfaceDecl()) { 1156 IDecl->setEndOfDefinitionLoc(RBrace); 1157 // Add ivar's to class's DeclContext. 1158 for (unsigned i = 0, e = numIvars; i != e; ++i) { 1159 ivars[i]->setLexicalDeclContext(ImpDecl); 1160 IDecl->makeDeclVisibleInContext(ivars[i]); 1161 ImpDecl->addDecl(ivars[i]); 1162 } 1163 1164 return; 1165 } 1166 // If implementation has empty ivar list, just return. 1167 if (numIvars == 0) 1168 return; 1169 1170 assert(ivars && "missing @implementation ivars"); 1171 if (LangOpts.ObjCRuntime.isNonFragile()) { 1172 if (ImpDecl->getSuperClass()) 1173 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 1174 for (unsigned i = 0; i < numIvars; i++) { 1175 ObjCIvarDecl* ImplIvar = ivars[i]; 1176 if (const ObjCIvarDecl *ClsIvar = 1177 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 1178 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 1179 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1180 continue; 1181 } 1182 // Check class extensions (unnamed categories) for duplicate ivars. 1183 for (const auto *CDecl : IDecl->visible_extensions()) { 1184 if (const ObjCIvarDecl *ClsExtIvar = 1185 CDecl->getIvarDecl(ImplIvar->getIdentifier())) { 1186 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 1187 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 1188 continue; 1189 } 1190 } 1191 // Instance ivar to Implementation's DeclContext. 1192 ImplIvar->setLexicalDeclContext(ImpDecl); 1193 IDecl->makeDeclVisibleInContext(ImplIvar); 1194 ImpDecl->addDecl(ImplIvar); 1195 } 1196 return; 1197 } 1198 // Check interface's Ivar list against those in the implementation. 1199 // names and types must match. 1200 // 1201 unsigned j = 0; 1202 ObjCInterfaceDecl::ivar_iterator 1203 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 1204 for (; numIvars > 0 && IVI != IVE; ++IVI) { 1205 ObjCIvarDecl* ImplIvar = ivars[j++]; 1206 ObjCIvarDecl* ClsIvar = *IVI; 1207 assert (ImplIvar && "missing implementation ivar"); 1208 assert (ClsIvar && "missing class ivar"); 1209 1210 // First, make sure the types match. 1211 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) { 1212 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 1213 << ImplIvar->getIdentifier() 1214 << ImplIvar->getType() << ClsIvar->getType(); 1215 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1216 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() && 1217 ImplIvar->getBitWidthValue(Context) != 1218 ClsIvar->getBitWidthValue(Context)) { 1219 Diag(ImplIvar->getBitWidth()->getLocStart(), 1220 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier(); 1221 Diag(ClsIvar->getBitWidth()->getLocStart(), 1222 diag::note_previous_definition); 1223 } 1224 // Make sure the names are identical. 1225 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 1226 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 1227 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 1228 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1229 } 1230 --numIvars; 1231 } 1232 1233 if (numIvars > 0) 1234 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count); 1235 else if (IVI != IVE) 1236 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count); 1237 } 1238 1239 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, 1240 ObjCMethodDecl *method, 1241 bool &IncompleteImpl, 1242 unsigned DiagID, 1243 NamedDecl *NeededFor = nullptr) { 1244 // No point warning no definition of method which is 'unavailable'. 1245 switch (method->getAvailability()) { 1246 case AR_Available: 1247 case AR_Deprecated: 1248 break; 1249 1250 // Don't warn about unavailable or not-yet-introduced methods. 1251 case AR_NotYetIntroduced: 1252 case AR_Unavailable: 1253 return; 1254 } 1255 1256 // FIXME: For now ignore 'IncompleteImpl'. 1257 // Previously we grouped all unimplemented methods under a single 1258 // warning, but some users strongly voiced that they would prefer 1259 // separate warnings. We will give that approach a try, as that 1260 // matches what we do with protocols. 1261 { 1262 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID); 1263 B << method; 1264 if (NeededFor) 1265 B << NeededFor; 1266 } 1267 1268 // Issue a note to the original declaration. 1269 SourceLocation MethodLoc = method->getLocStart(); 1270 if (MethodLoc.isValid()) 1271 S.Diag(MethodLoc, diag::note_method_declared_at) << method; 1272 } 1273 1274 /// Determines if type B can be substituted for type A. Returns true if we can 1275 /// guarantee that anything that the user will do to an object of type A can 1276 /// also be done to an object of type B. This is trivially true if the two 1277 /// types are the same, or if B is a subclass of A. It becomes more complex 1278 /// in cases where protocols are involved. 1279 /// 1280 /// Object types in Objective-C describe the minimum requirements for an 1281 /// object, rather than providing a complete description of a type. For 1282 /// example, if A is a subclass of B, then B* may refer to an instance of A. 1283 /// The principle of substitutability means that we may use an instance of A 1284 /// anywhere that we may use an instance of B - it will implement all of the 1285 /// ivars of B and all of the methods of B. 1286 /// 1287 /// This substitutability is important when type checking methods, because 1288 /// the implementation may have stricter type definitions than the interface. 1289 /// The interface specifies minimum requirements, but the implementation may 1290 /// have more accurate ones. For example, a method may privately accept 1291 /// instances of B, but only publish that it accepts instances of A. Any 1292 /// object passed to it will be type checked against B, and so will implicitly 1293 /// by a valid A*. Similarly, a method may return a subclass of the class that 1294 /// it is declared as returning. 1295 /// 1296 /// This is most important when considering subclassing. A method in a 1297 /// subclass must accept any object as an argument that its superclass's 1298 /// implementation accepts. It may, however, accept a more general type 1299 /// without breaking substitutability (i.e. you can still use the subclass 1300 /// anywhere that you can use the superclass, but not vice versa). The 1301 /// converse requirement applies to return types: the return type for a 1302 /// subclass method must be a valid object of the kind that the superclass 1303 /// advertises, but it may be specified more accurately. This avoids the need 1304 /// for explicit down-casting by callers. 1305 /// 1306 /// Note: This is a stricter requirement than for assignment. 1307 static bool isObjCTypeSubstitutable(ASTContext &Context, 1308 const ObjCObjectPointerType *A, 1309 const ObjCObjectPointerType *B, 1310 bool rejectId) { 1311 // Reject a protocol-unqualified id. 1312 if (rejectId && B->isObjCIdType()) return false; 1313 1314 // If B is a qualified id, then A must also be a qualified id and it must 1315 // implement all of the protocols in B. It may not be a qualified class. 1316 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 1317 // stricter definition so it is not substitutable for id<A>. 1318 if (B->isObjCQualifiedIdType()) { 1319 return A->isObjCQualifiedIdType() && 1320 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0), 1321 QualType(B,0), 1322 false); 1323 } 1324 1325 /* 1326 // id is a special type that bypasses type checking completely. We want a 1327 // warning when it is used in one place but not another. 1328 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 1329 1330 1331 // If B is a qualified id, then A must also be a qualified id (which it isn't 1332 // if we've got this far) 1333 if (B->isObjCQualifiedIdType()) return false; 1334 */ 1335 1336 // Now we know that A and B are (potentially-qualified) class types. The 1337 // normal rules for assignment apply. 1338 return Context.canAssignObjCInterfaces(A, B); 1339 } 1340 1341 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 1342 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 1343 } 1344 1345 static bool CheckMethodOverrideReturn(Sema &S, 1346 ObjCMethodDecl *MethodImpl, 1347 ObjCMethodDecl *MethodDecl, 1348 bool IsProtocolMethodDecl, 1349 bool IsOverridingMode, 1350 bool Warn) { 1351 if (IsProtocolMethodDecl && 1352 (MethodDecl->getObjCDeclQualifier() != 1353 MethodImpl->getObjCDeclQualifier())) { 1354 if (Warn) { 1355 S.Diag(MethodImpl->getLocation(), 1356 (IsOverridingMode 1357 ? diag::warn_conflicting_overriding_ret_type_modifiers 1358 : diag::warn_conflicting_ret_type_modifiers)) 1359 << MethodImpl->getDeclName() 1360 << MethodImpl->getReturnTypeSourceRange(); 1361 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 1362 << MethodDecl->getReturnTypeSourceRange(); 1363 } 1364 else 1365 return false; 1366 } 1367 1368 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(), 1369 MethodDecl->getReturnType())) 1370 return true; 1371 if (!Warn) 1372 return false; 1373 1374 unsigned DiagID = 1375 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 1376 : diag::warn_conflicting_ret_types; 1377 1378 // Mismatches between ObjC pointers go into a different warning 1379 // category, and sometimes they're even completely whitelisted. 1380 if (const ObjCObjectPointerType *ImplPtrTy = 1381 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) { 1382 if (const ObjCObjectPointerType *IfacePtrTy = 1383 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) { 1384 // Allow non-matching return types as long as they don't violate 1385 // the principle of substitutability. Specifically, we permit 1386 // return types that are subclasses of the declared return type, 1387 // or that are more-qualified versions of the declared type. 1388 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 1389 return false; 1390 1391 DiagID = 1392 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 1393 : diag::warn_non_covariant_ret_types; 1394 } 1395 } 1396 1397 S.Diag(MethodImpl->getLocation(), DiagID) 1398 << MethodImpl->getDeclName() << MethodDecl->getReturnType() 1399 << MethodImpl->getReturnType() 1400 << MethodImpl->getReturnTypeSourceRange(); 1401 S.Diag(MethodDecl->getLocation(), IsOverridingMode 1402 ? diag::note_previous_declaration 1403 : diag::note_previous_definition) 1404 << MethodDecl->getReturnTypeSourceRange(); 1405 return false; 1406 } 1407 1408 static bool CheckMethodOverrideParam(Sema &S, 1409 ObjCMethodDecl *MethodImpl, 1410 ObjCMethodDecl *MethodDecl, 1411 ParmVarDecl *ImplVar, 1412 ParmVarDecl *IfaceVar, 1413 bool IsProtocolMethodDecl, 1414 bool IsOverridingMode, 1415 bool Warn) { 1416 if (IsProtocolMethodDecl && 1417 (ImplVar->getObjCDeclQualifier() != 1418 IfaceVar->getObjCDeclQualifier())) { 1419 if (Warn) { 1420 if (IsOverridingMode) 1421 S.Diag(ImplVar->getLocation(), 1422 diag::warn_conflicting_overriding_param_modifiers) 1423 << getTypeRange(ImplVar->getTypeSourceInfo()) 1424 << MethodImpl->getDeclName(); 1425 else S.Diag(ImplVar->getLocation(), 1426 diag::warn_conflicting_param_modifiers) 1427 << getTypeRange(ImplVar->getTypeSourceInfo()) 1428 << MethodImpl->getDeclName(); 1429 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 1430 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1431 } 1432 else 1433 return false; 1434 } 1435 1436 QualType ImplTy = ImplVar->getType(); 1437 QualType IfaceTy = IfaceVar->getType(); 1438 1439 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 1440 return true; 1441 1442 if (!Warn) 1443 return false; 1444 unsigned DiagID = 1445 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 1446 : diag::warn_conflicting_param_types; 1447 1448 // Mismatches between ObjC pointers go into a different warning 1449 // category, and sometimes they're even completely whitelisted. 1450 if (const ObjCObjectPointerType *ImplPtrTy = 1451 ImplTy->getAs<ObjCObjectPointerType>()) { 1452 if (const ObjCObjectPointerType *IfacePtrTy = 1453 IfaceTy->getAs<ObjCObjectPointerType>()) { 1454 // Allow non-matching argument types as long as they don't 1455 // violate the principle of substitutability. Specifically, the 1456 // implementation must accept any objects that the superclass 1457 // accepts, however it may also accept others. 1458 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 1459 return false; 1460 1461 DiagID = 1462 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 1463 : diag::warn_non_contravariant_param_types; 1464 } 1465 } 1466 1467 S.Diag(ImplVar->getLocation(), DiagID) 1468 << getTypeRange(ImplVar->getTypeSourceInfo()) 1469 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 1470 S.Diag(IfaceVar->getLocation(), 1471 (IsOverridingMode ? diag::note_previous_declaration 1472 : diag::note_previous_definition)) 1473 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1474 return false; 1475 } 1476 1477 /// In ARC, check whether the conventional meanings of the two methods 1478 /// match. If they don't, it's a hard error. 1479 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 1480 ObjCMethodDecl *decl) { 1481 ObjCMethodFamily implFamily = impl->getMethodFamily(); 1482 ObjCMethodFamily declFamily = decl->getMethodFamily(); 1483 if (implFamily == declFamily) return false; 1484 1485 // Since conventions are sorted by selector, the only possibility is 1486 // that the types differ enough to cause one selector or the other 1487 // to fall out of the family. 1488 assert(implFamily == OMF_None || declFamily == OMF_None); 1489 1490 // No further diagnostics required on invalid declarations. 1491 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 1492 1493 const ObjCMethodDecl *unmatched = impl; 1494 ObjCMethodFamily family = declFamily; 1495 unsigned errorID = diag::err_arc_lost_method_convention; 1496 unsigned noteID = diag::note_arc_lost_method_convention; 1497 if (declFamily == OMF_None) { 1498 unmatched = decl; 1499 family = implFamily; 1500 errorID = diag::err_arc_gained_method_convention; 1501 noteID = diag::note_arc_gained_method_convention; 1502 } 1503 1504 // Indexes into a %select clause in the diagnostic. 1505 enum FamilySelector { 1506 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 1507 }; 1508 FamilySelector familySelector = FamilySelector(); 1509 1510 switch (family) { 1511 case OMF_None: llvm_unreachable("logic error, no method convention"); 1512 case OMF_retain: 1513 case OMF_release: 1514 case OMF_autorelease: 1515 case OMF_dealloc: 1516 case OMF_finalize: 1517 case OMF_retainCount: 1518 case OMF_self: 1519 case OMF_initialize: 1520 case OMF_performSelector: 1521 // Mismatches for these methods don't change ownership 1522 // conventions, so we don't care. 1523 return false; 1524 1525 case OMF_init: familySelector = F_init; break; 1526 case OMF_alloc: familySelector = F_alloc; break; 1527 case OMF_copy: familySelector = F_copy; break; 1528 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 1529 case OMF_new: familySelector = F_new; break; 1530 } 1531 1532 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 1533 ReasonSelector reasonSelector; 1534 1535 // The only reason these methods don't fall within their families is 1536 // due to unusual result types. 1537 if (unmatched->getReturnType()->isObjCObjectPointerType()) { 1538 reasonSelector = R_UnrelatedReturn; 1539 } else { 1540 reasonSelector = R_NonObjectReturn; 1541 } 1542 1543 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector); 1544 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector); 1545 1546 return true; 1547 } 1548 1549 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1550 ObjCMethodDecl *MethodDecl, 1551 bool IsProtocolMethodDecl) { 1552 if (getLangOpts().ObjCAutoRefCount && 1553 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 1554 return; 1555 1556 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1557 IsProtocolMethodDecl, false, 1558 true); 1559 1560 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1561 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1562 EF = MethodDecl->param_end(); 1563 IM != EM && IF != EF; ++IM, ++IF) { 1564 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 1565 IsProtocolMethodDecl, false, true); 1566 } 1567 1568 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 1569 Diag(ImpMethodDecl->getLocation(), 1570 diag::warn_conflicting_variadic); 1571 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 1572 } 1573 } 1574 1575 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 1576 ObjCMethodDecl *Overridden, 1577 bool IsProtocolMethodDecl) { 1578 1579 CheckMethodOverrideReturn(*this, Method, Overridden, 1580 IsProtocolMethodDecl, true, 1581 true); 1582 1583 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 1584 IF = Overridden->param_begin(), EM = Method->param_end(), 1585 EF = Overridden->param_end(); 1586 IM != EM && IF != EF; ++IM, ++IF) { 1587 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 1588 IsProtocolMethodDecl, true, true); 1589 } 1590 1591 if (Method->isVariadic() != Overridden->isVariadic()) { 1592 Diag(Method->getLocation(), 1593 diag::warn_conflicting_overriding_variadic); 1594 Diag(Overridden->getLocation(), diag::note_previous_declaration); 1595 } 1596 } 1597 1598 /// WarnExactTypedMethods - This routine issues a warning if method 1599 /// implementation declaration matches exactly that of its declaration. 1600 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1601 ObjCMethodDecl *MethodDecl, 1602 bool IsProtocolMethodDecl) { 1603 // don't issue warning when protocol method is optional because primary 1604 // class is not required to implement it and it is safe for protocol 1605 // to implement it. 1606 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 1607 return; 1608 // don't issue warning when primary class's method is 1609 // depecated/unavailable. 1610 if (MethodDecl->hasAttr<UnavailableAttr>() || 1611 MethodDecl->hasAttr<DeprecatedAttr>()) 1612 return; 1613 1614 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1615 IsProtocolMethodDecl, false, false); 1616 if (match) 1617 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1618 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1619 EF = MethodDecl->param_end(); 1620 IM != EM && IF != EF; ++IM, ++IF) { 1621 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 1622 *IM, *IF, 1623 IsProtocolMethodDecl, false, false); 1624 if (!match) 1625 break; 1626 } 1627 if (match) 1628 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 1629 if (match) 1630 match = !(MethodDecl->isClassMethod() && 1631 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 1632 1633 if (match) { 1634 Diag(ImpMethodDecl->getLocation(), 1635 diag::warn_category_method_impl_match); 1636 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 1637 << MethodDecl->getDeclName(); 1638 } 1639 } 1640 1641 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 1642 /// improve the efficiency of selector lookups and type checking by associating 1643 /// with each protocol / interface / category the flattened instance tables. If 1644 /// we used an immutable set to keep the table then it wouldn't add significant 1645 /// memory cost and it would be handy for lookups. 1646 1647 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet; 1648 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet; 1649 1650 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl, 1651 ProtocolNameSet &PNS) { 1652 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 1653 PNS.insert(PDecl->getIdentifier()); 1654 for (const auto *PI : PDecl->protocols()) 1655 findProtocolsWithExplicitImpls(PI, PNS); 1656 } 1657 1658 /// Recursively populates a set with all conformed protocols in a class 1659 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation' 1660 /// attribute. 1661 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super, 1662 ProtocolNameSet &PNS) { 1663 if (!Super) 1664 return; 1665 1666 for (const auto *I : Super->all_referenced_protocols()) 1667 findProtocolsWithExplicitImpls(I, PNS); 1668 1669 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS); 1670 } 1671 1672 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 1673 /// Declared in protocol, and those referenced by it. 1674 static void CheckProtocolMethodDefs(Sema &S, 1675 SourceLocation ImpLoc, 1676 ObjCProtocolDecl *PDecl, 1677 bool& IncompleteImpl, 1678 const Sema::SelectorSet &InsMap, 1679 const Sema::SelectorSet &ClsMap, 1680 ObjCContainerDecl *CDecl, 1681 LazyProtocolNameSet &ProtocolsExplictImpl) { 1682 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 1683 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 1684 : dyn_cast<ObjCInterfaceDecl>(CDecl); 1685 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 1686 1687 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 1688 ObjCInterfaceDecl *NSIDecl = nullptr; 1689 1690 // If this protocol is marked 'objc_protocol_requires_explicit_implementation' 1691 // then we should check if any class in the super class hierarchy also 1692 // conforms to this protocol, either directly or via protocol inheritance. 1693 // If so, we can skip checking this protocol completely because we 1694 // know that a parent class already satisfies this protocol. 1695 // 1696 // Note: we could generalize this logic for all protocols, and merely 1697 // add the limit on looking at the super class chain for just 1698 // specially marked protocols. This may be a good optimization. This 1699 // change is restricted to 'objc_protocol_requires_explicit_implementation' 1700 // protocols for now for controlled evaluation. 1701 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) { 1702 if (!ProtocolsExplictImpl) { 1703 ProtocolsExplictImpl.reset(new ProtocolNameSet); 1704 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl); 1705 } 1706 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) != 1707 ProtocolsExplictImpl->end()) 1708 return; 1709 1710 // If no super class conforms to the protocol, we should not search 1711 // for methods in the super class to implicitly satisfy the protocol. 1712 Super = nullptr; 1713 } 1714 1715 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) { 1716 // check to see if class implements forwardInvocation method and objects 1717 // of this class are derived from 'NSProxy' so that to forward requests 1718 // from one object to another. 1719 // Under such conditions, which means that every method possible is 1720 // implemented in the class, we should not issue "Method definition not 1721 // found" warnings. 1722 // FIXME: Use a general GetUnarySelector method for this. 1723 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation"); 1724 Selector fISelector = S.Context.Selectors.getSelector(1, &II); 1725 if (InsMap.count(fISelector)) 1726 // Is IDecl derived from 'NSProxy'? If so, no instance methods 1727 // need be implemented in the implementation. 1728 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy")); 1729 } 1730 1731 // If this is a forward protocol declaration, get its definition. 1732 if (!PDecl->isThisDeclarationADefinition() && 1733 PDecl->getDefinition()) 1734 PDecl = PDecl->getDefinition(); 1735 1736 // If a method lookup fails locally we still need to look and see if 1737 // the method was implemented by a base class or an inherited 1738 // protocol. This lookup is slow, but occurs rarely in correct code 1739 // and otherwise would terminate in a warning. 1740 1741 // check unimplemented instance methods. 1742 if (!NSIDecl) 1743 for (auto *method : PDecl->instance_methods()) { 1744 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1745 !method->isPropertyAccessor() && 1746 !InsMap.count(method->getSelector()) && 1747 (!Super || !Super->lookupMethod(method->getSelector(), 1748 true /* instance */, 1749 false /* shallowCategory */, 1750 true /* followsSuper */, 1751 nullptr /* category */))) { 1752 // If a method is not implemented in the category implementation but 1753 // has been declared in its primary class, superclass, 1754 // or in one of their protocols, no need to issue the warning. 1755 // This is because method will be implemented in the primary class 1756 // or one of its super class implementation. 1757 1758 // Ugly, but necessary. Method declared in protcol might have 1759 // have been synthesized due to a property declared in the class which 1760 // uses the protocol. 1761 if (ObjCMethodDecl *MethodInClass = 1762 IDecl->lookupMethod(method->getSelector(), 1763 true /* instance */, 1764 true /* shallowCategoryLookup */, 1765 false /* followSuper */)) 1766 if (C || MethodInClass->isPropertyAccessor()) 1767 continue; 1768 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1769 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 1770 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, 1771 PDecl); 1772 } 1773 } 1774 } 1775 // check unimplemented class methods 1776 for (auto *method : PDecl->class_methods()) { 1777 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1778 !ClsMap.count(method->getSelector()) && 1779 (!Super || !Super->lookupMethod(method->getSelector(), 1780 false /* class method */, 1781 false /* shallowCategoryLookup */, 1782 true /* followSuper */, 1783 nullptr /* category */))) { 1784 // See above comment for instance method lookups. 1785 if (C && IDecl->lookupMethod(method->getSelector(), 1786 false /* class */, 1787 true /* shallowCategoryLookup */, 1788 false /* followSuper */)) 1789 continue; 1790 1791 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1792 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 1793 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl); 1794 } 1795 } 1796 } 1797 // Check on this protocols's referenced protocols, recursively. 1798 for (auto *PI : PDecl->protocols()) 1799 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap, 1800 CDecl, ProtocolsExplictImpl); 1801 } 1802 1803 /// MatchAllMethodDeclarations - Check methods declared in interface 1804 /// or protocol against those declared in their implementations. 1805 /// 1806 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 1807 const SelectorSet &ClsMap, 1808 SelectorSet &InsMapSeen, 1809 SelectorSet &ClsMapSeen, 1810 ObjCImplDecl* IMPDecl, 1811 ObjCContainerDecl* CDecl, 1812 bool &IncompleteImpl, 1813 bool ImmediateClass, 1814 bool WarnCategoryMethodImpl) { 1815 // Check and see if instance methods in class interface have been 1816 // implemented in the implementation class. If so, their types match. 1817 for (auto *I : CDecl->instance_methods()) { 1818 if (!InsMapSeen.insert(I->getSelector()).second) 1819 continue; 1820 if (!I->isPropertyAccessor() && 1821 !InsMap.count(I->getSelector())) { 1822 if (ImmediateClass) 1823 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 1824 diag::warn_undef_method_impl); 1825 continue; 1826 } else { 1827 ObjCMethodDecl *ImpMethodDecl = 1828 IMPDecl->getInstanceMethod(I->getSelector()); 1829 assert(CDecl->getInstanceMethod(I->getSelector()) && 1830 "Expected to find the method through lookup as well"); 1831 // ImpMethodDecl may be null as in a @dynamic property. 1832 if (ImpMethodDecl) { 1833 if (!WarnCategoryMethodImpl) 1834 WarnConflictingTypedMethods(ImpMethodDecl, I, 1835 isa<ObjCProtocolDecl>(CDecl)); 1836 else if (!I->isPropertyAccessor()) 1837 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl)); 1838 } 1839 } 1840 } 1841 1842 // Check and see if class methods in class interface have been 1843 // implemented in the implementation class. If so, their types match. 1844 for (auto *I : CDecl->class_methods()) { 1845 if (!ClsMapSeen.insert(I->getSelector()).second) 1846 continue; 1847 if (!ClsMap.count(I->getSelector())) { 1848 if (ImmediateClass) 1849 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 1850 diag::warn_undef_method_impl); 1851 } else { 1852 ObjCMethodDecl *ImpMethodDecl = 1853 IMPDecl->getClassMethod(I->getSelector()); 1854 assert(CDecl->getClassMethod(I->getSelector()) && 1855 "Expected to find the method through lookup as well"); 1856 if (!WarnCategoryMethodImpl) 1857 WarnConflictingTypedMethods(ImpMethodDecl, I, 1858 isa<ObjCProtocolDecl>(CDecl)); 1859 else 1860 WarnExactTypedMethods(ImpMethodDecl, I, 1861 isa<ObjCProtocolDecl>(CDecl)); 1862 } 1863 } 1864 1865 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { 1866 // Also, check for methods declared in protocols inherited by 1867 // this protocol. 1868 for (auto *PI : PD->protocols()) 1869 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1870 IMPDecl, PI, IncompleteImpl, false, 1871 WarnCategoryMethodImpl); 1872 } 1873 1874 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1875 // when checking that methods in implementation match their declaration, 1876 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 1877 // extension; as well as those in categories. 1878 if (!WarnCategoryMethodImpl) { 1879 for (auto *Cat : I->visible_categories()) 1880 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1881 IMPDecl, Cat, IncompleteImpl, false, 1882 WarnCategoryMethodImpl); 1883 } else { 1884 // Also methods in class extensions need be looked at next. 1885 for (auto *Ext : I->visible_extensions()) 1886 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1887 IMPDecl, Ext, IncompleteImpl, false, 1888 WarnCategoryMethodImpl); 1889 } 1890 1891 // Check for any implementation of a methods declared in protocol. 1892 for (auto *PI : I->all_referenced_protocols()) 1893 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1894 IMPDecl, PI, IncompleteImpl, false, 1895 WarnCategoryMethodImpl); 1896 1897 // FIXME. For now, we are not checking for extact match of methods 1898 // in category implementation and its primary class's super class. 1899 if (!WarnCategoryMethodImpl && I->getSuperClass()) 1900 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1901 IMPDecl, 1902 I->getSuperClass(), IncompleteImpl, false); 1903 } 1904 } 1905 1906 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 1907 /// category matches with those implemented in its primary class and 1908 /// warns each time an exact match is found. 1909 void Sema::CheckCategoryVsClassMethodMatches( 1910 ObjCCategoryImplDecl *CatIMPDecl) { 1911 // Get category's primary class. 1912 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 1913 if (!CatDecl) 1914 return; 1915 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 1916 if (!IDecl) 1917 return; 1918 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 1919 SelectorSet InsMap, ClsMap; 1920 1921 for (const auto *I : CatIMPDecl->instance_methods()) { 1922 Selector Sel = I->getSelector(); 1923 // When checking for methods implemented in the category, skip over 1924 // those declared in category class's super class. This is because 1925 // the super class must implement the method. 1926 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 1927 continue; 1928 InsMap.insert(Sel); 1929 } 1930 1931 for (const auto *I : CatIMPDecl->class_methods()) { 1932 Selector Sel = I->getSelector(); 1933 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 1934 continue; 1935 ClsMap.insert(Sel); 1936 } 1937 if (InsMap.empty() && ClsMap.empty()) 1938 return; 1939 1940 SelectorSet InsMapSeen, ClsMapSeen; 1941 bool IncompleteImpl = false; 1942 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1943 CatIMPDecl, IDecl, 1944 IncompleteImpl, false, 1945 true /*WarnCategoryMethodImpl*/); 1946 } 1947 1948 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1949 ObjCContainerDecl* CDecl, 1950 bool IncompleteImpl) { 1951 SelectorSet InsMap; 1952 // Check and see if instance methods in class interface have been 1953 // implemented in the implementation class. 1954 for (const auto *I : IMPDecl->instance_methods()) 1955 InsMap.insert(I->getSelector()); 1956 1957 // Check and see if properties declared in the interface have either 1) 1958 // an implementation or 2) there is a @synthesize/@dynamic implementation 1959 // of the property in the @implementation. 1960 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1961 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties && 1962 LangOpts.ObjCRuntime.isNonFragile() && 1963 !IDecl->isObjCRequiresPropertyDefs(); 1964 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties); 1965 } 1966 1967 SelectorSet ClsMap; 1968 for (const auto *I : IMPDecl->class_methods()) 1969 ClsMap.insert(I->getSelector()); 1970 1971 // Check for type conflict of methods declared in a class/protocol and 1972 // its implementation; if any. 1973 SelectorSet InsMapSeen, ClsMapSeen; 1974 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1975 IMPDecl, CDecl, 1976 IncompleteImpl, true); 1977 1978 // check all methods implemented in category against those declared 1979 // in its primary class. 1980 if (ObjCCategoryImplDecl *CatDecl = 1981 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 1982 CheckCategoryVsClassMethodMatches(CatDecl); 1983 1984 // Check the protocol list for unimplemented methods in the @implementation 1985 // class. 1986 // Check and see if class methods in class interface have been 1987 // implemented in the implementation class. 1988 1989 LazyProtocolNameSet ExplicitImplProtocols; 1990 1991 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1992 for (auto *PI : I->all_referenced_protocols()) 1993 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl, 1994 InsMap, ClsMap, I, ExplicitImplProtocols); 1995 // Check class extensions (unnamed categories) 1996 for (auto *Ext : I->visible_extensions()) 1997 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl); 1998 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1999 // For extended class, unimplemented methods in its protocols will 2000 // be reported in the primary class. 2001 if (!C->IsClassExtension()) { 2002 for (auto *P : C->protocols()) 2003 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P, 2004 IncompleteImpl, InsMap, ClsMap, CDecl, 2005 ExplicitImplProtocols); 2006 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, 2007 /* SynthesizeProperties */ false); 2008 } 2009 } else 2010 llvm_unreachable("invalid ObjCContainerDecl type."); 2011 } 2012 2013 /// ActOnForwardClassDeclaration - 2014 Sema::DeclGroupPtrTy 2015 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 2016 IdentifierInfo **IdentList, 2017 SourceLocation *IdentLocs, 2018 unsigned NumElts) { 2019 SmallVector<Decl *, 8> DeclsInGroup; 2020 for (unsigned i = 0; i != NumElts; ++i) { 2021 // Check for another declaration kind with the same name. 2022 NamedDecl *PrevDecl 2023 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 2024 LookupOrdinaryName, ForRedeclaration); 2025 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2026 // GCC apparently allows the following idiom: 2027 // 2028 // typedef NSObject < XCElementTogglerP > XCElementToggler; 2029 // @class XCElementToggler; 2030 // 2031 // Here we have chosen to ignore the forward class declaration 2032 // with a warning. Since this is the implied behavior. 2033 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 2034 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 2035 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 2036 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2037 } else { 2038 // a forward class declaration matching a typedef name of a class refers 2039 // to the underlying class. Just ignore the forward class with a warning 2040 // as this will force the intended behavior which is to lookup the typedef 2041 // name. 2042 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 2043 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i]; 2044 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2045 continue; 2046 } 2047 } 2048 } 2049 2050 // Create a declaration to describe this forward declaration. 2051 ObjCInterfaceDecl *PrevIDecl 2052 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2053 2054 IdentifierInfo *ClassName = IdentList[i]; 2055 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 2056 // A previous decl with a different name is because of 2057 // @compatibility_alias, for example: 2058 // \code 2059 // @class NewImage; 2060 // @compatibility_alias OldImage NewImage; 2061 // \endcode 2062 // A lookup for 'OldImage' will return the 'NewImage' decl. 2063 // 2064 // In such a case use the real declaration name, instead of the alias one, 2065 // otherwise we will break IdentifierResolver and redecls-chain invariants. 2066 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 2067 // has been aliased. 2068 ClassName = PrevIDecl->getIdentifier(); 2069 } 2070 2071 ObjCInterfaceDecl *IDecl 2072 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 2073 ClassName, PrevIDecl, IdentLocs[i]); 2074 IDecl->setAtEndRange(IdentLocs[i]); 2075 2076 PushOnScopeChains(IDecl, TUScope); 2077 CheckObjCDeclScope(IDecl); 2078 DeclsInGroup.push_back(IDecl); 2079 } 2080 2081 return BuildDeclaratorGroup(DeclsInGroup, false); 2082 } 2083 2084 static bool tryMatchRecordTypes(ASTContext &Context, 2085 Sema::MethodMatchStrategy strategy, 2086 const Type *left, const Type *right); 2087 2088 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 2089 QualType leftQT, QualType rightQT) { 2090 const Type *left = 2091 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 2092 const Type *right = 2093 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 2094 2095 if (left == right) return true; 2096 2097 // If we're doing a strict match, the types have to match exactly. 2098 if (strategy == Sema::MMS_strict) return false; 2099 2100 if (left->isIncompleteType() || right->isIncompleteType()) return false; 2101 2102 // Otherwise, use this absurdly complicated algorithm to try to 2103 // validate the basic, low-level compatibility of the two types. 2104 2105 // As a minimum, require the sizes and alignments to match. 2106 TypeInfo LeftTI = Context.getTypeInfo(left); 2107 TypeInfo RightTI = Context.getTypeInfo(right); 2108 if (LeftTI.Width != RightTI.Width) 2109 return false; 2110 2111 if (LeftTI.Align != RightTI.Align) 2112 return false; 2113 2114 // Consider all the kinds of non-dependent canonical types: 2115 // - functions and arrays aren't possible as return and parameter types 2116 2117 // - vector types of equal size can be arbitrarily mixed 2118 if (isa<VectorType>(left)) return isa<VectorType>(right); 2119 if (isa<VectorType>(right)) return false; 2120 2121 // - references should only match references of identical type 2122 // - structs, unions, and Objective-C objects must match more-or-less 2123 // exactly 2124 // - everything else should be a scalar 2125 if (!left->isScalarType() || !right->isScalarType()) 2126 return tryMatchRecordTypes(Context, strategy, left, right); 2127 2128 // Make scalars agree in kind, except count bools as chars, and group 2129 // all non-member pointers together. 2130 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 2131 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 2132 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 2133 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 2134 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 2135 leftSK = Type::STK_ObjCObjectPointer; 2136 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 2137 rightSK = Type::STK_ObjCObjectPointer; 2138 2139 // Note that data member pointers and function member pointers don't 2140 // intermix because of the size differences. 2141 2142 return (leftSK == rightSK); 2143 } 2144 2145 static bool tryMatchRecordTypes(ASTContext &Context, 2146 Sema::MethodMatchStrategy strategy, 2147 const Type *lt, const Type *rt) { 2148 assert(lt && rt && lt != rt); 2149 2150 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 2151 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 2152 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 2153 2154 // Require union-hood to match. 2155 if (left->isUnion() != right->isUnion()) return false; 2156 2157 // Require an exact match if either is non-POD. 2158 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 2159 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 2160 return false; 2161 2162 // Require size and alignment to match. 2163 TypeInfo LeftTI = Context.getTypeInfo(lt); 2164 TypeInfo RightTI = Context.getTypeInfo(rt); 2165 if (LeftTI.Width != RightTI.Width) 2166 return false; 2167 2168 if (LeftTI.Align != RightTI.Align) 2169 return false; 2170 2171 // Require fields to match. 2172 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 2173 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 2174 for (; li != le && ri != re; ++li, ++ri) { 2175 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 2176 return false; 2177 } 2178 return (li == le && ri == re); 2179 } 2180 2181 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 2182 /// returns true, or false, accordingly. 2183 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 2184 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 2185 const ObjCMethodDecl *right, 2186 MethodMatchStrategy strategy) { 2187 if (!matchTypes(Context, strategy, left->getReturnType(), 2188 right->getReturnType())) 2189 return false; 2190 2191 // If either is hidden, it is not considered to match. 2192 if (left->isHidden() || right->isHidden()) 2193 return false; 2194 2195 if (getLangOpts().ObjCAutoRefCount && 2196 (left->hasAttr<NSReturnsRetainedAttr>() 2197 != right->hasAttr<NSReturnsRetainedAttr>() || 2198 left->hasAttr<NSConsumesSelfAttr>() 2199 != right->hasAttr<NSConsumesSelfAttr>())) 2200 return false; 2201 2202 ObjCMethodDecl::param_const_iterator 2203 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 2204 re = right->param_end(); 2205 2206 for (; li != le && ri != re; ++li, ++ri) { 2207 assert(ri != right->param_end() && "Param mismatch"); 2208 const ParmVarDecl *lparm = *li, *rparm = *ri; 2209 2210 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 2211 return false; 2212 2213 if (getLangOpts().ObjCAutoRefCount && 2214 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 2215 return false; 2216 } 2217 return true; 2218 } 2219 2220 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) { 2221 // Record at the head of the list whether there were 0, 1, or >= 2 methods 2222 // inside categories. 2223 if (ObjCCategoryDecl * 2224 CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 2225 if (!CD->IsClassExtension() && List->getBits() < 2) 2226 List->setBits(List->getBits()+1); 2227 2228 // If the list is empty, make it a singleton list. 2229 if (List->Method == nullptr) { 2230 List->Method = Method; 2231 List->setNext(nullptr); 2232 List->Count = Method->isDefined() ? 0 : 1; 2233 return; 2234 } 2235 2236 // We've seen a method with this name, see if we have already seen this type 2237 // signature. 2238 ObjCMethodList *Previous = List; 2239 for (; List; Previous = List, List = List->getNext()) { 2240 // If we are building a module, keep all of the methods. 2241 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) 2242 continue; 2243 2244 if (!MatchTwoMethodDeclarations(Method, List->Method)) 2245 continue; 2246 2247 ObjCMethodDecl *PrevObjCMethod = List->Method; 2248 2249 // Propagate the 'defined' bit. 2250 if (Method->isDefined()) 2251 PrevObjCMethod->setDefined(true); 2252 else 2253 ++List->Count; 2254 2255 // If a method is deprecated, push it in the global pool. 2256 // This is used for better diagnostics. 2257 if (Method->isDeprecated()) { 2258 if (!PrevObjCMethod->isDeprecated()) 2259 List->Method = Method; 2260 } 2261 // If new method is unavailable, push it into global pool 2262 // unless previous one is deprecated. 2263 if (Method->isUnavailable()) { 2264 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 2265 List->Method = Method; 2266 } 2267 2268 return; 2269 } 2270 2271 // We have a new signature for an existing method - add it. 2272 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 2273 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 2274 Previous->setNext(new (Mem) ObjCMethodList(Method, 0, nullptr)); 2275 } 2276 2277 /// \brief Read the contents of the method pool for a given selector from 2278 /// external storage. 2279 void Sema::ReadMethodPool(Selector Sel) { 2280 assert(ExternalSource && "We need an external AST source"); 2281 ExternalSource->ReadMethodPool(Sel); 2282 } 2283 2284 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 2285 bool instance) { 2286 // Ignore methods of invalid containers. 2287 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 2288 return; 2289 2290 if (ExternalSource) 2291 ReadMethodPool(Method->getSelector()); 2292 2293 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 2294 if (Pos == MethodPool.end()) 2295 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 2296 GlobalMethods())).first; 2297 2298 Method->setDefined(impl); 2299 2300 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 2301 addMethodToGlobalList(&Entry, Method); 2302 } 2303 2304 /// Determines if this is an "acceptable" loose mismatch in the global 2305 /// method pool. This exists mostly as a hack to get around certain 2306 /// global mismatches which we can't afford to make warnings / errors. 2307 /// Really, what we want is a way to take a method out of the global 2308 /// method pool. 2309 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 2310 ObjCMethodDecl *other) { 2311 if (!chosen->isInstanceMethod()) 2312 return false; 2313 2314 Selector sel = chosen->getSelector(); 2315 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 2316 return false; 2317 2318 // Don't complain about mismatches for -length if the method we 2319 // chose has an integral result type. 2320 return (chosen->getReturnType()->isIntegerType()); 2321 } 2322 2323 bool Sema::CollectMultipleMethodsInGlobalPool(Selector Sel, 2324 SmallVectorImpl<ObjCMethodDecl*>& Methods, 2325 bool instance) { 2326 if (ExternalSource) 2327 ReadMethodPool(Sel); 2328 2329 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2330 if (Pos == MethodPool.end()) 2331 return false; 2332 // Gather the non-hidden methods. 2333 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 2334 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) 2335 if (M->Method && !M->Method->isHidden()) 2336 Methods.push_back(M->Method); 2337 return (Methods.size() > 1); 2338 } 2339 2340 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, 2341 bool instance) { 2342 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2343 // Test for no method in the pool which should not trigger any warning by caller. 2344 if (Pos == MethodPool.end()) 2345 return true; 2346 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 2347 return MethList.Count > 1; 2348 } 2349 2350 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2351 bool receiverIdOrClass, 2352 bool warn, bool instance) { 2353 if (ExternalSource) 2354 ReadMethodPool(Sel); 2355 2356 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2357 if (Pos == MethodPool.end()) 2358 return nullptr; 2359 2360 // Gather the non-hidden methods. 2361 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 2362 SmallVector<ObjCMethodDecl *, 4> Methods; 2363 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 2364 if (M->Method && !M->Method->isHidden()) { 2365 // If we're not supposed to warn about mismatches, we're done. 2366 if (!warn) 2367 return M->Method; 2368 2369 Methods.push_back(M->Method); 2370 } 2371 } 2372 2373 // If there aren't any visible methods, we're done. 2374 // FIXME: Recover if there are any known-but-hidden methods? 2375 if (Methods.empty()) 2376 return nullptr; 2377 2378 if (Methods.size() == 1) 2379 return Methods[0]; 2380 2381 // We found multiple methods, so we may have to complain. 2382 bool issueDiagnostic = false, issueError = false; 2383 2384 // We support a warning which complains about *any* difference in 2385 // method signature. 2386 bool strictSelectorMatch = 2387 receiverIdOrClass && warn && 2388 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin()); 2389 if (strictSelectorMatch) { 2390 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2391 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 2392 issueDiagnostic = true; 2393 break; 2394 } 2395 } 2396 } 2397 2398 // If we didn't see any strict differences, we won't see any loose 2399 // differences. In ARC, however, we also need to check for loose 2400 // mismatches, because most of them are errors. 2401 if (!strictSelectorMatch || 2402 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 2403 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2404 // This checks if the methods differ in type mismatch. 2405 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 2406 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 2407 issueDiagnostic = true; 2408 if (getLangOpts().ObjCAutoRefCount) 2409 issueError = true; 2410 break; 2411 } 2412 } 2413 2414 if (issueDiagnostic) { 2415 if (issueError) 2416 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 2417 else if (strictSelectorMatch) 2418 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 2419 else 2420 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 2421 2422 Diag(Methods[0]->getLocStart(), 2423 issueError ? diag::note_possibility : diag::note_using) 2424 << Methods[0]->getSourceRange(); 2425 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2426 Diag(Methods[I]->getLocStart(), diag::note_also_found) 2427 << Methods[I]->getSourceRange(); 2428 } 2429 } 2430 return Methods[0]; 2431 } 2432 2433 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 2434 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2435 if (Pos == MethodPool.end()) 2436 return nullptr; 2437 2438 GlobalMethods &Methods = Pos->second; 2439 for (const ObjCMethodList *Method = &Methods.first; Method; 2440 Method = Method->getNext()) 2441 if (Method->Method && Method->Method->isDefined()) 2442 return Method->Method; 2443 2444 for (const ObjCMethodList *Method = &Methods.second; Method; 2445 Method = Method->getNext()) 2446 if (Method->Method && Method->Method->isDefined()) 2447 return Method->Method; 2448 return nullptr; 2449 } 2450 2451 static void 2452 HelperSelectorsForTypoCorrection( 2453 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 2454 StringRef Typo, const ObjCMethodDecl * Method) { 2455 const unsigned MaxEditDistance = 1; 2456 unsigned BestEditDistance = MaxEditDistance + 1; 2457 std::string MethodName = Method->getSelector().getAsString(); 2458 2459 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 2460 if (MinPossibleEditDistance > 0 && 2461 Typo.size() / MinPossibleEditDistance < 1) 2462 return; 2463 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 2464 if (EditDistance > MaxEditDistance) 2465 return; 2466 if (EditDistance == BestEditDistance) 2467 BestMethod.push_back(Method); 2468 else if (EditDistance < BestEditDistance) { 2469 BestMethod.clear(); 2470 BestMethod.push_back(Method); 2471 } 2472 } 2473 2474 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 2475 QualType ObjectType) { 2476 if (ObjectType.isNull()) 2477 return true; 2478 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 2479 return true; 2480 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 2481 nullptr; 2482 } 2483 2484 const ObjCMethodDecl * 2485 Sema::SelectorsForTypoCorrection(Selector Sel, 2486 QualType ObjectType) { 2487 unsigned NumArgs = Sel.getNumArgs(); 2488 SmallVector<const ObjCMethodDecl *, 8> Methods; 2489 bool ObjectIsId = true, ObjectIsClass = true; 2490 if (ObjectType.isNull()) 2491 ObjectIsId = ObjectIsClass = false; 2492 else if (!ObjectType->isObjCObjectPointerType()) 2493 return nullptr; 2494 else if (const ObjCObjectPointerType *ObjCPtr = 2495 ObjectType->getAsObjCInterfacePointerType()) { 2496 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 2497 ObjectIsId = ObjectIsClass = false; 2498 } 2499 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 2500 ObjectIsClass = false; 2501 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 2502 ObjectIsId = false; 2503 else 2504 return nullptr; 2505 2506 for (GlobalMethodPool::iterator b = MethodPool.begin(), 2507 e = MethodPool.end(); b != e; b++) { 2508 // instance methods 2509 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 2510 if (M->Method && 2511 (M->Method->getSelector().getNumArgs() == NumArgs) && 2512 (M->Method->getSelector() != Sel)) { 2513 if (ObjectIsId) 2514 Methods.push_back(M->Method); 2515 else if (!ObjectIsClass && 2516 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType)) 2517 Methods.push_back(M->Method); 2518 } 2519 // class methods 2520 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 2521 if (M->Method && 2522 (M->Method->getSelector().getNumArgs() == NumArgs) && 2523 (M->Method->getSelector() != Sel)) { 2524 if (ObjectIsClass) 2525 Methods.push_back(M->Method); 2526 else if (!ObjectIsId && 2527 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType)) 2528 Methods.push_back(M->Method); 2529 } 2530 } 2531 2532 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 2533 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 2534 HelperSelectorsForTypoCorrection(SelectedMethods, 2535 Sel.getAsString(), Methods[i]); 2536 } 2537 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr; 2538 } 2539 2540 /// DiagnoseDuplicateIvars - 2541 /// Check for duplicate ivars in the entire class at the start of 2542 /// \@implementation. This becomes necesssary because class extension can 2543 /// add ivars to a class in random order which will not be known until 2544 /// class's \@implementation is seen. 2545 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 2546 ObjCInterfaceDecl *SID) { 2547 for (auto *Ivar : ID->ivars()) { 2548 if (Ivar->isInvalidDecl()) 2549 continue; 2550 if (IdentifierInfo *II = Ivar->getIdentifier()) { 2551 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 2552 if (prevIvar) { 2553 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 2554 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 2555 Ivar->setInvalidDecl(); 2556 } 2557 } 2558 } 2559 } 2560 2561 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 2562 switch (CurContext->getDeclKind()) { 2563 case Decl::ObjCInterface: 2564 return Sema::OCK_Interface; 2565 case Decl::ObjCProtocol: 2566 return Sema::OCK_Protocol; 2567 case Decl::ObjCCategory: 2568 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 2569 return Sema::OCK_ClassExtension; 2570 else 2571 return Sema::OCK_Category; 2572 case Decl::ObjCImplementation: 2573 return Sema::OCK_Implementation; 2574 case Decl::ObjCCategoryImpl: 2575 return Sema::OCK_CategoryImplementation; 2576 2577 default: 2578 return Sema::OCK_None; 2579 } 2580 } 2581 2582 // Note: For class/category implementations, allMethods is always null. 2583 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 2584 ArrayRef<DeclGroupPtrTy> allTUVars) { 2585 if (getObjCContainerKind() == Sema::OCK_None) 2586 return nullptr; 2587 2588 assert(AtEnd.isValid() && "Invalid location for '@end'"); 2589 2590 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 2591 Decl *ClassDecl = cast<Decl>(OCD); 2592 2593 bool isInterfaceDeclKind = 2594 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 2595 || isa<ObjCProtocolDecl>(ClassDecl); 2596 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 2597 2598 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 2599 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 2600 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 2601 2602 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 2603 ObjCMethodDecl *Method = 2604 cast_or_null<ObjCMethodDecl>(allMethods[i]); 2605 2606 if (!Method) continue; // Already issued a diagnostic. 2607 if (Method->isInstanceMethod()) { 2608 /// Check for instance method of the same name with incompatible types 2609 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 2610 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2611 : false; 2612 if ((isInterfaceDeclKind && PrevMethod && !match) 2613 || (checkIdenticalMethods && match)) { 2614 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2615 << Method->getDeclName(); 2616 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2617 Method->setInvalidDecl(); 2618 } else { 2619 if (PrevMethod) { 2620 Method->setAsRedeclaration(PrevMethod); 2621 if (!Context.getSourceManager().isInSystemHeader( 2622 Method->getLocation())) 2623 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2624 << Method->getDeclName(); 2625 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2626 } 2627 InsMap[Method->getSelector()] = Method; 2628 /// The following allows us to typecheck messages to "id". 2629 AddInstanceMethodToGlobalPool(Method); 2630 } 2631 } else { 2632 /// Check for class method of the same name with incompatible types 2633 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 2634 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2635 : false; 2636 if ((isInterfaceDeclKind && PrevMethod && !match) 2637 || (checkIdenticalMethods && match)) { 2638 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2639 << Method->getDeclName(); 2640 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2641 Method->setInvalidDecl(); 2642 } else { 2643 if (PrevMethod) { 2644 Method->setAsRedeclaration(PrevMethod); 2645 if (!Context.getSourceManager().isInSystemHeader( 2646 Method->getLocation())) 2647 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2648 << Method->getDeclName(); 2649 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2650 } 2651 ClsMap[Method->getSelector()] = Method; 2652 AddFactoryMethodToGlobalPool(Method); 2653 } 2654 } 2655 } 2656 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 2657 // Nothing to do here. 2658 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 2659 // Categories are used to extend the class by declaring new methods. 2660 // By the same token, they are also used to add new properties. No 2661 // need to compare the added property to those in the class. 2662 2663 if (C->IsClassExtension()) { 2664 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 2665 DiagnoseClassExtensionDupMethods(C, CCPrimary); 2666 } 2667 } 2668 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 2669 if (CDecl->getIdentifier()) 2670 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 2671 // user-defined setter/getter. It also synthesizes setter/getter methods 2672 // and adds them to the DeclContext and global method pools. 2673 for (auto *I : CDecl->properties()) 2674 ProcessPropertyDecl(I, CDecl); 2675 CDecl->setAtEndRange(AtEnd); 2676 } 2677 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 2678 IC->setAtEndRange(AtEnd); 2679 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 2680 // Any property declared in a class extension might have user 2681 // declared setter or getter in current class extension or one 2682 // of the other class extensions. Mark them as synthesized as 2683 // property will be synthesized when property with same name is 2684 // seen in the @implementation. 2685 for (const auto *Ext : IDecl->visible_extensions()) { 2686 for (const auto *Property : Ext->properties()) { 2687 // Skip over properties declared @dynamic 2688 if (const ObjCPropertyImplDecl *PIDecl 2689 = IC->FindPropertyImplDecl(Property->getIdentifier())) 2690 if (PIDecl->getPropertyImplementation() 2691 == ObjCPropertyImplDecl::Dynamic) 2692 continue; 2693 2694 for (const auto *Ext : IDecl->visible_extensions()) { 2695 if (ObjCMethodDecl *GetterMethod 2696 = Ext->getInstanceMethod(Property->getGetterName())) 2697 GetterMethod->setPropertyAccessor(true); 2698 if (!Property->isReadOnly()) 2699 if (ObjCMethodDecl *SetterMethod 2700 = Ext->getInstanceMethod(Property->getSetterName())) 2701 SetterMethod->setPropertyAccessor(true); 2702 } 2703 } 2704 } 2705 ImplMethodsVsClassMethods(S, IC, IDecl); 2706 AtomicPropertySetterGetterRules(IC, IDecl); 2707 DiagnoseOwningPropertyGetterSynthesis(IC); 2708 DiagnoseUnusedBackingIvarInAccessor(S, IC); 2709 if (IDecl->hasDesignatedInitializers()) 2710 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 2711 2712 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 2713 if (IDecl->getSuperClass() == nullptr) { 2714 // This class has no superclass, so check that it has been marked with 2715 // __attribute((objc_root_class)). 2716 if (!HasRootClassAttr) { 2717 SourceLocation DeclLoc(IDecl->getLocation()); 2718 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc)); 2719 Diag(DeclLoc, diag::warn_objc_root_class_missing) 2720 << IDecl->getIdentifier(); 2721 // See if NSObject is in the current scope, and if it is, suggest 2722 // adding " : NSObject " to the class declaration. 2723 NamedDecl *IF = LookupSingleName(TUScope, 2724 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 2725 DeclLoc, LookupOrdinaryName); 2726 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 2727 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 2728 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 2729 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 2730 } else { 2731 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 2732 } 2733 } 2734 } else if (HasRootClassAttr) { 2735 // Complain that only root classes may have this attribute. 2736 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 2737 } 2738 2739 if (LangOpts.ObjCRuntime.isNonFragile()) { 2740 while (IDecl->getSuperClass()) { 2741 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 2742 IDecl = IDecl->getSuperClass(); 2743 } 2744 } 2745 } 2746 SetIvarInitializers(IC); 2747 } else if (ObjCCategoryImplDecl* CatImplClass = 2748 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 2749 CatImplClass->setAtEndRange(AtEnd); 2750 2751 // Find category interface decl and then check that all methods declared 2752 // in this interface are implemented in the category @implementation. 2753 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 2754 if (ObjCCategoryDecl *Cat 2755 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 2756 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 2757 } 2758 } 2759 } 2760 if (isInterfaceDeclKind) { 2761 // Reject invalid vardecls. 2762 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 2763 DeclGroupRef DG = allTUVars[i].get(); 2764 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2765 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 2766 if (!VDecl->hasExternalStorage()) 2767 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 2768 } 2769 } 2770 } 2771 ActOnObjCContainerFinishDefinition(); 2772 2773 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 2774 DeclGroupRef DG = allTUVars[i].get(); 2775 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2776 (*I)->setTopLevelDeclInObjCContainer(); 2777 Consumer.HandleTopLevelDeclInObjCContainer(DG); 2778 } 2779 2780 ActOnDocumentableDecl(ClassDecl); 2781 return ClassDecl; 2782 } 2783 2784 2785 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 2786 /// objective-c's type qualifier from the parser version of the same info. 2787 static Decl::ObjCDeclQualifier 2788 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 2789 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 2790 } 2791 2792 /// \brief Check whether the declared result type of the given Objective-C 2793 /// method declaration is compatible with the method's class. 2794 /// 2795 static Sema::ResultTypeCompatibilityKind 2796 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 2797 ObjCInterfaceDecl *CurrentClass) { 2798 QualType ResultType = Method->getReturnType(); 2799 2800 // If an Objective-C method inherits its related result type, then its 2801 // declared result type must be compatible with its own class type. The 2802 // declared result type is compatible if: 2803 if (const ObjCObjectPointerType *ResultObjectType 2804 = ResultType->getAs<ObjCObjectPointerType>()) { 2805 // - it is id or qualified id, or 2806 if (ResultObjectType->isObjCIdType() || 2807 ResultObjectType->isObjCQualifiedIdType()) 2808 return Sema::RTC_Compatible; 2809 2810 if (CurrentClass) { 2811 if (ObjCInterfaceDecl *ResultClass 2812 = ResultObjectType->getInterfaceDecl()) { 2813 // - it is the same as the method's class type, or 2814 if (declaresSameEntity(CurrentClass, ResultClass)) 2815 return Sema::RTC_Compatible; 2816 2817 // - it is a superclass of the method's class type 2818 if (ResultClass->isSuperClassOf(CurrentClass)) 2819 return Sema::RTC_Compatible; 2820 } 2821 } else { 2822 // Any Objective-C pointer type might be acceptable for a protocol 2823 // method; we just don't know. 2824 return Sema::RTC_Unknown; 2825 } 2826 } 2827 2828 return Sema::RTC_Incompatible; 2829 } 2830 2831 namespace { 2832 /// A helper class for searching for methods which a particular method 2833 /// overrides. 2834 class OverrideSearch { 2835 public: 2836 Sema &S; 2837 ObjCMethodDecl *Method; 2838 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 2839 bool Recursive; 2840 2841 public: 2842 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 2843 Selector selector = method->getSelector(); 2844 2845 // Bypass this search if we've never seen an instance/class method 2846 // with this selector before. 2847 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 2848 if (it == S.MethodPool.end()) { 2849 if (!S.getExternalSource()) return; 2850 S.ReadMethodPool(selector); 2851 2852 it = S.MethodPool.find(selector); 2853 if (it == S.MethodPool.end()) 2854 return; 2855 } 2856 ObjCMethodList &list = 2857 method->isInstanceMethod() ? it->second.first : it->second.second; 2858 if (!list.Method) return; 2859 2860 ObjCContainerDecl *container 2861 = cast<ObjCContainerDecl>(method->getDeclContext()); 2862 2863 // Prevent the search from reaching this container again. This is 2864 // important with categories, which override methods from the 2865 // interface and each other. 2866 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 2867 searchFromContainer(container); 2868 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 2869 searchFromContainer(Interface); 2870 } else { 2871 searchFromContainer(container); 2872 } 2873 } 2874 2875 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 2876 iterator begin() const { return Overridden.begin(); } 2877 iterator end() const { return Overridden.end(); } 2878 2879 private: 2880 void searchFromContainer(ObjCContainerDecl *container) { 2881 if (container->isInvalidDecl()) return; 2882 2883 switch (container->getDeclKind()) { 2884 #define OBJCCONTAINER(type, base) \ 2885 case Decl::type: \ 2886 searchFrom(cast<type##Decl>(container)); \ 2887 break; 2888 #define ABSTRACT_DECL(expansion) 2889 #define DECL(type, base) \ 2890 case Decl::type: 2891 #include "clang/AST/DeclNodes.inc" 2892 llvm_unreachable("not an ObjC container!"); 2893 } 2894 } 2895 2896 void searchFrom(ObjCProtocolDecl *protocol) { 2897 if (!protocol->hasDefinition()) 2898 return; 2899 2900 // A method in a protocol declaration overrides declarations from 2901 // referenced ("parent") protocols. 2902 search(protocol->getReferencedProtocols()); 2903 } 2904 2905 void searchFrom(ObjCCategoryDecl *category) { 2906 // A method in a category declaration overrides declarations from 2907 // the main class and from protocols the category references. 2908 // The main class is handled in the constructor. 2909 search(category->getReferencedProtocols()); 2910 } 2911 2912 void searchFrom(ObjCCategoryImplDecl *impl) { 2913 // A method in a category definition that has a category 2914 // declaration overrides declarations from the category 2915 // declaration. 2916 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 2917 search(category); 2918 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 2919 search(Interface); 2920 2921 // Otherwise it overrides declarations from the class. 2922 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 2923 search(Interface); 2924 } 2925 } 2926 2927 void searchFrom(ObjCInterfaceDecl *iface) { 2928 // A method in a class declaration overrides declarations from 2929 if (!iface->hasDefinition()) 2930 return; 2931 2932 // - categories, 2933 for (auto *Cat : iface->known_categories()) 2934 search(Cat); 2935 2936 // - the super class, and 2937 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 2938 search(super); 2939 2940 // - any referenced protocols. 2941 search(iface->getReferencedProtocols()); 2942 } 2943 2944 void searchFrom(ObjCImplementationDecl *impl) { 2945 // A method in a class implementation overrides declarations from 2946 // the class interface. 2947 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 2948 search(Interface); 2949 } 2950 2951 2952 void search(const ObjCProtocolList &protocols) { 2953 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 2954 i != e; ++i) 2955 search(*i); 2956 } 2957 2958 void search(ObjCContainerDecl *container) { 2959 // Check for a method in this container which matches this selector. 2960 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 2961 Method->isInstanceMethod(), 2962 /*AllowHidden=*/true); 2963 2964 // If we find one, record it and bail out. 2965 if (meth) { 2966 Overridden.insert(meth); 2967 return; 2968 } 2969 2970 // Otherwise, search for methods that a hypothetical method here 2971 // would have overridden. 2972 2973 // Note that we're now in a recursive case. 2974 Recursive = true; 2975 2976 searchFromContainer(container); 2977 } 2978 }; 2979 } 2980 2981 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 2982 ObjCInterfaceDecl *CurrentClass, 2983 ResultTypeCompatibilityKind RTC) { 2984 // Search for overridden methods and merge information down from them. 2985 OverrideSearch overrides(*this, ObjCMethod); 2986 // Keep track if the method overrides any method in the class's base classes, 2987 // its protocols, or its categories' protocols; we will keep that info 2988 // in the ObjCMethodDecl. 2989 // For this info, a method in an implementation is not considered as 2990 // overriding the same method in the interface or its categories. 2991 bool hasOverriddenMethodsInBaseOrProtocol = false; 2992 for (OverrideSearch::iterator 2993 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 2994 ObjCMethodDecl *overridden = *i; 2995 2996 if (!hasOverriddenMethodsInBaseOrProtocol) { 2997 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 2998 CurrentClass != overridden->getClassInterface() || 2999 overridden->isOverriding()) { 3000 hasOverriddenMethodsInBaseOrProtocol = true; 3001 3002 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 3003 // OverrideSearch will return as "overridden" the same method in the 3004 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 3005 // check whether a category of a base class introduced a method with the 3006 // same selector, after the interface method declaration. 3007 // To avoid unnecessary lookups in the majority of cases, we use the 3008 // extra info bits in GlobalMethodPool to check whether there were any 3009 // category methods with this selector. 3010 GlobalMethodPool::iterator It = 3011 MethodPool.find(ObjCMethod->getSelector()); 3012 if (It != MethodPool.end()) { 3013 ObjCMethodList &List = 3014 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 3015 unsigned CategCount = List.getBits(); 3016 if (CategCount > 0) { 3017 // If the method is in a category we'll do lookup if there were at 3018 // least 2 category methods recorded, otherwise only one will do. 3019 if (CategCount > 1 || 3020 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 3021 OverrideSearch overrides(*this, overridden); 3022 for (OverrideSearch::iterator 3023 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) { 3024 ObjCMethodDecl *SuperOverridden = *OI; 3025 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 3026 CurrentClass != SuperOverridden->getClassInterface()) { 3027 hasOverriddenMethodsInBaseOrProtocol = true; 3028 overridden->setOverriding(true); 3029 break; 3030 } 3031 } 3032 } 3033 } 3034 } 3035 } 3036 } 3037 3038 // Propagate down the 'related result type' bit from overridden methods. 3039 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 3040 ObjCMethod->SetRelatedResultType(); 3041 3042 // Then merge the declarations. 3043 mergeObjCMethodDecls(ObjCMethod, overridden); 3044 3045 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 3046 continue; // Conflicting properties are detected elsewhere. 3047 3048 // Check for overriding methods 3049 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 3050 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 3051 CheckConflictingOverridingMethod(ObjCMethod, overridden, 3052 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 3053 3054 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 3055 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 3056 !overridden->isImplicit() /* not meant for properties */) { 3057 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 3058 E = ObjCMethod->param_end(); 3059 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 3060 PrevE = overridden->param_end(); 3061 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 3062 assert(PrevI != overridden->param_end() && "Param mismatch"); 3063 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 3064 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 3065 // If type of argument of method in this class does not match its 3066 // respective argument type in the super class method, issue warning; 3067 if (!Context.typesAreCompatible(T1, T2)) { 3068 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 3069 << T1 << T2; 3070 Diag(overridden->getLocation(), diag::note_previous_declaration); 3071 break; 3072 } 3073 } 3074 } 3075 } 3076 3077 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 3078 } 3079 3080 Decl *Sema::ActOnMethodDeclaration( 3081 Scope *S, 3082 SourceLocation MethodLoc, SourceLocation EndLoc, 3083 tok::TokenKind MethodType, 3084 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 3085 ArrayRef<SourceLocation> SelectorLocs, 3086 Selector Sel, 3087 // optional arguments. The number of types/arguments is obtained 3088 // from the Sel.getNumArgs(). 3089 ObjCArgInfo *ArgInfo, 3090 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 3091 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 3092 bool isVariadic, bool MethodDefinition) { 3093 // Make sure we can establish a context for the method. 3094 if (!CurContext->isObjCContainer()) { 3095 Diag(MethodLoc, diag::error_missing_method_context); 3096 return nullptr; 3097 } 3098 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 3099 Decl *ClassDecl = cast<Decl>(OCD); 3100 QualType resultDeclType; 3101 3102 bool HasRelatedResultType = false; 3103 TypeSourceInfo *ReturnTInfo = nullptr; 3104 if (ReturnType) { 3105 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo); 3106 3107 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 3108 return nullptr; 3109 3110 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType()); 3111 } else { // get the type for "id". 3112 resultDeclType = Context.getObjCIdType(); 3113 Diag(MethodLoc, diag::warn_missing_method_return_type) 3114 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 3115 } 3116 3117 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create( 3118 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext, 3119 MethodType == tok::minus, isVariadic, 3120 /*isPropertyAccessor=*/false, 3121 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 3122 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional 3123 : ObjCMethodDecl::Required, 3124 HasRelatedResultType); 3125 3126 SmallVector<ParmVarDecl*, 16> Params; 3127 3128 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 3129 QualType ArgType; 3130 TypeSourceInfo *DI; 3131 3132 if (!ArgInfo[i].Type) { 3133 ArgType = Context.getObjCIdType(); 3134 DI = nullptr; 3135 } else { 3136 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 3137 } 3138 3139 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 3140 LookupOrdinaryName, ForRedeclaration); 3141 LookupName(R, S); 3142 if (R.isSingleResult()) { 3143 NamedDecl *PrevDecl = R.getFoundDecl(); 3144 if (S->isDeclScope(PrevDecl)) { 3145 Diag(ArgInfo[i].NameLoc, 3146 (MethodDefinition ? diag::warn_method_param_redefinition 3147 : diag::warn_method_param_declaration)) 3148 << ArgInfo[i].Name; 3149 Diag(PrevDecl->getLocation(), 3150 diag::note_previous_declaration); 3151 } 3152 } 3153 3154 SourceLocation StartLoc = DI 3155 ? DI->getTypeLoc().getBeginLoc() 3156 : ArgInfo[i].NameLoc; 3157 3158 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 3159 ArgInfo[i].NameLoc, ArgInfo[i].Name, 3160 ArgType, DI, SC_None); 3161 3162 Param->setObjCMethodScopeInfo(i); 3163 3164 Param->setObjCDeclQualifier( 3165 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 3166 3167 // Apply the attributes to the parameter. 3168 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 3169 3170 if (Param->hasAttr<BlocksAttr>()) { 3171 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 3172 Param->setInvalidDecl(); 3173 } 3174 S->AddDecl(Param); 3175 IdResolver.AddDecl(Param); 3176 3177 Params.push_back(Param); 3178 } 3179 3180 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 3181 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 3182 QualType ArgType = Param->getType(); 3183 if (ArgType.isNull()) 3184 ArgType = Context.getObjCIdType(); 3185 else 3186 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 3187 ArgType = Context.getAdjustedParameterType(ArgType); 3188 3189 Param->setDeclContext(ObjCMethod); 3190 Params.push_back(Param); 3191 } 3192 3193 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 3194 ObjCMethod->setObjCDeclQualifier( 3195 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 3196 3197 if (AttrList) 3198 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 3199 3200 // Add the method now. 3201 const ObjCMethodDecl *PrevMethod = nullptr; 3202 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 3203 if (MethodType == tok::minus) { 3204 PrevMethod = ImpDecl->getInstanceMethod(Sel); 3205 ImpDecl->addInstanceMethod(ObjCMethod); 3206 } else { 3207 PrevMethod = ImpDecl->getClassMethod(Sel); 3208 ImpDecl->addClassMethod(ObjCMethod); 3209 } 3210 3211 ObjCMethodDecl *IMD = nullptr; 3212 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) 3213 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 3214 ObjCMethod->isInstanceMethod()); 3215 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() && 3216 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) { 3217 // merge the attribute into implementation. 3218 ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context, 3219 ObjCMethod->getLocation())); 3220 } 3221 if (isa<ObjCCategoryImplDecl>(ImpDecl)) { 3222 ObjCMethodFamily family = 3223 ObjCMethod->getSelector().getMethodFamily(); 3224 if (family == OMF_dealloc && IMD && IMD->isOverriding()) 3225 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 3226 << ObjCMethod->getDeclName(); 3227 } 3228 } else { 3229 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 3230 } 3231 3232 if (PrevMethod) { 3233 // You can never have two method definitions with the same name. 3234 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 3235 << ObjCMethod->getDeclName(); 3236 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3237 ObjCMethod->setInvalidDecl(); 3238 return ObjCMethod; 3239 } 3240 3241 // If this Objective-C method does not have a related result type, but we 3242 // are allowed to infer related result types, try to do so based on the 3243 // method family. 3244 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 3245 if (!CurrentClass) { 3246 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 3247 CurrentClass = Cat->getClassInterface(); 3248 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 3249 CurrentClass = Impl->getClassInterface(); 3250 else if (ObjCCategoryImplDecl *CatImpl 3251 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 3252 CurrentClass = CatImpl->getClassInterface(); 3253 } 3254 3255 ResultTypeCompatibilityKind RTC 3256 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 3257 3258 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 3259 3260 bool ARCError = false; 3261 if (getLangOpts().ObjCAutoRefCount) 3262 ARCError = CheckARCMethodDecl(ObjCMethod); 3263 3264 // Infer the related result type when possible. 3265 if (!ARCError && RTC == Sema::RTC_Compatible && 3266 !ObjCMethod->hasRelatedResultType() && 3267 LangOpts.ObjCInferRelatedResultType) { 3268 bool InferRelatedResultType = false; 3269 switch (ObjCMethod->getMethodFamily()) { 3270 case OMF_None: 3271 case OMF_copy: 3272 case OMF_dealloc: 3273 case OMF_finalize: 3274 case OMF_mutableCopy: 3275 case OMF_release: 3276 case OMF_retainCount: 3277 case OMF_initialize: 3278 case OMF_performSelector: 3279 break; 3280 3281 case OMF_alloc: 3282 case OMF_new: 3283 InferRelatedResultType = ObjCMethod->isClassMethod(); 3284 break; 3285 3286 case OMF_init: 3287 case OMF_autorelease: 3288 case OMF_retain: 3289 case OMF_self: 3290 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 3291 break; 3292 } 3293 3294 if (InferRelatedResultType) 3295 ObjCMethod->SetRelatedResultType(); 3296 } 3297 3298 ActOnDocumentableDecl(ObjCMethod); 3299 3300 return ObjCMethod; 3301 } 3302 3303 bool Sema::CheckObjCDeclScope(Decl *D) { 3304 // Following is also an error. But it is caused by a missing @end 3305 // and diagnostic is issued elsewhere. 3306 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 3307 return false; 3308 3309 // If we switched context to translation unit while we are still lexically in 3310 // an objc container, it means the parser missed emitting an error. 3311 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 3312 return false; 3313 3314 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 3315 D->setInvalidDecl(); 3316 3317 return true; 3318 } 3319 3320 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 3321 /// instance variables of ClassName into Decls. 3322 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 3323 IdentifierInfo *ClassName, 3324 SmallVectorImpl<Decl*> &Decls) { 3325 // Check that ClassName is a valid class 3326 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 3327 if (!Class) { 3328 Diag(DeclStart, diag::err_undef_interface) << ClassName; 3329 return; 3330 } 3331 if (LangOpts.ObjCRuntime.isNonFragile()) { 3332 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 3333 return; 3334 } 3335 3336 // Collect the instance variables 3337 SmallVector<const ObjCIvarDecl*, 32> Ivars; 3338 Context.DeepCollectObjCIvars(Class, true, Ivars); 3339 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 3340 for (unsigned i = 0; i < Ivars.size(); i++) { 3341 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 3342 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 3343 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 3344 /*FIXME: StartL=*/ID->getLocation(), 3345 ID->getLocation(), 3346 ID->getIdentifier(), ID->getType(), 3347 ID->getBitWidth()); 3348 Decls.push_back(FD); 3349 } 3350 3351 // Introduce all of these fields into the appropriate scope. 3352 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 3353 D != Decls.end(); ++D) { 3354 FieldDecl *FD = cast<FieldDecl>(*D); 3355 if (getLangOpts().CPlusPlus) 3356 PushOnScopeChains(cast<FieldDecl>(FD), S); 3357 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 3358 Record->addDecl(FD); 3359 } 3360 } 3361 3362 /// \brief Build a type-check a new Objective-C exception variable declaration. 3363 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 3364 SourceLocation StartLoc, 3365 SourceLocation IdLoc, 3366 IdentifierInfo *Id, 3367 bool Invalid) { 3368 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 3369 // duration shall not be qualified by an address-space qualifier." 3370 // Since all parameters have automatic store duration, they can not have 3371 // an address space. 3372 if (T.getAddressSpace() != 0) { 3373 Diag(IdLoc, diag::err_arg_with_address_space); 3374 Invalid = true; 3375 } 3376 3377 // An @catch parameter must be an unqualified object pointer type; 3378 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 3379 if (Invalid) { 3380 // Don't do any further checking. 3381 } else if (T->isDependentType()) { 3382 // Okay: we don't know what this type will instantiate to. 3383 } else if (!T->isObjCObjectPointerType()) { 3384 Invalid = true; 3385 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 3386 } else if (T->isObjCQualifiedIdType()) { 3387 Invalid = true; 3388 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 3389 } 3390 3391 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 3392 T, TInfo, SC_None); 3393 New->setExceptionVariable(true); 3394 3395 // In ARC, infer 'retaining' for variables of retainable type. 3396 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 3397 Invalid = true; 3398 3399 if (Invalid) 3400 New->setInvalidDecl(); 3401 return New; 3402 } 3403 3404 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 3405 const DeclSpec &DS = D.getDeclSpec(); 3406 3407 // We allow the "register" storage class on exception variables because 3408 // GCC did, but we drop it completely. Any other storage class is an error. 3409 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 3410 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 3411 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 3412 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3413 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 3414 << DeclSpec::getSpecifierName(SCS); 3415 } 3416 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 3417 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 3418 diag::err_invalid_thread) 3419 << DeclSpec::getSpecifierName(TSCS); 3420 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3421 3422 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 3423 3424 // Check that there are no default arguments inside the type of this 3425 // exception object (C++ only). 3426 if (getLangOpts().CPlusPlus) 3427 CheckExtraCXXDefaultArguments(D); 3428 3429 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3430 QualType ExceptionType = TInfo->getType(); 3431 3432 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 3433 D.getSourceRange().getBegin(), 3434 D.getIdentifierLoc(), 3435 D.getIdentifier(), 3436 D.isInvalidType()); 3437 3438 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 3439 if (D.getCXXScopeSpec().isSet()) { 3440 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 3441 << D.getCXXScopeSpec().getRange(); 3442 New->setInvalidDecl(); 3443 } 3444 3445 // Add the parameter declaration into this scope. 3446 S->AddDecl(New); 3447 if (D.getIdentifier()) 3448 IdResolver.AddDecl(New); 3449 3450 ProcessDeclAttributes(S, New, D); 3451 3452 if (New->hasAttr<BlocksAttr>()) 3453 Diag(New->getLocation(), diag::err_block_on_nonlocal); 3454 return New; 3455 } 3456 3457 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 3458 /// initialization. 3459 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 3460 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 3461 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 3462 Iv= Iv->getNextIvar()) { 3463 QualType QT = Context.getBaseElementType(Iv->getType()); 3464 if (QT->isRecordType()) 3465 Ivars.push_back(Iv); 3466 } 3467 } 3468 3469 void Sema::DiagnoseUseOfUnimplementedSelectors() { 3470 // Load referenced selectors from the external source. 3471 if (ExternalSource) { 3472 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 3473 ExternalSource->ReadReferencedSelectors(Sels); 3474 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 3475 ReferencedSelectors[Sels[I].first] = Sels[I].second; 3476 } 3477 3478 // Warning will be issued only when selector table is 3479 // generated (which means there is at lease one implementation 3480 // in the TU). This is to match gcc's behavior. 3481 if (ReferencedSelectors.empty() || 3482 !Context.AnyObjCImplementation()) 3483 return; 3484 for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 3485 ReferencedSelectors.begin(), 3486 E = ReferencedSelectors.end(); S != E; ++S) { 3487 Selector Sel = (*S).first; 3488 if (!LookupImplementedMethodInGlobalPool(Sel)) 3489 Diag((*S).second, diag::warn_unimplemented_selector) << Sel; 3490 } 3491 return; 3492 } 3493 3494 ObjCIvarDecl * 3495 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 3496 const ObjCPropertyDecl *&PDecl) const { 3497 if (Method->isClassMethod()) 3498 return nullptr; 3499 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 3500 if (!IDecl) 3501 return nullptr; 3502 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 3503 /*shallowCategoryLookup=*/false, 3504 /*followSuper=*/false); 3505 if (!Method || !Method->isPropertyAccessor()) 3506 return nullptr; 3507 if ((PDecl = Method->findPropertyDecl())) 3508 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) { 3509 // property backing ivar must belong to property's class 3510 // or be a private ivar in class's implementation. 3511 // FIXME. fix the const-ness issue. 3512 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable( 3513 IV->getIdentifier()); 3514 return IV; 3515 } 3516 return nullptr; 3517 } 3518 3519 namespace { 3520 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 3521 /// accessor references the backing ivar. 3522 class UnusedBackingIvarChecker : 3523 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> { 3524 public: 3525 Sema &S; 3526 const ObjCMethodDecl *Method; 3527 const ObjCIvarDecl *IvarD; 3528 bool AccessedIvar; 3529 bool InvokedSelfMethod; 3530 3531 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 3532 const ObjCIvarDecl *IvarD) 3533 : S(S), Method(Method), IvarD(IvarD), 3534 AccessedIvar(false), InvokedSelfMethod(false) { 3535 assert(IvarD); 3536 } 3537 3538 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 3539 if (E->getDecl() == IvarD) { 3540 AccessedIvar = true; 3541 return false; 3542 } 3543 return true; 3544 } 3545 3546 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 3547 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 3548 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 3549 InvokedSelfMethod = true; 3550 } 3551 return true; 3552 } 3553 }; 3554 } 3555 3556 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 3557 const ObjCImplementationDecl *ImplD) { 3558 if (S->hasUnrecoverableErrorOccurred()) 3559 return; 3560 3561 for (const auto *CurMethod : ImplD->instance_methods()) { 3562 unsigned DIAG = diag::warn_unused_property_backing_ivar; 3563 SourceLocation Loc = CurMethod->getLocation(); 3564 if (Diags.isIgnored(DIAG, Loc)) 3565 continue; 3566 3567 const ObjCPropertyDecl *PDecl; 3568 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 3569 if (!IV) 3570 continue; 3571 3572 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 3573 Checker.TraverseStmt(CurMethod->getBody()); 3574 if (Checker.AccessedIvar) 3575 continue; 3576 3577 // Do not issue this warning if backing ivar is used somewhere and accessor 3578 // implementation makes a self call. This is to prevent false positive in 3579 // cases where the ivar is accessed by another method that the accessor 3580 // delegates to. 3581 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 3582 Diag(Loc, DIAG) << IV; 3583 Diag(PDecl->getLocation(), diag::note_property_declare); 3584 } 3585 } 3586 } 3587