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