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