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