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