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