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