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