1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective C declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DataRecursiveASTVisitor.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ExternalSemaSource.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/DenseSet.h"
30 using namespace clang;
32 /// Check whether the given method, which must be in the 'init'
33 /// family, is a valid member of that family.
35 /// \param receiverTypeIfCall - if null, check this as if declaring it;
36 /// if non-null, check this as if making a call to it with the given
39 /// \return true to indicate that there was an error and appropriate
40 /// actions were taken
41 bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
49 // We ignore protocols here. Should we? What about Class?
51 const ObjCObjectType *result =
52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
54 if (result->isObjCId()) {
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
64 if (!resultClass->hasDefinition()) {
65 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
69 // Otherwise, we try to compare class types.
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
73 const ObjCInterfaceDecl *receiverClass = nullptr;
74 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
95 SourceLocation loc = method->getLocation();
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
100 method->addAttr(UnavailableAttr::CreateImplicit(Context,
101 "init method returns a type unrelated to its receiver type",
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
112 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
113 const ObjCMethodDecl *Overridden) {
114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
120 QualType ResultType = NewMethod->getReturnType();
121 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
123 // Figure out which class this method is part of, if any.
124 ObjCInterfaceDecl *CurrentClass
125 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
127 DeclContext *DC = NewMethod->getDeclContext();
128 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
129 CurrentClass = Cat->getClassInterface();
130 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
131 CurrentClass = Impl->getClassInterface();
132 else if (ObjCCategoryImplDecl *CatImpl
133 = dyn_cast<ObjCCategoryImplDecl>(DC))
134 CurrentClass = CatImpl->getClassInterface();
138 Diag(NewMethod->getLocation(),
139 diag::warn_related_result_type_compatibility_class)
140 << Context.getObjCInterfaceType(CurrentClass)
144 Diag(NewMethod->getLocation(),
145 diag::warn_related_result_type_compatibility_protocol)
150 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151 Diag(Overridden->getLocation(),
152 diag::note_related_result_type_family)
153 << /*overridden method*/ 0
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
159 if (getLangOpts().ObjCAutoRefCount) {
160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
163 diag::err_nsreturns_retained_attribute_mismatch) << 1;
164 Diag(Overridden->getLocation(), diag::note_previous_decl)
167 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
168 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
169 Diag(NewMethod->getLocation(),
170 diag::err_nsreturns_retained_attribute_mismatch) << 0;
171 Diag(Overridden->getLocation(), diag::note_previous_decl)
174 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
175 oe = Overridden->param_end();
176 for (ObjCMethodDecl::param_iterator
177 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
178 ni != ne && oi != oe; ++ni, ++oi) {
179 const ParmVarDecl *oldDecl = (*oi);
180 ParmVarDecl *newDecl = (*ni);
181 if (newDecl->hasAttr<NSConsumedAttr>() !=
182 oldDecl->hasAttr<NSConsumedAttr>()) {
183 Diag(newDecl->getLocation(),
184 diag::err_nsconsumed_attribute_mismatch);
185 Diag(oldDecl->getLocation(), diag::note_previous_decl)
192 /// \brief Check a method declaration for compatibility with the Objective-C
194 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
195 ObjCMethodFamily family = method->getMethodFamily();
201 case OMF_autorelease:
202 case OMF_retainCount:
205 case OMF_performSelector:
209 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
210 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
211 if (ResultTypeRange.isInvalid())
212 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
213 << method->getReturnType()
214 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
216 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
217 << method->getReturnType()
218 << FixItHint::CreateReplacement(ResultTypeRange, "void");
224 // If the method doesn't obey the init rules, don't bother annotating it.
225 if (checkInitMethod(method, QualType()))
228 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
230 // Don't add a second copy of this attribute, but otherwise don't
231 // let it be suppressed.
232 if (method->hasAttr<NSReturnsRetainedAttr>())
238 case OMF_mutableCopy:
240 if (method->hasAttr<NSReturnsRetainedAttr>() ||
241 method->hasAttr<NSReturnsNotRetainedAttr>() ||
242 method->hasAttr<NSReturnsAutoreleasedAttr>())
247 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
251 static void DiagnoseObjCImplementedDeprecations(Sema &S,
253 SourceLocation ImplLoc,
255 if (ND && ND->isDeprecated()) {
256 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
258 S.Diag(ND->getLocation(), diag::note_method_declared_at)
259 << ND->getDeclName();
261 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
265 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
267 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
268 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
270 // If we don't have a valid method decl, simply return.
273 if (MDecl->isInstanceMethod())
274 AddInstanceMethodToGlobalPool(MDecl, true);
276 AddFactoryMethodToGlobalPool(MDecl, true);
279 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
280 /// has explicit ownership attribute; false otherwise.
282 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
283 QualType T = Param->getType();
285 if (const PointerType *PT = T->getAs<PointerType>()) {
286 T = PT->getPointeeType();
287 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
288 T = RT->getPointeeType();
293 // If we have a lifetime qualifier, but it's local, we must have
294 // inferred it. So, it is implicit.
295 return !T.getLocalQualifiers().hasObjCLifetime();
298 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
299 /// and user declared, in the method definition's AST.
300 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
301 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
302 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
304 // If we don't have a valid method decl, simply return.
308 // Allow all of Sema to see that we are entering a method definition.
309 PushDeclContext(FnBodyScope, MDecl);
312 // Create Decl objects for each parameter, entrring them in the scope for
313 // binding to their use.
315 // Insert the invisible arguments, self and _cmd!
316 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
318 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
319 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
321 // The ObjC parser requires parameter names so there's no need to check.
322 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
323 /*CheckParameterNames=*/false);
325 // Introduce all of the other parameters into this scope.
326 for (auto *Param : MDecl->params()) {
327 if (!Param->isInvalidDecl() &&
328 getLangOpts().ObjCAutoRefCount &&
329 !HasExplicitOwnershipAttr(*this, Param))
330 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
333 if (Param->getIdentifier())
334 PushOnScopeChains(Param, FnBodyScope);
337 // In ARC, disallow definition of retain/release/autorelease/retainCount
338 if (getLangOpts().ObjCAutoRefCount) {
339 switch (MDecl->getMethodFamily()) {
341 case OMF_retainCount:
343 case OMF_autorelease:
344 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
345 << 0 << MDecl->getSelector();
353 case OMF_mutableCopy:
358 case OMF_performSelector:
363 // Warn on deprecated methods under -Wdeprecated-implementations,
364 // and prepare for warning on missing super calls.
365 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
366 ObjCMethodDecl *IMD =
367 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
370 ObjCImplDecl *ImplDeclOfMethodDef =
371 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
372 ObjCContainerDecl *ContDeclOfMethodDecl =
373 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
374 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
375 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
376 ImplDeclOfMethodDecl = OID->getImplementation();
377 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
378 if (CD->IsClassExtension()) {
379 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
380 ImplDeclOfMethodDecl = OID->getImplementation();
382 ImplDeclOfMethodDecl = CD->getImplementation();
384 // No need to issue deprecated warning if deprecated mehod in class/category
385 // is being implemented in its own implementation (no overriding is involved).
386 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
387 DiagnoseObjCImplementedDeprecations(*this,
388 dyn_cast<NamedDecl>(IMD),
389 MDecl->getLocation(), 0);
392 if (MDecl->getMethodFamily() == OMF_init) {
393 if (MDecl->isDesignatedInitializerForTheInterface()) {
394 getCurFunction()->ObjCIsDesignatedInit = true;
395 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
396 IC->getSuperClass() != nullptr;
397 } else if (IC->hasDesignatedInitializers()) {
398 getCurFunction()->ObjCIsSecondaryInit = true;
399 getCurFunction()->ObjCWarnForNoInitDelegation = true;
403 // If this is "dealloc" or "finalize", set some bit here.
404 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
405 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
406 // Only do this if the current class actually has a superclass.
407 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
408 ObjCMethodFamily Family = MDecl->getMethodFamily();
409 if (Family == OMF_dealloc) {
410 if (!(getLangOpts().ObjCAutoRefCount ||
411 getLangOpts().getGC() == LangOptions::GCOnly))
412 getCurFunction()->ObjCShouldCallSuper = true;
414 } else if (Family == OMF_finalize) {
415 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
416 getCurFunction()->ObjCShouldCallSuper = true;
419 const ObjCMethodDecl *SuperMethod =
420 SuperClass->lookupMethod(MDecl->getSelector(),
421 MDecl->isInstanceMethod());
422 getCurFunction()->ObjCShouldCallSuper =
423 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
431 // Callback to only accept typo corrections that are Objective-C classes.
432 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
433 // function will reject corrections to that class.
434 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
436 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
437 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
438 : CurrentIDecl(IDecl) {}
440 bool ValidateCandidate(const TypoCorrection &candidate) override {
441 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
442 return ID && !declaresSameEntity(ID, CurrentIDecl);
446 ObjCInterfaceDecl *CurrentIDecl;
451 static void diagnoseUseOfProtocols(Sema &TheSema,
452 ObjCContainerDecl *CD,
453 ObjCProtocolDecl *const *ProtoRefs,
454 unsigned NumProtoRefs,
455 const SourceLocation *ProtoLocs) {
457 // Diagnose availability in the context of the ObjC container.
458 Sema::ContextRAII SavedContext(TheSema, CD);
459 for (unsigned i = 0; i < NumProtoRefs; ++i) {
460 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]);
465 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
466 IdentifierInfo *ClassName, SourceLocation ClassLoc,
467 IdentifierInfo *SuperName, SourceLocation SuperLoc,
468 Decl * const *ProtoRefs, unsigned NumProtoRefs,
469 const SourceLocation *ProtoLocs,
470 SourceLocation EndProtoLoc, AttributeList *AttrList) {
471 assert(ClassName && "Missing class identifier");
473 // Check for another declaration kind with the same name.
474 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
475 LookupOrdinaryName, ForRedeclaration);
477 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
478 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
479 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
482 // Create a declaration to describe this @interface.
483 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
485 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
486 // A previous decl with a different name is because of
487 // @compatibility_alias, for example:
490 // @compatibility_alias OldImage NewImage;
492 // A lookup for 'OldImage' will return the 'NewImage' decl.
494 // In such a case use the real declaration name, instead of the alias one,
495 // otherwise we will break IdentifierResolver and redecls-chain invariants.
496 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
498 ClassName = PrevIDecl->getIdentifier();
501 ObjCInterfaceDecl *IDecl
502 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
503 PrevIDecl, ClassLoc);
506 // Class already seen. Was it a definition?
507 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
508 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
509 << PrevIDecl->getDeclName();
510 Diag(Def->getLocation(), diag::note_previous_definition);
511 IDecl->setInvalidDecl();
516 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
517 PushOnScopeChains(IDecl, TUScope);
519 // Start the definition of this class. If we're in a redefinition case, there
520 // may already be a definition, so we'll end up adding to it.
521 if (!IDecl->hasDefinition())
522 IDecl->startDefinition();
525 // Check if a different kind of symbol declared in this scope.
526 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
530 // Try to correct for a typo in the superclass name without correcting
531 // to the class we're defining.
532 if (TypoCorrection Corrected =
533 CorrectTypo(DeclarationNameInfo(SuperName, SuperLoc),
534 LookupOrdinaryName, TUScope, nullptr,
535 llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
536 CTK_ErrorRecovery)) {
537 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
538 << SuperName << ClassName);
539 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
543 if (declaresSameEntity(PrevDecl, IDecl)) {
544 Diag(SuperLoc, diag::err_recursive_superclass)
545 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
546 IDecl->setEndOfDefinitionLoc(ClassLoc);
548 ObjCInterfaceDecl *SuperClassDecl =
549 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
551 // Diagnose availability in the context of the @interface.
552 ContextRAII SavedContext(*this, IDecl);
553 // Diagnose classes that inherit from deprecated classes.
555 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
557 if (PrevDecl && !SuperClassDecl) {
558 // The previous declaration was not a class decl. Check if we have a
559 // typedef. If we do, get the underlying class type.
560 if (const TypedefNameDecl *TDecl =
561 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
562 QualType T = TDecl->getUnderlyingType();
563 if (T->isObjCObjectType()) {
564 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
565 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
566 // This handles the following case:
567 // @interface NewI @end
568 // typedef NewI DeprI __attribute__((deprecated("blah")))
569 // @interface SI : DeprI /* warn here */ @end
570 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
575 // This handles the following case:
577 // typedef int SuperClass;
578 // @interface MyClass : SuperClass {} @end
580 if (!SuperClassDecl) {
581 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
582 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
586 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
588 Diag(SuperLoc, diag::err_undef_superclass)
589 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
590 else if (RequireCompleteType(SuperLoc,
591 Context.getObjCInterfaceType(SuperClassDecl),
592 diag::err_forward_superclass,
593 SuperClassDecl->getDeclName(),
595 SourceRange(AtInterfaceLoc, ClassLoc))) {
596 SuperClassDecl = nullptr;
599 IDecl->setSuperClass(SuperClassDecl);
600 IDecl->setSuperClassLoc(SuperLoc);
601 IDecl->setEndOfDefinitionLoc(SuperLoc);
603 } else { // we have a root class.
604 IDecl->setEndOfDefinitionLoc(ClassLoc);
607 // Check then save referenced protocols.
609 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
610 NumProtoRefs, ProtoLocs);
611 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
613 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
616 CheckObjCDeclScope(IDecl);
617 return ActOnObjCContainerStartDefinition(IDecl);
620 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
621 /// typedef'ed use for a qualified super class and adds them to the list
622 /// of the protocols.
623 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
624 IdentifierInfo *SuperName,
625 SourceLocation SuperLoc) {
628 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
633 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
634 QualType T = TDecl->getUnderlyingType();
635 if (T->isObjCObjectType())
636 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
637 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
641 /// ActOnCompatibilityAlias - this action is called after complete parsing of
642 /// a \@compatibility_alias declaration. It sets up the alias relationships.
643 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
644 IdentifierInfo *AliasName,
645 SourceLocation AliasLocation,
646 IdentifierInfo *ClassName,
647 SourceLocation ClassLocation) {
648 // Look for previous declaration of alias name
649 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
650 LookupOrdinaryName, ForRedeclaration);
652 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
653 Diag(ADecl->getLocation(), diag::note_previous_declaration);
656 // Check for class declaration
657 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
658 LookupOrdinaryName, ForRedeclaration);
659 if (const TypedefNameDecl *TDecl =
660 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
661 QualType T = TDecl->getUnderlyingType();
662 if (T->isObjCObjectType()) {
663 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
664 ClassName = IDecl->getIdentifier();
665 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
666 LookupOrdinaryName, ForRedeclaration);
670 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
672 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
674 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
678 // Everything checked out, instantiate a new alias declaration AST.
679 ObjCCompatibleAliasDecl *AliasDecl =
680 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
682 if (!CheckObjCDeclScope(AliasDecl))
683 PushOnScopeChains(AliasDecl, TUScope);
688 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
689 IdentifierInfo *PName,
690 SourceLocation &Ploc, SourceLocation PrevLoc,
691 const ObjCList<ObjCProtocolDecl> &PList) {
694 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
695 E = PList.end(); I != E; ++I) {
696 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
698 if (PDecl->getIdentifier() == PName) {
699 Diag(Ploc, diag::err_protocol_has_circular_dependency);
700 Diag(PrevLoc, diag::note_previous_definition);
704 if (!PDecl->hasDefinition())
707 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
708 PDecl->getLocation(), PDecl->getReferencedProtocols()))
716 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
717 IdentifierInfo *ProtocolName,
718 SourceLocation ProtocolLoc,
719 Decl * const *ProtoRefs,
720 unsigned NumProtoRefs,
721 const SourceLocation *ProtoLocs,
722 SourceLocation EndProtoLoc,
723 AttributeList *AttrList) {
725 // FIXME: Deal with AttrList.
726 assert(ProtocolName && "Missing protocol identifier");
727 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
729 ObjCProtocolDecl *PDecl = nullptr;
730 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
731 // If we already have a definition, complain.
732 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
733 Diag(Def->getLocation(), diag::note_previous_definition);
735 // Create a new protocol that is completely distinct from previous
736 // declarations, and do not make this protocol available for name lookup.
737 // That way, we'll end up completely ignoring the duplicate.
738 // FIXME: Can we turn this into an error?
739 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
740 ProtocolLoc, AtProtoInterfaceLoc,
741 /*PrevDecl=*/nullptr);
742 PDecl->startDefinition();
745 // Check for circular dependencies among protocol declarations. This can
746 // only happen if this protocol was forward-declared.
747 ObjCList<ObjCProtocolDecl> PList;
748 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
749 err = CheckForwardProtocolDeclarationForCircularDependency(
750 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
753 // Create the new declaration.
754 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
755 ProtocolLoc, AtProtoInterfaceLoc,
756 /*PrevDecl=*/PrevDecl);
758 PushOnScopeChains(PDecl, TUScope);
759 PDecl->startDefinition();
763 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
765 // Merge attributes from previous declarations.
767 mergeDeclAttributes(PDecl, PrevDecl);
769 if (!err && NumProtoRefs ) {
770 /// Check then save referenced protocols.
771 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
772 NumProtoRefs, ProtoLocs);
773 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
777 CheckObjCDeclScope(PDecl);
778 return ActOnObjCContainerStartDefinition(PDecl);
781 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
782 ObjCProtocolDecl *&UndefinedProtocol) {
783 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
784 UndefinedProtocol = PDecl;
788 for (auto *PI : PDecl->protocols())
789 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
790 UndefinedProtocol = PI;
796 /// FindProtocolDeclaration - This routine looks up protocols and
797 /// issues an error if they are not declared. It returns list of
798 /// protocol declarations in its 'Protocols' argument.
800 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
801 const IdentifierLocPair *ProtocolId,
802 unsigned NumProtocols,
803 SmallVectorImpl<Decl *> &Protocols) {
804 for (unsigned i = 0; i != NumProtocols; ++i) {
805 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
806 ProtocolId[i].second);
808 TypoCorrection Corrected = CorrectTypo(
809 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
810 LookupObjCProtocolName, TUScope, nullptr,
811 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
813 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
814 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
815 << ProtocolId[i].first);
819 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
820 << ProtocolId[i].first;
823 // If this is a forward protocol declaration, get its definition.
824 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
825 PDecl = PDecl->getDefinition();
827 // For an objc container, delay protocol reference checking until after we
828 // can set the objc decl as the availability context, otherwise check now.
829 if (!ForObjCContainer) {
830 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
833 // If this is a forward declaration and we are supposed to warn in this
835 // FIXME: Recover nicely in the hidden case.
836 ObjCProtocolDecl *UndefinedProtocol;
838 if (WarnOnDeclarations &&
839 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
840 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
841 << ProtocolId[i].first;
842 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
843 << UndefinedProtocol;
845 Protocols.push_back(PDecl);
849 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
850 /// a class method in its extension.
852 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
853 ObjCInterfaceDecl *ID) {
855 return; // Possibly due to previous error
857 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
858 for (auto *MD : ID->methods())
859 MethodMap[MD->getSelector()] = MD;
861 if (MethodMap.empty())
863 for (const auto *Method : CAT->methods()) {
864 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
866 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
867 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
868 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
869 << Method->getDeclName();
870 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
875 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
877 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
878 const IdentifierLocPair *IdentList,
880 AttributeList *attrList) {
881 SmallVector<Decl *, 8> DeclsInGroup;
882 for (unsigned i = 0; i != NumElts; ++i) {
883 IdentifierInfo *Ident = IdentList[i].first;
884 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
886 ObjCProtocolDecl *PDecl
887 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
888 IdentList[i].second, AtProtocolLoc,
891 PushOnScopeChains(PDecl, TUScope);
892 CheckObjCDeclScope(PDecl);
895 ProcessDeclAttributeList(TUScope, PDecl, attrList);
898 mergeDeclAttributes(PDecl, PrevDecl);
900 DeclsInGroup.push_back(PDecl);
903 return BuildDeclaratorGroup(DeclsInGroup, false);
907 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
908 IdentifierInfo *ClassName, SourceLocation ClassLoc,
909 IdentifierInfo *CategoryName,
910 SourceLocation CategoryLoc,
911 Decl * const *ProtoRefs,
912 unsigned NumProtoRefs,
913 const SourceLocation *ProtoLocs,
914 SourceLocation EndProtoLoc) {
915 ObjCCategoryDecl *CDecl;
916 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
918 /// Check that class of this category is already completely declared.
921 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
922 diag::err_category_forward_interface,
923 CategoryName == nullptr)) {
924 // Create an invalid ObjCCategoryDecl to serve as context for
925 // the enclosing method declarations. We mark the decl invalid
926 // to make it clear that this isn't a valid AST.
927 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
928 ClassLoc, CategoryLoc, CategoryName,IDecl);
929 CDecl->setInvalidDecl();
930 CurContext->addDecl(CDecl);
933 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
934 return ActOnObjCContainerStartDefinition(CDecl);
937 if (!CategoryName && IDecl->getImplementation()) {
938 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
939 Diag(IDecl->getImplementation()->getLocation(),
940 diag::note_implementation_declared);
944 /// Check for duplicate interface declaration for this category
945 if (ObjCCategoryDecl *Previous
946 = IDecl->FindCategoryDeclaration(CategoryName)) {
947 // Class extensions can be declared multiple times, categories cannot.
948 Diag(CategoryLoc, diag::warn_dup_category_def)
949 << ClassName << CategoryName;
950 Diag(Previous->getLocation(), diag::note_previous_definition);
954 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
955 ClassLoc, CategoryLoc, CategoryName, IDecl);
956 // FIXME: PushOnScopeChains?
957 CurContext->addDecl(CDecl);
960 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
961 NumProtoRefs, ProtoLocs);
962 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
964 // Protocols in the class extension belong to the class.
965 if (CDecl->IsClassExtension())
966 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
967 NumProtoRefs, Context);
970 CheckObjCDeclScope(CDecl);
971 return ActOnObjCContainerStartDefinition(CDecl);
974 /// ActOnStartCategoryImplementation - Perform semantic checks on the
975 /// category implementation declaration and build an ObjCCategoryImplDecl
977 Decl *Sema::ActOnStartCategoryImplementation(
978 SourceLocation AtCatImplLoc,
979 IdentifierInfo *ClassName, SourceLocation ClassLoc,
980 IdentifierInfo *CatName, SourceLocation CatLoc) {
981 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
982 ObjCCategoryDecl *CatIDecl = nullptr;
983 if (IDecl && IDecl->hasDefinition()) {
984 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
986 // Category @implementation with no corresponding @interface.
987 // Create and install one.
988 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
991 CatIDecl->setImplicit();
995 ObjCCategoryImplDecl *CDecl =
996 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
997 ClassLoc, AtCatImplLoc, CatLoc);
998 /// Check that class of this category is already completely declared.
1000 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1001 CDecl->setInvalidDecl();
1002 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1003 diag::err_undef_interface)) {
1004 CDecl->setInvalidDecl();
1007 // FIXME: PushOnScopeChains?
1008 CurContext->addDecl(CDecl);
1010 // If the interface is deprecated/unavailable, warn/error about it.
1012 DiagnoseUseOfDecl(IDecl, ClassLoc);
1014 /// Check that CatName, category name, is not used in another implementation.
1016 if (CatIDecl->getImplementation()) {
1017 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1019 Diag(CatIDecl->getImplementation()->getLocation(),
1020 diag::note_previous_definition);
1021 CDecl->setInvalidDecl();
1023 CatIDecl->setImplementation(CDecl);
1024 // Warn on implementating category of deprecated class under
1025 // -Wdeprecated-implementations flag.
1026 DiagnoseObjCImplementedDeprecations(*this,
1027 dyn_cast<NamedDecl>(IDecl),
1028 CDecl->getLocation(), 2);
1032 CheckObjCDeclScope(CDecl);
1033 return ActOnObjCContainerStartDefinition(CDecl);
1036 Decl *Sema::ActOnStartClassImplementation(
1037 SourceLocation AtClassImplLoc,
1038 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1039 IdentifierInfo *SuperClassname,
1040 SourceLocation SuperClassLoc) {
1041 ObjCInterfaceDecl *IDecl = nullptr;
1042 // Check for another declaration kind with the same name.
1044 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1046 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1047 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1048 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1049 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1050 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1051 diag::warn_undef_interface);
1053 // We did not find anything with the name ClassName; try to correct for
1054 // typos in the class name.
1055 TypoCorrection Corrected = CorrectTypo(
1056 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1057 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
1058 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1059 // Suggest the (potentially) correct interface name. Don't provide a
1060 // code-modification hint or use the typo name for recovery, because
1061 // this is just a warning. The program may actually be correct.
1062 diagnoseTypo(Corrected,
1063 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1064 /*ErrorRecovery*/false);
1066 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1070 // Check that super class name is valid class name
1071 ObjCInterfaceDecl *SDecl = nullptr;
1072 if (SuperClassname) {
1073 // Check if a different kind of symbol declared in this scope.
1074 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1075 LookupOrdinaryName);
1076 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1077 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1079 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1081 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1082 if (SDecl && !SDecl->hasDefinition())
1085 Diag(SuperClassLoc, diag::err_undef_superclass)
1086 << SuperClassname << ClassName;
1087 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1088 // This implementation and its interface do not have the same
1090 Diag(SuperClassLoc, diag::err_conflicting_super_class)
1091 << SDecl->getDeclName();
1092 Diag(SDecl->getLocation(), diag::note_previous_definition);
1098 // Legacy case of @implementation with no corresponding @interface.
1099 // Build, chain & install the interface decl into the identifier.
1101 // FIXME: Do we support attributes on the @implementation? If so we should
1103 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1104 ClassName, /*PrevDecl=*/nullptr, ClassLoc,
1106 IDecl->startDefinition();
1108 IDecl->setSuperClass(SDecl);
1109 IDecl->setSuperClassLoc(SuperClassLoc);
1110 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1112 IDecl->setEndOfDefinitionLoc(ClassLoc);
1115 PushOnScopeChains(IDecl, TUScope);
1117 // Mark the interface as being completed, even if it was just as
1119 // declaration; the user cannot reopen it.
1120 if (!IDecl->hasDefinition())
1121 IDecl->startDefinition();
1124 ObjCImplementationDecl* IMPDecl =
1125 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1126 ClassLoc, AtClassImplLoc, SuperClassLoc);
1128 if (CheckObjCDeclScope(IMPDecl))
1129 return ActOnObjCContainerStartDefinition(IMPDecl);
1131 // Check that there is no duplicate implementation of this class.
1132 if (IDecl->getImplementation()) {
1133 // FIXME: Don't leak everything!
1134 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1135 Diag(IDecl->getImplementation()->getLocation(),
1136 diag::note_previous_definition);
1137 IMPDecl->setInvalidDecl();
1138 } else { // add it to the list.
1139 IDecl->setImplementation(IMPDecl);
1140 PushOnScopeChains(IMPDecl, TUScope);
1141 // Warn on implementating deprecated class under
1142 // -Wdeprecated-implementations flag.
1143 DiagnoseObjCImplementedDeprecations(*this,
1144 dyn_cast<NamedDecl>(IDecl),
1145 IMPDecl->getLocation(), 1);
1147 return ActOnObjCContainerStartDefinition(IMPDecl);
1150 Sema::DeclGroupPtrTy
1151 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1152 SmallVector<Decl *, 64> DeclsInGroup;
1153 DeclsInGroup.reserve(Decls.size() + 1);
1155 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1156 Decl *Dcl = Decls[i];
1159 if (Dcl->getDeclContext()->isFileContext())
1160 Dcl->setTopLevelDeclInObjCContainer();
1161 DeclsInGroup.push_back(Dcl);
1164 DeclsInGroup.push_back(ObjCImpDecl);
1166 return BuildDeclaratorGroup(DeclsInGroup, false);
1169 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1170 ObjCIvarDecl **ivars, unsigned numIvars,
1171 SourceLocation RBrace) {
1172 assert(ImpDecl && "missing implementation decl");
1173 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1176 /// Check case of non-existing \@interface decl.
1177 /// (legacy objective-c \@implementation decl without an \@interface decl).
1178 /// Add implementations's ivar to the synthesize class's ivar list.
1179 if (IDecl->isImplicitInterfaceDecl()) {
1180 IDecl->setEndOfDefinitionLoc(RBrace);
1181 // Add ivar's to class's DeclContext.
1182 for (unsigned i = 0, e = numIvars; i != e; ++i) {
1183 ivars[i]->setLexicalDeclContext(ImpDecl);
1184 IDecl->makeDeclVisibleInContext(ivars[i]);
1185 ImpDecl->addDecl(ivars[i]);
1190 // If implementation has empty ivar list, just return.
1194 assert(ivars && "missing @implementation ivars");
1195 if (LangOpts.ObjCRuntime.isNonFragile()) {
1196 if (ImpDecl->getSuperClass())
1197 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1198 for (unsigned i = 0; i < numIvars; i++) {
1199 ObjCIvarDecl* ImplIvar = ivars[i];
1200 if (const ObjCIvarDecl *ClsIvar =
1201 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1202 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1203 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1206 // Check class extensions (unnamed categories) for duplicate ivars.
1207 for (const auto *CDecl : IDecl->visible_extensions()) {
1208 if (const ObjCIvarDecl *ClsExtIvar =
1209 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1210 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1211 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1215 // Instance ivar to Implementation's DeclContext.
1216 ImplIvar->setLexicalDeclContext(ImpDecl);
1217 IDecl->makeDeclVisibleInContext(ImplIvar);
1218 ImpDecl->addDecl(ImplIvar);
1222 // Check interface's Ivar list against those in the implementation.
1223 // names and types must match.
1226 ObjCInterfaceDecl::ivar_iterator
1227 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1228 for (; numIvars > 0 && IVI != IVE; ++IVI) {
1229 ObjCIvarDecl* ImplIvar = ivars[j++];
1230 ObjCIvarDecl* ClsIvar = *IVI;
1231 assert (ImplIvar && "missing implementation ivar");
1232 assert (ClsIvar && "missing class ivar");
1234 // First, make sure the types match.
1235 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1236 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1237 << ImplIvar->getIdentifier()
1238 << ImplIvar->getType() << ClsIvar->getType();
1239 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1240 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1241 ImplIvar->getBitWidthValue(Context) !=
1242 ClsIvar->getBitWidthValue(Context)) {
1243 Diag(ImplIvar->getBitWidth()->getLocStart(),
1244 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1245 Diag(ClsIvar->getBitWidth()->getLocStart(),
1246 diag::note_previous_definition);
1248 // Make sure the names are identical.
1249 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1250 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1251 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1252 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1258 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
1259 else if (IVI != IVE)
1260 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
1263 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1264 ObjCMethodDecl *method,
1265 bool &IncompleteImpl,
1267 NamedDecl *NeededFor = nullptr) {
1268 // No point warning no definition of method which is 'unavailable'.
1269 switch (method->getAvailability()) {
1274 // Don't warn about unavailable or not-yet-introduced methods.
1275 case AR_NotYetIntroduced:
1276 case AR_Unavailable:
1280 // FIXME: For now ignore 'IncompleteImpl'.
1281 // Previously we grouped all unimplemented methods under a single
1282 // warning, but some users strongly voiced that they would prefer
1283 // separate warnings. We will give that approach a try, as that
1284 // matches what we do with protocols.
1286 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1292 // Issue a note to the original declaration.
1293 SourceLocation MethodLoc = method->getLocStart();
1294 if (MethodLoc.isValid())
1295 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
1298 /// Determines if type B can be substituted for type A. Returns true if we can
1299 /// guarantee that anything that the user will do to an object of type A can
1300 /// also be done to an object of type B. This is trivially true if the two
1301 /// types are the same, or if B is a subclass of A. It becomes more complex
1302 /// in cases where protocols are involved.
1304 /// Object types in Objective-C describe the minimum requirements for an
1305 /// object, rather than providing a complete description of a type. For
1306 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1307 /// The principle of substitutability means that we may use an instance of A
1308 /// anywhere that we may use an instance of B - it will implement all of the
1309 /// ivars of B and all of the methods of B.
1311 /// This substitutability is important when type checking methods, because
1312 /// the implementation may have stricter type definitions than the interface.
1313 /// The interface specifies minimum requirements, but the implementation may
1314 /// have more accurate ones. For example, a method may privately accept
1315 /// instances of B, but only publish that it accepts instances of A. Any
1316 /// object passed to it will be type checked against B, and so will implicitly
1317 /// by a valid A*. Similarly, a method may return a subclass of the class that
1318 /// it is declared as returning.
1320 /// This is most important when considering subclassing. A method in a
1321 /// subclass must accept any object as an argument that its superclass's
1322 /// implementation accepts. It may, however, accept a more general type
1323 /// without breaking substitutability (i.e. you can still use the subclass
1324 /// anywhere that you can use the superclass, but not vice versa). The
1325 /// converse requirement applies to return types: the return type for a
1326 /// subclass method must be a valid object of the kind that the superclass
1327 /// advertises, but it may be specified more accurately. This avoids the need
1328 /// for explicit down-casting by callers.
1330 /// Note: This is a stricter requirement than for assignment.
1331 static bool isObjCTypeSubstitutable(ASTContext &Context,
1332 const ObjCObjectPointerType *A,
1333 const ObjCObjectPointerType *B,
1335 // Reject a protocol-unqualified id.
1336 if (rejectId && B->isObjCIdType()) return false;
1338 // If B is a qualified id, then A must also be a qualified id and it must
1339 // implement all of the protocols in B. It may not be a qualified class.
1340 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1341 // stricter definition so it is not substitutable for id<A>.
1342 if (B->isObjCQualifiedIdType()) {
1343 return A->isObjCQualifiedIdType() &&
1344 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1350 // id is a special type that bypasses type checking completely. We want a
1351 // warning when it is used in one place but not another.
1352 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1355 // If B is a qualified id, then A must also be a qualified id (which it isn't
1356 // if we've got this far)
1357 if (B->isObjCQualifiedIdType()) return false;
1360 // Now we know that A and B are (potentially-qualified) class types. The
1361 // normal rules for assignment apply.
1362 return Context.canAssignObjCInterfaces(A, B);
1365 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1366 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1369 static bool CheckMethodOverrideReturn(Sema &S,
1370 ObjCMethodDecl *MethodImpl,
1371 ObjCMethodDecl *MethodDecl,
1372 bool IsProtocolMethodDecl,
1373 bool IsOverridingMode,
1375 if (IsProtocolMethodDecl &&
1376 (MethodDecl->getObjCDeclQualifier() !=
1377 MethodImpl->getObjCDeclQualifier())) {
1379 S.Diag(MethodImpl->getLocation(),
1381 ? diag::warn_conflicting_overriding_ret_type_modifiers
1382 : diag::warn_conflicting_ret_type_modifiers))
1383 << MethodImpl->getDeclName()
1384 << MethodImpl->getReturnTypeSourceRange();
1385 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1386 << MethodDecl->getReturnTypeSourceRange();
1392 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1393 MethodDecl->getReturnType()))
1399 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1400 : diag::warn_conflicting_ret_types;
1402 // Mismatches between ObjC pointers go into a different warning
1403 // category, and sometimes they're even completely whitelisted.
1404 if (const ObjCObjectPointerType *ImplPtrTy =
1405 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1406 if (const ObjCObjectPointerType *IfacePtrTy =
1407 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1408 // Allow non-matching return types as long as they don't violate
1409 // the principle of substitutability. Specifically, we permit
1410 // return types that are subclasses of the declared return type,
1411 // or that are more-qualified versions of the declared type.
1412 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1416 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1417 : diag::warn_non_covariant_ret_types;
1421 S.Diag(MethodImpl->getLocation(), DiagID)
1422 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1423 << MethodImpl->getReturnType()
1424 << MethodImpl->getReturnTypeSourceRange();
1425 S.Diag(MethodDecl->getLocation(), IsOverridingMode
1426 ? diag::note_previous_declaration
1427 : diag::note_previous_definition)
1428 << MethodDecl->getReturnTypeSourceRange();
1432 static bool CheckMethodOverrideParam(Sema &S,
1433 ObjCMethodDecl *MethodImpl,
1434 ObjCMethodDecl *MethodDecl,
1435 ParmVarDecl *ImplVar,
1436 ParmVarDecl *IfaceVar,
1437 bool IsProtocolMethodDecl,
1438 bool IsOverridingMode,
1440 if (IsProtocolMethodDecl &&
1441 (ImplVar->getObjCDeclQualifier() !=
1442 IfaceVar->getObjCDeclQualifier())) {
1444 if (IsOverridingMode)
1445 S.Diag(ImplVar->getLocation(),
1446 diag::warn_conflicting_overriding_param_modifiers)
1447 << getTypeRange(ImplVar->getTypeSourceInfo())
1448 << MethodImpl->getDeclName();
1449 else S.Diag(ImplVar->getLocation(),
1450 diag::warn_conflicting_param_modifiers)
1451 << getTypeRange(ImplVar->getTypeSourceInfo())
1452 << MethodImpl->getDeclName();
1453 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1454 << getTypeRange(IfaceVar->getTypeSourceInfo());
1460 QualType ImplTy = ImplVar->getType();
1461 QualType IfaceTy = IfaceVar->getType();
1463 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1469 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1470 : diag::warn_conflicting_param_types;
1472 // Mismatches between ObjC pointers go into a different warning
1473 // category, and sometimes they're even completely whitelisted.
1474 if (const ObjCObjectPointerType *ImplPtrTy =
1475 ImplTy->getAs<ObjCObjectPointerType>()) {
1476 if (const ObjCObjectPointerType *IfacePtrTy =
1477 IfaceTy->getAs<ObjCObjectPointerType>()) {
1478 // Allow non-matching argument types as long as they don't
1479 // violate the principle of substitutability. Specifically, the
1480 // implementation must accept any objects that the superclass
1481 // accepts, however it may also accept others.
1482 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1486 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1487 : diag::warn_non_contravariant_param_types;
1491 S.Diag(ImplVar->getLocation(), DiagID)
1492 << getTypeRange(ImplVar->getTypeSourceInfo())
1493 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1494 S.Diag(IfaceVar->getLocation(),
1495 (IsOverridingMode ? diag::note_previous_declaration
1496 : diag::note_previous_definition))
1497 << getTypeRange(IfaceVar->getTypeSourceInfo());
1501 /// In ARC, check whether the conventional meanings of the two methods
1502 /// match. If they don't, it's a hard error.
1503 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1504 ObjCMethodDecl *decl) {
1505 ObjCMethodFamily implFamily = impl->getMethodFamily();
1506 ObjCMethodFamily declFamily = decl->getMethodFamily();
1507 if (implFamily == declFamily) return false;
1509 // Since conventions are sorted by selector, the only possibility is
1510 // that the types differ enough to cause one selector or the other
1511 // to fall out of the family.
1512 assert(implFamily == OMF_None || declFamily == OMF_None);
1514 // No further diagnostics required on invalid declarations.
1515 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1517 const ObjCMethodDecl *unmatched = impl;
1518 ObjCMethodFamily family = declFamily;
1519 unsigned errorID = diag::err_arc_lost_method_convention;
1520 unsigned noteID = diag::note_arc_lost_method_convention;
1521 if (declFamily == OMF_None) {
1523 family = implFamily;
1524 errorID = diag::err_arc_gained_method_convention;
1525 noteID = diag::note_arc_gained_method_convention;
1528 // Indexes into a %select clause in the diagnostic.
1529 enum FamilySelector {
1530 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1532 FamilySelector familySelector = FamilySelector();
1535 case OMF_None: llvm_unreachable("logic error, no method convention");
1538 case OMF_autorelease:
1541 case OMF_retainCount:
1543 case OMF_initialize:
1544 case OMF_performSelector:
1545 // Mismatches for these methods don't change ownership
1546 // conventions, so we don't care.
1549 case OMF_init: familySelector = F_init; break;
1550 case OMF_alloc: familySelector = F_alloc; break;
1551 case OMF_copy: familySelector = F_copy; break;
1552 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1553 case OMF_new: familySelector = F_new; break;
1556 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1557 ReasonSelector reasonSelector;
1559 // The only reason these methods don't fall within their families is
1560 // due to unusual result types.
1561 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
1562 reasonSelector = R_UnrelatedReturn;
1564 reasonSelector = R_NonObjectReturn;
1567 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1568 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
1573 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1574 ObjCMethodDecl *MethodDecl,
1575 bool IsProtocolMethodDecl) {
1576 if (getLangOpts().ObjCAutoRefCount &&
1577 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1580 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1581 IsProtocolMethodDecl, false,
1584 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1585 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1586 EF = MethodDecl->param_end();
1587 IM != EM && IF != EF; ++IM, ++IF) {
1588 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1589 IsProtocolMethodDecl, false, true);
1592 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1593 Diag(ImpMethodDecl->getLocation(),
1594 diag::warn_conflicting_variadic);
1595 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1599 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1600 ObjCMethodDecl *Overridden,
1601 bool IsProtocolMethodDecl) {
1603 CheckMethodOverrideReturn(*this, Method, Overridden,
1604 IsProtocolMethodDecl, true,
1607 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1608 IF = Overridden->param_begin(), EM = Method->param_end(),
1609 EF = Overridden->param_end();
1610 IM != EM && IF != EF; ++IM, ++IF) {
1611 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1612 IsProtocolMethodDecl, true, true);
1615 if (Method->isVariadic() != Overridden->isVariadic()) {
1616 Diag(Method->getLocation(),
1617 diag::warn_conflicting_overriding_variadic);
1618 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1622 /// WarnExactTypedMethods - This routine issues a warning if method
1623 /// implementation declaration matches exactly that of its declaration.
1624 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1625 ObjCMethodDecl *MethodDecl,
1626 bool IsProtocolMethodDecl) {
1627 // don't issue warning when protocol method is optional because primary
1628 // class is not required to implement it and it is safe for protocol
1630 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1632 // don't issue warning when primary class's method is
1633 // depecated/unavailable.
1634 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1635 MethodDecl->hasAttr<DeprecatedAttr>())
1638 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1639 IsProtocolMethodDecl, false, false);
1641 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1642 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1643 EF = MethodDecl->param_end();
1644 IM != EM && IF != EF; ++IM, ++IF) {
1645 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1647 IsProtocolMethodDecl, false, false);
1652 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1654 match = !(MethodDecl->isClassMethod() &&
1655 MethodDecl->getSelector() == GetNullarySelector("load", Context));
1658 Diag(ImpMethodDecl->getLocation(),
1659 diag::warn_category_method_impl_match);
1660 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1661 << MethodDecl->getDeclName();
1665 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1666 /// improve the efficiency of selector lookups and type checking by associating
1667 /// with each protocol / interface / category the flattened instance tables. If
1668 /// we used an immutable set to keep the table then it wouldn't add significant
1669 /// memory cost and it would be handy for lookups.
1671 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
1672 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
1674 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1675 ProtocolNameSet &PNS) {
1676 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1677 PNS.insert(PDecl->getIdentifier());
1678 for (const auto *PI : PDecl->protocols())
1679 findProtocolsWithExplicitImpls(PI, PNS);
1682 /// Recursively populates a set with all conformed protocols in a class
1683 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1685 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1686 ProtocolNameSet &PNS) {
1690 for (const auto *I : Super->all_referenced_protocols())
1691 findProtocolsWithExplicitImpls(I, PNS);
1693 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
1696 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1697 /// Declared in protocol, and those referenced by it.
1698 static void CheckProtocolMethodDefs(Sema &S,
1699 SourceLocation ImpLoc,
1700 ObjCProtocolDecl *PDecl,
1701 bool& IncompleteImpl,
1702 const Sema::SelectorSet &InsMap,
1703 const Sema::SelectorSet &ClsMap,
1704 ObjCContainerDecl *CDecl,
1705 LazyProtocolNameSet &ProtocolsExplictImpl) {
1706 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1707 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1708 : dyn_cast<ObjCInterfaceDecl>(CDecl);
1709 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1711 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1712 ObjCInterfaceDecl *NSIDecl = nullptr;
1714 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1715 // then we should check if any class in the super class hierarchy also
1716 // conforms to this protocol, either directly or via protocol inheritance.
1717 // If so, we can skip checking this protocol completely because we
1718 // know that a parent class already satisfies this protocol.
1720 // Note: we could generalize this logic for all protocols, and merely
1721 // add the limit on looking at the super class chain for just
1722 // specially marked protocols. This may be a good optimization. This
1723 // change is restricted to 'objc_protocol_requires_explicit_implementation'
1724 // protocols for now for controlled evaluation.
1725 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
1726 if (!ProtocolsExplictImpl) {
1727 ProtocolsExplictImpl.reset(new ProtocolNameSet);
1728 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1730 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1731 ProtocolsExplictImpl->end())
1734 // If no super class conforms to the protocol, we should not search
1735 // for methods in the super class to implicitly satisfy the protocol.
1739 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
1740 // check to see if class implements forwardInvocation method and objects
1741 // of this class are derived from 'NSProxy' so that to forward requests
1742 // from one object to another.
1743 // Under such conditions, which means that every method possible is
1744 // implemented in the class, we should not issue "Method definition not
1746 // FIXME: Use a general GetUnarySelector method for this.
1747 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1748 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
1749 if (InsMap.count(fISelector))
1750 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1751 // need be implemented in the implementation.
1752 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
1755 // If this is a forward protocol declaration, get its definition.
1756 if (!PDecl->isThisDeclarationADefinition() &&
1757 PDecl->getDefinition())
1758 PDecl = PDecl->getDefinition();
1760 // If a method lookup fails locally we still need to look and see if
1761 // the method was implemented by a base class or an inherited
1762 // protocol. This lookup is slow, but occurs rarely in correct code
1763 // and otherwise would terminate in a warning.
1765 // check unimplemented instance methods.
1767 for (auto *method : PDecl->instance_methods()) {
1768 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1769 !method->isPropertyAccessor() &&
1770 !InsMap.count(method->getSelector()) &&
1771 (!Super || !Super->lookupMethod(method->getSelector(),
1772 true /* instance */,
1773 false /* shallowCategory */,
1774 true /* followsSuper */,
1775 nullptr /* category */))) {
1776 // If a method is not implemented in the category implementation but
1777 // has been declared in its primary class, superclass,
1778 // or in one of their protocols, no need to issue the warning.
1779 // This is because method will be implemented in the primary class
1780 // or one of its super class implementation.
1782 // Ugly, but necessary. Method declared in protcol might have
1783 // have been synthesized due to a property declared in the class which
1784 // uses the protocol.
1785 if (ObjCMethodDecl *MethodInClass =
1786 IDecl->lookupMethod(method->getSelector(),
1787 true /* instance */,
1788 true /* shallowCategoryLookup */,
1789 false /* followSuper */))
1790 if (C || MethodInClass->isPropertyAccessor())
1792 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1793 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1794 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
1799 // check unimplemented class methods
1800 for (auto *method : PDecl->class_methods()) {
1801 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1802 !ClsMap.count(method->getSelector()) &&
1803 (!Super || !Super->lookupMethod(method->getSelector(),
1804 false /* class method */,
1805 false /* shallowCategoryLookup */,
1806 true /* followSuper */,
1807 nullptr /* category */))) {
1808 // See above comment for instance method lookups.
1809 if (C && IDecl->lookupMethod(method->getSelector(),
1811 true /* shallowCategoryLookup */,
1812 false /* followSuper */))
1815 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1816 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1817 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
1821 // Check on this protocols's referenced protocols, recursively.
1822 for (auto *PI : PDecl->protocols())
1823 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
1824 CDecl, ProtocolsExplictImpl);
1827 /// MatchAllMethodDeclarations - Check methods declared in interface
1828 /// or protocol against those declared in their implementations.
1830 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1831 const SelectorSet &ClsMap,
1832 SelectorSet &InsMapSeen,
1833 SelectorSet &ClsMapSeen,
1834 ObjCImplDecl* IMPDecl,
1835 ObjCContainerDecl* CDecl,
1836 bool &IncompleteImpl,
1837 bool ImmediateClass,
1838 bool WarnCategoryMethodImpl) {
1839 // Check and see if instance methods in class interface have been
1840 // implemented in the implementation class. If so, their types match.
1841 for (auto *I : CDecl->instance_methods()) {
1842 if (!InsMapSeen.insert(I->getSelector()).second)
1844 if (!I->isPropertyAccessor() &&
1845 !InsMap.count(I->getSelector())) {
1847 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1848 diag::warn_undef_method_impl);
1851 ObjCMethodDecl *ImpMethodDecl =
1852 IMPDecl->getInstanceMethod(I->getSelector());
1853 assert(CDecl->getInstanceMethod(I->getSelector()) &&
1854 "Expected to find the method through lookup as well");
1855 // ImpMethodDecl may be null as in a @dynamic property.
1856 if (ImpMethodDecl) {
1857 if (!WarnCategoryMethodImpl)
1858 WarnConflictingTypedMethods(ImpMethodDecl, I,
1859 isa<ObjCProtocolDecl>(CDecl));
1860 else if (!I->isPropertyAccessor())
1861 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
1866 // Check and see if class methods in class interface have been
1867 // implemented in the implementation class. If so, their types match.
1868 for (auto *I : CDecl->class_methods()) {
1869 if (!ClsMapSeen.insert(I->getSelector()).second)
1871 if (!ClsMap.count(I->getSelector())) {
1873 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1874 diag::warn_undef_method_impl);
1876 ObjCMethodDecl *ImpMethodDecl =
1877 IMPDecl->getClassMethod(I->getSelector());
1878 assert(CDecl->getClassMethod(I->getSelector()) &&
1879 "Expected to find the method through lookup as well");
1880 if (!WarnCategoryMethodImpl)
1881 WarnConflictingTypedMethods(ImpMethodDecl, I,
1882 isa<ObjCProtocolDecl>(CDecl));
1884 WarnExactTypedMethods(ImpMethodDecl, I,
1885 isa<ObjCProtocolDecl>(CDecl));
1889 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1890 // Also, check for methods declared in protocols inherited by
1892 for (auto *PI : PD->protocols())
1893 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1894 IMPDecl, PI, IncompleteImpl, false,
1895 WarnCategoryMethodImpl);
1898 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1899 // when checking that methods in implementation match their declaration,
1900 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1901 // extension; as well as those in categories.
1902 if (!WarnCategoryMethodImpl) {
1903 for (auto *Cat : I->visible_categories())
1904 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1905 IMPDecl, Cat, IncompleteImpl, false,
1906 WarnCategoryMethodImpl);
1908 // Also methods in class extensions need be looked at next.
1909 for (auto *Ext : I->visible_extensions())
1910 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1911 IMPDecl, Ext, IncompleteImpl, false,
1912 WarnCategoryMethodImpl);
1915 // Check for any implementation of a methods declared in protocol.
1916 for (auto *PI : I->all_referenced_protocols())
1917 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1918 IMPDecl, PI, IncompleteImpl, false,
1919 WarnCategoryMethodImpl);
1921 // FIXME. For now, we are not checking for extact match of methods
1922 // in category implementation and its primary class's super class.
1923 if (!WarnCategoryMethodImpl && I->getSuperClass())
1924 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1926 I->getSuperClass(), IncompleteImpl, false);
1930 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1931 /// category matches with those implemented in its primary class and
1932 /// warns each time an exact match is found.
1933 void Sema::CheckCategoryVsClassMethodMatches(
1934 ObjCCategoryImplDecl *CatIMPDecl) {
1935 // Get category's primary class.
1936 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1939 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1942 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1943 SelectorSet InsMap, ClsMap;
1945 for (const auto *I : CatIMPDecl->instance_methods()) {
1946 Selector Sel = I->getSelector();
1947 // When checking for methods implemented in the category, skip over
1948 // those declared in category class's super class. This is because
1949 // the super class must implement the method.
1950 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1955 for (const auto *I : CatIMPDecl->class_methods()) {
1956 Selector Sel = I->getSelector();
1957 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1961 if (InsMap.empty() && ClsMap.empty())
1964 SelectorSet InsMapSeen, ClsMapSeen;
1965 bool IncompleteImpl = false;
1966 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1968 IncompleteImpl, false,
1969 true /*WarnCategoryMethodImpl*/);
1972 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1973 ObjCContainerDecl* CDecl,
1974 bool IncompleteImpl) {
1976 // Check and see if instance methods in class interface have been
1977 // implemented in the implementation class.
1978 for (const auto *I : IMPDecl->instance_methods())
1979 InsMap.insert(I->getSelector());
1981 // Check and see if properties declared in the interface have either 1)
1982 // an implementation or 2) there is a @synthesize/@dynamic implementation
1983 // of the property in the @implementation.
1984 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1985 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1986 LangOpts.ObjCRuntime.isNonFragile() &&
1987 !IDecl->isObjCRequiresPropertyDefs();
1988 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1992 for (const auto *I : IMPDecl->class_methods())
1993 ClsMap.insert(I->getSelector());
1995 // Check for type conflict of methods declared in a class/protocol and
1996 // its implementation; if any.
1997 SelectorSet InsMapSeen, ClsMapSeen;
1998 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2000 IncompleteImpl, true);
2002 // check all methods implemented in category against those declared
2003 // in its primary class.
2004 if (ObjCCategoryImplDecl *CatDecl =
2005 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2006 CheckCategoryVsClassMethodMatches(CatDecl);
2008 // Check the protocol list for unimplemented methods in the @implementation
2010 // Check and see if class methods in class interface have been
2011 // implemented in the implementation class.
2013 LazyProtocolNameSet ExplicitImplProtocols;
2015 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2016 for (auto *PI : I->all_referenced_protocols())
2017 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2018 InsMap, ClsMap, I, ExplicitImplProtocols);
2019 // Check class extensions (unnamed categories)
2020 for (auto *Ext : I->visible_extensions())
2021 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
2022 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2023 // For extended class, unimplemented methods in its protocols will
2024 // be reported in the primary class.
2025 if (!C->IsClassExtension()) {
2026 for (auto *P : C->protocols())
2027 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2028 IncompleteImpl, InsMap, ClsMap, CDecl,
2029 ExplicitImplProtocols);
2030 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2031 /*SynthesizeProperties=*/false);
2034 llvm_unreachable("invalid ObjCContainerDecl type.");
2037 Sema::DeclGroupPtrTy
2038 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2039 IdentifierInfo **IdentList,
2040 SourceLocation *IdentLocs,
2042 SmallVector<Decl *, 8> DeclsInGroup;
2043 for (unsigned i = 0; i != NumElts; ++i) {
2044 // Check for another declaration kind with the same name.
2046 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2047 LookupOrdinaryName, ForRedeclaration);
2048 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2049 // GCC apparently allows the following idiom:
2051 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2052 // @class XCElementToggler;
2054 // Here we have chosen to ignore the forward class declaration
2055 // with a warning. Since this is the implied behavior.
2056 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2057 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2058 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2059 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2061 // a forward class declaration matching a typedef name of a class refers
2062 // to the underlying class. Just ignore the forward class with a warning
2063 // as this will force the intended behavior which is to lookup the
2065 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2066 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2068 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2074 // Create a declaration to describe this forward declaration.
2075 ObjCInterfaceDecl *PrevIDecl
2076 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2078 IdentifierInfo *ClassName = IdentList[i];
2079 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2080 // A previous decl with a different name is because of
2081 // @compatibility_alias, for example:
2084 // @compatibility_alias OldImage NewImage;
2086 // A lookup for 'OldImage' will return the 'NewImage' decl.
2088 // In such a case use the real declaration name, instead of the alias one,
2089 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2090 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2091 // has been aliased.
2092 ClassName = PrevIDecl->getIdentifier();
2095 ObjCInterfaceDecl *IDecl
2096 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
2097 ClassName, PrevIDecl, IdentLocs[i]);
2098 IDecl->setAtEndRange(IdentLocs[i]);
2100 PushOnScopeChains(IDecl, TUScope);
2101 CheckObjCDeclScope(IDecl);
2102 DeclsInGroup.push_back(IDecl);
2105 return BuildDeclaratorGroup(DeclsInGroup, false);
2108 static bool tryMatchRecordTypes(ASTContext &Context,
2109 Sema::MethodMatchStrategy strategy,
2110 const Type *left, const Type *right);
2112 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2113 QualType leftQT, QualType rightQT) {
2115 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2117 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2119 if (left == right) return true;
2121 // If we're doing a strict match, the types have to match exactly.
2122 if (strategy == Sema::MMS_strict) return false;
2124 if (left->isIncompleteType() || right->isIncompleteType()) return false;
2126 // Otherwise, use this absurdly complicated algorithm to try to
2127 // validate the basic, low-level compatibility of the two types.
2129 // As a minimum, require the sizes and alignments to match.
2130 TypeInfo LeftTI = Context.getTypeInfo(left);
2131 TypeInfo RightTI = Context.getTypeInfo(right);
2132 if (LeftTI.Width != RightTI.Width)
2135 if (LeftTI.Align != RightTI.Align)
2138 // Consider all the kinds of non-dependent canonical types:
2139 // - functions and arrays aren't possible as return and parameter types
2141 // - vector types of equal size can be arbitrarily mixed
2142 if (isa<VectorType>(left)) return isa<VectorType>(right);
2143 if (isa<VectorType>(right)) return false;
2145 // - references should only match references of identical type
2146 // - structs, unions, and Objective-C objects must match more-or-less
2148 // - everything else should be a scalar
2149 if (!left->isScalarType() || !right->isScalarType())
2150 return tryMatchRecordTypes(Context, strategy, left, right);
2152 // Make scalars agree in kind, except count bools as chars, and group
2153 // all non-member pointers together.
2154 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2155 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2156 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2157 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
2158 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2159 leftSK = Type::STK_ObjCObjectPointer;
2160 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2161 rightSK = Type::STK_ObjCObjectPointer;
2163 // Note that data member pointers and function member pointers don't
2164 // intermix because of the size differences.
2166 return (leftSK == rightSK);
2169 static bool tryMatchRecordTypes(ASTContext &Context,
2170 Sema::MethodMatchStrategy strategy,
2171 const Type *lt, const Type *rt) {
2172 assert(lt && rt && lt != rt);
2174 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2175 RecordDecl *left = cast<RecordType>(lt)->getDecl();
2176 RecordDecl *right = cast<RecordType>(rt)->getDecl();
2178 // Require union-hood to match.
2179 if (left->isUnion() != right->isUnion()) return false;
2181 // Require an exact match if either is non-POD.
2182 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2183 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2186 // Require size and alignment to match.
2187 TypeInfo LeftTI = Context.getTypeInfo(lt);
2188 TypeInfo RightTI = Context.getTypeInfo(rt);
2189 if (LeftTI.Width != RightTI.Width)
2192 if (LeftTI.Align != RightTI.Align)
2195 // Require fields to match.
2196 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2197 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2198 for (; li != le && ri != re; ++li, ++ri) {
2199 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2202 return (li == le && ri == re);
2205 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2206 /// returns true, or false, accordingly.
2207 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
2208 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2209 const ObjCMethodDecl *right,
2210 MethodMatchStrategy strategy) {
2211 if (!matchTypes(Context, strategy, left->getReturnType(),
2212 right->getReturnType()))
2215 // If either is hidden, it is not considered to match.
2216 if (left->isHidden() || right->isHidden())
2219 if (getLangOpts().ObjCAutoRefCount &&
2220 (left->hasAttr<NSReturnsRetainedAttr>()
2221 != right->hasAttr<NSReturnsRetainedAttr>() ||
2222 left->hasAttr<NSConsumesSelfAttr>()
2223 != right->hasAttr<NSConsumesSelfAttr>()))
2226 ObjCMethodDecl::param_const_iterator
2227 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2228 re = right->param_end();
2230 for (; li != le && ri != re; ++li, ++ri) {
2231 assert(ri != right->param_end() && "Param mismatch");
2232 const ParmVarDecl *lparm = *li, *rparm = *ri;
2234 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2237 if (getLangOpts().ObjCAutoRefCount &&
2238 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2244 void Sema::addMethodToGlobalList(ObjCMethodList *List,
2245 ObjCMethodDecl *Method) {
2246 // Record at the head of the list whether there were 0, 1, or >= 2 methods
2247 // inside categories.
2248 if (ObjCCategoryDecl *CD =
2249 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2250 if (!CD->IsClassExtension() && List->getBits() < 2)
2251 List->setBits(List->getBits() + 1);
2253 // If the list is empty, make it a singleton list.
2254 if (List->getMethod() == nullptr) {
2255 List->setMethod(Method);
2256 List->setNext(nullptr);
2260 // We've seen a method with this name, see if we have already seen this type
2262 ObjCMethodList *Previous = List;
2263 for (; List; Previous = List, List = List->getNext()) {
2264 // If we are building a module, keep all of the methods.
2265 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2268 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) {
2269 // Even if two method types do not match, we would like to say
2270 // there is more than one declaration so unavailability/deprecated
2271 // warning is not too noisy.
2272 if (!Method->isDefined())
2273 List->setHasMoreThanOneDecl(true);
2277 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
2279 // Propagate the 'defined' bit.
2280 if (Method->isDefined())
2281 PrevObjCMethod->setDefined(true);
2283 // Objective-C doesn't allow an @interface for a class after its
2284 // @implementation. So if Method is not defined and there already is
2285 // an entry for this type signature, Method has to be for a different
2286 // class than PrevObjCMethod.
2287 List->setHasMoreThanOneDecl(true);
2290 // If a method is deprecated, push it in the global pool.
2291 // This is used for better diagnostics.
2292 if (Method->isDeprecated()) {
2293 if (!PrevObjCMethod->isDeprecated())
2294 List->setMethod(Method);
2296 // If the new method is unavailable, push it into global pool
2297 // unless previous one is deprecated.
2298 if (Method->isUnavailable()) {
2299 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2300 List->setMethod(Method);
2306 // We have a new signature for an existing method - add it.
2307 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2308 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2309 Previous->setNext(new (Mem) ObjCMethodList(Method));
2312 /// \brief Read the contents of the method pool for a given selector from
2313 /// external storage.
2314 void Sema::ReadMethodPool(Selector Sel) {
2315 assert(ExternalSource && "We need an external AST source");
2316 ExternalSource->ReadMethodPool(Sel);
2319 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2321 // Ignore methods of invalid containers.
2322 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2326 ReadMethodPool(Method->getSelector());
2328 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2329 if (Pos == MethodPool.end())
2330 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2331 GlobalMethods())).first;
2333 Method->setDefined(impl);
2335 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2336 addMethodToGlobalList(&Entry, Method);
2339 /// Determines if this is an "acceptable" loose mismatch in the global
2340 /// method pool. This exists mostly as a hack to get around certain
2341 /// global mismatches which we can't afford to make warnings / errors.
2342 /// Really, what we want is a way to take a method out of the global
2344 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2345 ObjCMethodDecl *other) {
2346 if (!chosen->isInstanceMethod())
2349 Selector sel = chosen->getSelector();
2350 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2353 // Don't complain about mismatches for -length if the method we
2354 // chose has an integral result type.
2355 return (chosen->getReturnType()->isIntegerType());
2358 bool Sema::CollectMultipleMethodsInGlobalPool(
2359 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
2361 ReadMethodPool(Sel);
2363 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2364 if (Pos == MethodPool.end())
2366 // Gather the non-hidden methods.
2367 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2368 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
2369 if (M->getMethod() && !M->getMethod()->isHidden())
2370 Methods.push_back(M->getMethod());
2371 return Methods.size() > 1;
2374 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
2376 bool receiverIdOrClass) {
2377 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2378 // Test for no method in the pool which should not trigger any warning by
2380 if (Pos == MethodPool.end())
2382 ObjCMethodList &MethList =
2383 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
2385 // Diagnose finding more than one method in global pool
2386 SmallVector<ObjCMethodDecl *, 4> Methods;
2387 Methods.push_back(BestMethod);
2388 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext())
2389 if (ObjCMethodDecl *M = ML->getMethod())
2390 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>())
2391 Methods.push_back(M);
2392 if (Methods.size() > 1)
2393 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass);
2395 return MethList.hasMoreThanOneDecl();
2398 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2399 bool receiverIdOrClass,
2402 ReadMethodPool(Sel);
2404 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2405 if (Pos == MethodPool.end())
2408 // Gather the non-hidden methods.
2409 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2410 SmallVector<ObjCMethodDecl *, 4> Methods;
2411 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
2412 if (M->getMethod() && !M->getMethod()->isHidden())
2413 return M->getMethod();
2418 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
2419 Selector Sel, SourceRange R,
2420 bool receiverIdOrClass) {
2421 // We found multiple methods, so we may have to complain.
2422 bool issueDiagnostic = false, issueError = false;
2424 // We support a warning which complains about *any* difference in
2425 // method signature.
2426 bool strictSelectorMatch =
2427 receiverIdOrClass &&
2428 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
2429 if (strictSelectorMatch) {
2430 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2431 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2432 issueDiagnostic = true;
2438 // If we didn't see any strict differences, we won't see any loose
2439 // differences. In ARC, however, we also need to check for loose
2440 // mismatches, because most of them are errors.
2441 if (!strictSelectorMatch ||
2442 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2443 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2444 // This checks if the methods differ in type mismatch.
2445 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2446 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2447 issueDiagnostic = true;
2448 if (getLangOpts().ObjCAutoRefCount)
2454 if (issueDiagnostic) {
2456 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2457 else if (strictSelectorMatch)
2458 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2460 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2462 Diag(Methods[0]->getLocStart(),
2463 issueError ? diag::note_possibility : diag::note_using)
2464 << Methods[0]->getSourceRange();
2465 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2466 Diag(Methods[I]->getLocStart(), diag::note_also_found)
2467 << Methods[I]->getSourceRange();
2472 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2473 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2474 if (Pos == MethodPool.end())
2477 GlobalMethods &Methods = Pos->second;
2478 for (const ObjCMethodList *Method = &Methods.first; Method;
2479 Method = Method->getNext())
2480 if (Method->getMethod() &&
2481 (Method->getMethod()->isDefined() ||
2482 Method->getMethod()->isPropertyAccessor()))
2483 return Method->getMethod();
2485 for (const ObjCMethodList *Method = &Methods.second; Method;
2486 Method = Method->getNext())
2487 if (Method->getMethod() &&
2488 (Method->getMethod()->isDefined() ||
2489 Method->getMethod()->isPropertyAccessor()))
2490 return Method->getMethod();
2495 HelperSelectorsForTypoCorrection(
2496 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2497 StringRef Typo, const ObjCMethodDecl * Method) {
2498 const unsigned MaxEditDistance = 1;
2499 unsigned BestEditDistance = MaxEditDistance + 1;
2500 std::string MethodName = Method->getSelector().getAsString();
2502 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2503 if (MinPossibleEditDistance > 0 &&
2504 Typo.size() / MinPossibleEditDistance < 1)
2506 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2507 if (EditDistance > MaxEditDistance)
2509 if (EditDistance == BestEditDistance)
2510 BestMethod.push_back(Method);
2511 else if (EditDistance < BestEditDistance) {
2513 BestMethod.push_back(Method);
2517 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2518 QualType ObjectType) {
2519 if (ObjectType.isNull())
2521 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2523 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
2527 const ObjCMethodDecl *
2528 Sema::SelectorsForTypoCorrection(Selector Sel,
2529 QualType ObjectType) {
2530 unsigned NumArgs = Sel.getNumArgs();
2531 SmallVector<const ObjCMethodDecl *, 8> Methods;
2532 bool ObjectIsId = true, ObjectIsClass = true;
2533 if (ObjectType.isNull())
2534 ObjectIsId = ObjectIsClass = false;
2535 else if (!ObjectType->isObjCObjectPointerType())
2537 else if (const ObjCObjectPointerType *ObjCPtr =
2538 ObjectType->getAsObjCInterfacePointerType()) {
2539 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2540 ObjectIsId = ObjectIsClass = false;
2542 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2543 ObjectIsClass = false;
2544 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2549 for (GlobalMethodPool::iterator b = MethodPool.begin(),
2550 e = MethodPool.end(); b != e; b++) {
2552 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2553 if (M->getMethod() &&
2554 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
2555 (M->getMethod()->getSelector() != Sel)) {
2557 Methods.push_back(M->getMethod());
2558 else if (!ObjectIsClass &&
2559 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
2561 Methods.push_back(M->getMethod());
2564 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2565 if (M->getMethod() &&
2566 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
2567 (M->getMethod()->getSelector() != Sel)) {
2569 Methods.push_back(M->getMethod());
2570 else if (!ObjectIsId &&
2571 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
2573 Methods.push_back(M->getMethod());
2577 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2578 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2579 HelperSelectorsForTypoCorrection(SelectedMethods,
2580 Sel.getAsString(), Methods[i]);
2582 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
2585 /// DiagnoseDuplicateIvars -
2586 /// Check for duplicate ivars in the entire class at the start of
2587 /// \@implementation. This becomes necesssary because class extension can
2588 /// add ivars to a class in random order which will not be known until
2589 /// class's \@implementation is seen.
2590 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2591 ObjCInterfaceDecl *SID) {
2592 for (auto *Ivar : ID->ivars()) {
2593 if (Ivar->isInvalidDecl())
2595 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2596 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2598 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2599 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2600 Ivar->setInvalidDecl();
2606 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2607 switch (CurContext->getDeclKind()) {
2608 case Decl::ObjCInterface:
2609 return Sema::OCK_Interface;
2610 case Decl::ObjCProtocol:
2611 return Sema::OCK_Protocol;
2612 case Decl::ObjCCategory:
2613 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2614 return Sema::OCK_ClassExtension;
2615 return Sema::OCK_Category;
2616 case Decl::ObjCImplementation:
2617 return Sema::OCK_Implementation;
2618 case Decl::ObjCCategoryImpl:
2619 return Sema::OCK_CategoryImplementation;
2622 return Sema::OCK_None;
2626 // Note: For class/category implementations, allMethods is always null.
2627 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
2628 ArrayRef<DeclGroupPtrTy> allTUVars) {
2629 if (getObjCContainerKind() == Sema::OCK_None)
2632 assert(AtEnd.isValid() && "Invalid location for '@end'");
2634 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2635 Decl *ClassDecl = cast<Decl>(OCD);
2637 bool isInterfaceDeclKind =
2638 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2639 || isa<ObjCProtocolDecl>(ClassDecl);
2640 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2642 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2643 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2644 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2646 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
2647 ObjCMethodDecl *Method =
2648 cast_or_null<ObjCMethodDecl>(allMethods[i]);
2650 if (!Method) continue; // Already issued a diagnostic.
2651 if (Method->isInstanceMethod()) {
2652 /// Check for instance method of the same name with incompatible types
2653 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2654 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2656 if ((isInterfaceDeclKind && PrevMethod && !match)
2657 || (checkIdenticalMethods && match)) {
2658 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2659 << Method->getDeclName();
2660 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2661 Method->setInvalidDecl();
2664 Method->setAsRedeclaration(PrevMethod);
2665 if (!Context.getSourceManager().isInSystemHeader(
2666 Method->getLocation()))
2667 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2668 << Method->getDeclName();
2669 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2671 InsMap[Method->getSelector()] = Method;
2672 /// The following allows us to typecheck messages to "id".
2673 AddInstanceMethodToGlobalPool(Method);
2676 /// Check for class method of the same name with incompatible types
2677 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2678 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2680 if ((isInterfaceDeclKind && PrevMethod && !match)
2681 || (checkIdenticalMethods && match)) {
2682 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2683 << Method->getDeclName();
2684 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2685 Method->setInvalidDecl();
2688 Method->setAsRedeclaration(PrevMethod);
2689 if (!Context.getSourceManager().isInSystemHeader(
2690 Method->getLocation()))
2691 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2692 << Method->getDeclName();
2693 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2695 ClsMap[Method->getSelector()] = Method;
2696 AddFactoryMethodToGlobalPool(Method);
2700 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2701 // Nothing to do here.
2702 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2703 // Categories are used to extend the class by declaring new methods.
2704 // By the same token, they are also used to add new properties. No
2705 // need to compare the added property to those in the class.
2707 if (C->IsClassExtension()) {
2708 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2709 DiagnoseClassExtensionDupMethods(C, CCPrimary);
2712 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2713 if (CDecl->getIdentifier())
2714 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2715 // user-defined setter/getter. It also synthesizes setter/getter methods
2716 // and adds them to the DeclContext and global method pools.
2717 for (auto *I : CDecl->properties())
2718 ProcessPropertyDecl(I, CDecl);
2719 CDecl->setAtEndRange(AtEnd);
2721 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2722 IC->setAtEndRange(AtEnd);
2723 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2724 // Any property declared in a class extension might have user
2725 // declared setter or getter in current class extension or one
2726 // of the other class extensions. Mark them as synthesized as
2727 // property will be synthesized when property with same name is
2728 // seen in the @implementation.
2729 for (const auto *Ext : IDecl->visible_extensions()) {
2730 for (const auto *Property : Ext->properties()) {
2731 // Skip over properties declared @dynamic
2732 if (const ObjCPropertyImplDecl *PIDecl
2733 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2734 if (PIDecl->getPropertyImplementation()
2735 == ObjCPropertyImplDecl::Dynamic)
2738 for (const auto *Ext : IDecl->visible_extensions()) {
2739 if (ObjCMethodDecl *GetterMethod
2740 = Ext->getInstanceMethod(Property->getGetterName()))
2741 GetterMethod->setPropertyAccessor(true);
2742 if (!Property->isReadOnly())
2743 if (ObjCMethodDecl *SetterMethod
2744 = Ext->getInstanceMethod(Property->getSetterName()))
2745 SetterMethod->setPropertyAccessor(true);
2749 ImplMethodsVsClassMethods(S, IC, IDecl);
2750 AtomicPropertySetterGetterRules(IC, IDecl);
2751 DiagnoseOwningPropertyGetterSynthesis(IC);
2752 DiagnoseUnusedBackingIvarInAccessor(S, IC);
2753 if (IDecl->hasDesignatedInitializers())
2754 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2756 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2757 if (IDecl->getSuperClass() == nullptr) {
2758 // This class has no superclass, so check that it has been marked with
2759 // __attribute((objc_root_class)).
2760 if (!HasRootClassAttr) {
2761 SourceLocation DeclLoc(IDecl->getLocation());
2762 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
2763 Diag(DeclLoc, diag::warn_objc_root_class_missing)
2764 << IDecl->getIdentifier();
2765 // See if NSObject is in the current scope, and if it is, suggest
2766 // adding " : NSObject " to the class declaration.
2767 NamedDecl *IF = LookupSingleName(TUScope,
2768 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2769 DeclLoc, LookupOrdinaryName);
2770 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2771 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2772 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2773 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2775 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2778 } else if (HasRootClassAttr) {
2779 // Complain that only root classes may have this attribute.
2780 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2783 if (LangOpts.ObjCRuntime.isNonFragile()) {
2784 while (IDecl->getSuperClass()) {
2785 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2786 IDecl = IDecl->getSuperClass();
2790 SetIvarInitializers(IC);
2791 } else if (ObjCCategoryImplDecl* CatImplClass =
2792 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2793 CatImplClass->setAtEndRange(AtEnd);
2795 // Find category interface decl and then check that all methods declared
2796 // in this interface are implemented in the category @implementation.
2797 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2798 if (ObjCCategoryDecl *Cat
2799 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2800 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
2804 if (isInterfaceDeclKind) {
2805 // Reject invalid vardecls.
2806 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2807 DeclGroupRef DG = allTUVars[i].get();
2808 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2809 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2810 if (!VDecl->hasExternalStorage())
2811 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2815 ActOnObjCContainerFinishDefinition();
2817 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2818 DeclGroupRef DG = allTUVars[i].get();
2819 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2820 (*I)->setTopLevelDeclInObjCContainer();
2821 Consumer.HandleTopLevelDeclInObjCContainer(DG);
2824 ActOnDocumentableDecl(ClassDecl);
2829 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2830 /// objective-c's type qualifier from the parser version of the same info.
2831 static Decl::ObjCDeclQualifier
2832 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2833 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2836 /// \brief Check whether the declared result type of the given Objective-C
2837 /// method declaration is compatible with the method's class.
2839 static Sema::ResultTypeCompatibilityKind
2840 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2841 ObjCInterfaceDecl *CurrentClass) {
2842 QualType ResultType = Method->getReturnType();
2844 // If an Objective-C method inherits its related result type, then its
2845 // declared result type must be compatible with its own class type. The
2846 // declared result type is compatible if:
2847 if (const ObjCObjectPointerType *ResultObjectType
2848 = ResultType->getAs<ObjCObjectPointerType>()) {
2849 // - it is id or qualified id, or
2850 if (ResultObjectType->isObjCIdType() ||
2851 ResultObjectType->isObjCQualifiedIdType())
2852 return Sema::RTC_Compatible;
2855 if (ObjCInterfaceDecl *ResultClass
2856 = ResultObjectType->getInterfaceDecl()) {
2857 // - it is the same as the method's class type, or
2858 if (declaresSameEntity(CurrentClass, ResultClass))
2859 return Sema::RTC_Compatible;
2861 // - it is a superclass of the method's class type
2862 if (ResultClass->isSuperClassOf(CurrentClass))
2863 return Sema::RTC_Compatible;
2866 // Any Objective-C pointer type might be acceptable for a protocol
2867 // method; we just don't know.
2868 return Sema::RTC_Unknown;
2872 return Sema::RTC_Incompatible;
2876 /// A helper class for searching for methods which a particular method
2878 class OverrideSearch {
2881 ObjCMethodDecl *Method;
2882 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2886 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2887 Selector selector = method->getSelector();
2889 // Bypass this search if we've never seen an instance/class method
2890 // with this selector before.
2891 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2892 if (it == S.MethodPool.end()) {
2893 if (!S.getExternalSource()) return;
2894 S.ReadMethodPool(selector);
2896 it = S.MethodPool.find(selector);
2897 if (it == S.MethodPool.end())
2900 ObjCMethodList &list =
2901 method->isInstanceMethod() ? it->second.first : it->second.second;
2902 if (!list.getMethod()) return;
2904 ObjCContainerDecl *container
2905 = cast<ObjCContainerDecl>(method->getDeclContext());
2907 // Prevent the search from reaching this container again. This is
2908 // important with categories, which override methods from the
2909 // interface and each other.
2910 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2911 searchFromContainer(container);
2912 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2913 searchFromContainer(Interface);
2915 searchFromContainer(container);
2919 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
2920 iterator begin() const { return Overridden.begin(); }
2921 iterator end() const { return Overridden.end(); }
2924 void searchFromContainer(ObjCContainerDecl *container) {
2925 if (container->isInvalidDecl()) return;
2927 switch (container->getDeclKind()) {
2928 #define OBJCCONTAINER(type, base) \
2930 searchFrom(cast<type##Decl>(container)); \
2932 #define ABSTRACT_DECL(expansion)
2933 #define DECL(type, base) \
2935 #include "clang/AST/DeclNodes.inc"
2936 llvm_unreachable("not an ObjC container!");
2940 void searchFrom(ObjCProtocolDecl *protocol) {
2941 if (!protocol->hasDefinition())
2944 // A method in a protocol declaration overrides declarations from
2945 // referenced ("parent") protocols.
2946 search(protocol->getReferencedProtocols());
2949 void searchFrom(ObjCCategoryDecl *category) {
2950 // A method in a category declaration overrides declarations from
2951 // the main class and from protocols the category references.
2952 // The main class is handled in the constructor.
2953 search(category->getReferencedProtocols());
2956 void searchFrom(ObjCCategoryImplDecl *impl) {
2957 // A method in a category definition that has a category
2958 // declaration overrides declarations from the category
2960 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2962 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2965 // Otherwise it overrides declarations from the class.
2966 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2971 void searchFrom(ObjCInterfaceDecl *iface) {
2972 // A method in a class declaration overrides declarations from
2973 if (!iface->hasDefinition())
2977 for (auto *Cat : iface->known_categories())
2980 // - the super class, and
2981 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2984 // - any referenced protocols.
2985 search(iface->getReferencedProtocols());
2988 void searchFrom(ObjCImplementationDecl *impl) {
2989 // A method in a class implementation overrides declarations from
2990 // the class interface.
2991 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2996 void search(const ObjCProtocolList &protocols) {
2997 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
3002 void search(ObjCContainerDecl *container) {
3003 // Check for a method in this container which matches this selector.
3004 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
3005 Method->isInstanceMethod(),
3006 /*AllowHidden=*/true);
3008 // If we find one, record it and bail out.
3010 Overridden.insert(meth);
3014 // Otherwise, search for methods that a hypothetical method here
3015 // would have overridden.
3017 // Note that we're now in a recursive case.
3020 searchFromContainer(container);
3025 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
3026 ObjCInterfaceDecl *CurrentClass,
3027 ResultTypeCompatibilityKind RTC) {
3028 // Search for overridden methods and merge information down from them.
3029 OverrideSearch overrides(*this, ObjCMethod);
3030 // Keep track if the method overrides any method in the class's base classes,
3031 // its protocols, or its categories' protocols; we will keep that info
3032 // in the ObjCMethodDecl.
3033 // For this info, a method in an implementation is not considered as
3034 // overriding the same method in the interface or its categories.
3035 bool hasOverriddenMethodsInBaseOrProtocol = false;
3036 for (OverrideSearch::iterator
3037 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
3038 ObjCMethodDecl *overridden = *i;
3040 if (!hasOverriddenMethodsInBaseOrProtocol) {
3041 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3042 CurrentClass != overridden->getClassInterface() ||
3043 overridden->isOverriding()) {
3044 hasOverriddenMethodsInBaseOrProtocol = true;
3046 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3047 // OverrideSearch will return as "overridden" the same method in the
3048 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3049 // check whether a category of a base class introduced a method with the
3050 // same selector, after the interface method declaration.
3051 // To avoid unnecessary lookups in the majority of cases, we use the
3052 // extra info bits in GlobalMethodPool to check whether there were any
3053 // category methods with this selector.
3054 GlobalMethodPool::iterator It =
3055 MethodPool.find(ObjCMethod->getSelector());
3056 if (It != MethodPool.end()) {
3057 ObjCMethodList &List =
3058 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3059 unsigned CategCount = List.getBits();
3060 if (CategCount > 0) {
3061 // If the method is in a category we'll do lookup if there were at
3062 // least 2 category methods recorded, otherwise only one will do.
3063 if (CategCount > 1 ||
3064 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3065 OverrideSearch overrides(*this, overridden);
3066 for (OverrideSearch::iterator
3067 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3068 ObjCMethodDecl *SuperOverridden = *OI;
3069 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3070 CurrentClass != SuperOverridden->getClassInterface()) {
3071 hasOverriddenMethodsInBaseOrProtocol = true;
3072 overridden->setOverriding(true);
3082 // Propagate down the 'related result type' bit from overridden methods.
3083 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3084 ObjCMethod->SetRelatedResultType();
3086 // Then merge the declarations.
3087 mergeObjCMethodDecls(ObjCMethod, overridden);
3089 if (ObjCMethod->isImplicit() && overridden->isImplicit())
3090 continue; // Conflicting properties are detected elsewhere.
3092 // Check for overriding methods
3093 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3094 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3095 CheckConflictingOverridingMethod(ObjCMethod, overridden,
3096 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3098 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
3099 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3100 !overridden->isImplicit() /* not meant for properties */) {
3101 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3102 E = ObjCMethod->param_end();
3103 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3104 PrevE = overridden->param_end();
3105 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
3106 assert(PrevI != overridden->param_end() && "Param mismatch");
3107 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3108 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3109 // If type of argument of method in this class does not match its
3110 // respective argument type in the super class method, issue warning;
3111 if (!Context.typesAreCompatible(T1, T2)) {
3112 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3114 Diag(overridden->getLocation(), diag::note_previous_declaration);
3121 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3124 Decl *Sema::ActOnMethodDeclaration(
3126 SourceLocation MethodLoc, SourceLocation EndLoc,
3127 tok::TokenKind MethodType,
3128 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
3129 ArrayRef<SourceLocation> SelectorLocs,
3131 // optional arguments. The number of types/arguments is obtained
3132 // from the Sel.getNumArgs().
3133 ObjCArgInfo *ArgInfo,
3134 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
3135 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
3136 bool isVariadic, bool MethodDefinition) {
3137 // Make sure we can establish a context for the method.
3138 if (!CurContext->isObjCContainer()) {
3139 Diag(MethodLoc, diag::error_missing_method_context);
3142 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3143 Decl *ClassDecl = cast<Decl>(OCD);
3144 QualType resultDeclType;
3146 bool HasRelatedResultType = false;
3147 TypeSourceInfo *ReturnTInfo = nullptr;
3149 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
3151 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
3154 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
3155 } else { // get the type for "id".
3156 resultDeclType = Context.getObjCIdType();
3157 Diag(MethodLoc, diag::warn_missing_method_return_type)
3158 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
3161 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3162 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3163 MethodType == tok::minus, isVariadic,
3164 /*isPropertyAccessor=*/false,
3165 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3166 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3167 : ObjCMethodDecl::Required,
3168 HasRelatedResultType);
3170 SmallVector<ParmVarDecl*, 16> Params;
3172 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
3176 if (!ArgInfo[i].Type) {
3177 ArgType = Context.getObjCIdType();
3180 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
3183 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3184 LookupOrdinaryName, ForRedeclaration);
3186 if (R.isSingleResult()) {
3187 NamedDecl *PrevDecl = R.getFoundDecl();
3188 if (S->isDeclScope(PrevDecl)) {
3189 Diag(ArgInfo[i].NameLoc,
3190 (MethodDefinition ? diag::warn_method_param_redefinition
3191 : diag::warn_method_param_declaration))
3193 Diag(PrevDecl->getLocation(),
3194 diag::note_previous_declaration);
3198 SourceLocation StartLoc = DI
3199 ? DI->getTypeLoc().getBeginLoc()
3200 : ArgInfo[i].NameLoc;
3202 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3203 ArgInfo[i].NameLoc, ArgInfo[i].Name,
3204 ArgType, DI, SC_None);
3206 Param->setObjCMethodScopeInfo(i);
3208 Param->setObjCDeclQualifier(
3209 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
3211 // Apply the attributes to the parameter.
3212 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
3214 if (Param->hasAttr<BlocksAttr>()) {
3215 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3216 Param->setInvalidDecl();
3219 IdResolver.AddDecl(Param);
3221 Params.push_back(Param);
3224 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
3225 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
3226 QualType ArgType = Param->getType();
3227 if (ArgType.isNull())
3228 ArgType = Context.getObjCIdType();
3230 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
3231 ArgType = Context.getAdjustedParameterType(ArgType);
3233 Param->setDeclContext(ObjCMethod);
3234 Params.push_back(Param);
3237 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
3238 ObjCMethod->setObjCDeclQualifier(
3239 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
3242 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
3244 // Add the method now.
3245 const ObjCMethodDecl *PrevMethod = nullptr;
3246 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
3247 if (MethodType == tok::minus) {
3248 PrevMethod = ImpDecl->getInstanceMethod(Sel);
3249 ImpDecl->addInstanceMethod(ObjCMethod);
3251 PrevMethod = ImpDecl->getClassMethod(Sel);
3252 ImpDecl->addClassMethod(ObjCMethod);
3255 ObjCMethodDecl *IMD = nullptr;
3256 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3257 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3258 ObjCMethod->isInstanceMethod());
3259 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3260 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3261 // merge the attribute into implementation.
3262 ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3263 ObjCMethod->getLocation()));
3265 if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
3266 ObjCMethodFamily family =
3267 ObjCMethod->getSelector().getMethodFamily();
3268 if (family == OMF_dealloc && IMD && IMD->isOverriding())
3269 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
3270 << ObjCMethod->getDeclName();
3273 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
3277 // You can never have two method definitions with the same name.
3278 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
3279 << ObjCMethod->getDeclName();
3280 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3281 ObjCMethod->setInvalidDecl();
3285 // If this Objective-C method does not have a related result type, but we
3286 // are allowed to infer related result types, try to do so based on the
3288 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3289 if (!CurrentClass) {
3290 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3291 CurrentClass = Cat->getClassInterface();
3292 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3293 CurrentClass = Impl->getClassInterface();
3294 else if (ObjCCategoryImplDecl *CatImpl
3295 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3296 CurrentClass = CatImpl->getClassInterface();
3299 ResultTypeCompatibilityKind RTC
3300 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
3302 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
3304 bool ARCError = false;
3305 if (getLangOpts().ObjCAutoRefCount)
3306 ARCError = CheckARCMethodDecl(ObjCMethod);
3308 // Infer the related result type when possible.
3309 if (!ARCError && RTC == Sema::RTC_Compatible &&
3310 !ObjCMethod->hasRelatedResultType() &&
3311 LangOpts.ObjCInferRelatedResultType) {
3312 bool InferRelatedResultType = false;
3313 switch (ObjCMethod->getMethodFamily()) {
3318 case OMF_mutableCopy:
3320 case OMF_retainCount:
3321 case OMF_initialize:
3322 case OMF_performSelector:
3327 InferRelatedResultType = ObjCMethod->isClassMethod();
3331 case OMF_autorelease:
3334 InferRelatedResultType = ObjCMethod->isInstanceMethod();
3338 if (InferRelatedResultType &&
3339 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
3340 ObjCMethod->SetRelatedResultType();
3343 ActOnDocumentableDecl(ObjCMethod);
3348 bool Sema::CheckObjCDeclScope(Decl *D) {
3349 // Following is also an error. But it is caused by a missing @end
3350 // and diagnostic is issued elsewhere.
3351 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
3354 // If we switched context to translation unit while we are still lexically in
3355 // an objc container, it means the parser missed emitting an error.
3356 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3359 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3360 D->setInvalidDecl();
3365 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
3366 /// instance variables of ClassName into Decls.
3367 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3368 IdentifierInfo *ClassName,
3369 SmallVectorImpl<Decl*> &Decls) {
3370 // Check that ClassName is a valid class
3371 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
3373 Diag(DeclStart, diag::err_undef_interface) << ClassName;
3376 if (LangOpts.ObjCRuntime.isNonFragile()) {
3377 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3381 // Collect the instance variables
3382 SmallVector<const ObjCIvarDecl*, 32> Ivars;
3383 Context.DeepCollectObjCIvars(Class, true, Ivars);
3384 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
3385 for (unsigned i = 0; i < Ivars.size(); i++) {
3386 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
3387 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
3388 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3389 /*FIXME: StartL=*/ID->getLocation(),
3391 ID->getIdentifier(), ID->getType(),
3393 Decls.push_back(FD);
3396 // Introduce all of these fields into the appropriate scope.
3397 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
3398 D != Decls.end(); ++D) {
3399 FieldDecl *FD = cast<FieldDecl>(*D);
3400 if (getLangOpts().CPlusPlus)
3401 PushOnScopeChains(cast<FieldDecl>(FD), S);
3402 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
3403 Record->addDecl(FD);
3407 /// \brief Build a type-check a new Objective-C exception variable declaration.
3408 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3409 SourceLocation StartLoc,
3410 SourceLocation IdLoc,
3413 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3414 // duration shall not be qualified by an address-space qualifier."
3415 // Since all parameters have automatic store duration, they can not have
3416 // an address space.
3417 if (T.getAddressSpace() != 0) {
3418 Diag(IdLoc, diag::err_arg_with_address_space);
3422 // An @catch parameter must be an unqualified object pointer type;
3423 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3425 // Don't do any further checking.
3426 } else if (T->isDependentType()) {
3427 // Okay: we don't know what this type will instantiate to.
3428 } else if (!T->isObjCObjectPointerType()) {
3430 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3431 } else if (T->isObjCQualifiedIdType()) {
3433 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3436 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3438 New->setExceptionVariable(true);
3440 // In ARC, infer 'retaining' for variables of retainable type.
3441 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3445 New->setInvalidDecl();
3449 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3450 const DeclSpec &DS = D.getDeclSpec();
3452 // We allow the "register" storage class on exception variables because
3453 // GCC did, but we drop it completely. Any other storage class is an error.
3454 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3455 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3456 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3457 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3458 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3459 << DeclSpec::getSpecifierName(SCS);
3461 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3462 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3463 diag::err_invalid_thread)
3464 << DeclSpec::getSpecifierName(TSCS);
3465 D.getMutableDeclSpec().ClearStorageClassSpecs();
3467 DiagnoseFunctionSpecifiers(D.getDeclSpec());
3469 // Check that there are no default arguments inside the type of this
3470 // exception object (C++ only).
3471 if (getLangOpts().CPlusPlus)
3472 CheckExtraCXXDefaultArguments(D);
3474 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3475 QualType ExceptionType = TInfo->getType();
3477 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3478 D.getSourceRange().getBegin(),
3479 D.getIdentifierLoc(),
3483 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3484 if (D.getCXXScopeSpec().isSet()) {
3485 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3486 << D.getCXXScopeSpec().getRange();
3487 New->setInvalidDecl();
3490 // Add the parameter declaration into this scope.
3492 if (D.getIdentifier())
3493 IdResolver.AddDecl(New);
3495 ProcessDeclAttributes(S, New, D);
3497 if (New->hasAttr<BlocksAttr>())
3498 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3502 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3504 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3505 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3506 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3507 Iv= Iv->getNextIvar()) {
3508 QualType QT = Context.getBaseElementType(Iv->getType());
3509 if (QT->isRecordType())
3510 Ivars.push_back(Iv);
3514 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3515 // Load referenced selectors from the external source.
3516 if (ExternalSource) {
3517 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3518 ExternalSource->ReadReferencedSelectors(Sels);
3519 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3520 ReferencedSelectors[Sels[I].first] = Sels[I].second;
3523 // Warning will be issued only when selector table is
3524 // generated (which means there is at lease one implementation
3525 // in the TU). This is to match gcc's behavior.
3526 if (ReferencedSelectors.empty() ||
3527 !Context.AnyObjCImplementation())
3529 for (auto &SelectorAndLocation : ReferencedSelectors) {
3530 Selector Sel = SelectorAndLocation.first;
3531 SourceLocation Loc = SelectorAndLocation.second;
3532 if (!LookupImplementedMethodInGlobalPool(Sel))
3533 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
3539 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3540 const ObjCPropertyDecl *&PDecl) const {
3541 if (Method->isClassMethod())
3543 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3546 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3547 /*shallowCategoryLookup=*/false,
3548 /*followSuper=*/false);
3549 if (!Method || !Method->isPropertyAccessor())
3551 if ((PDecl = Method->findPropertyDecl()))
3552 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3553 // property backing ivar must belong to property's class
3554 // or be a private ivar in class's implementation.
3555 // FIXME. fix the const-ness issue.
3556 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3557 IV->getIdentifier());
3564 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3565 /// accessor references the backing ivar.
3566 class UnusedBackingIvarChecker :
3567 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
3570 const ObjCMethodDecl *Method;
3571 const ObjCIvarDecl *IvarD;
3573 bool InvokedSelfMethod;
3575 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3576 const ObjCIvarDecl *IvarD)
3577 : S(S), Method(Method), IvarD(IvarD),
3578 AccessedIvar(false), InvokedSelfMethod(false) {
3582 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3583 if (E->getDecl() == IvarD) {
3584 AccessedIvar = true;
3590 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3591 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3592 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3593 InvokedSelfMethod = true;
3600 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3601 const ObjCImplementationDecl *ImplD) {
3602 if (S->hasUnrecoverableErrorOccurred())
3605 for (const auto *CurMethod : ImplD->instance_methods()) {
3606 unsigned DIAG = diag::warn_unused_property_backing_ivar;
3607 SourceLocation Loc = CurMethod->getLocation();
3608 if (Diags.isIgnored(DIAG, Loc))
3611 const ObjCPropertyDecl *PDecl;
3612 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3616 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3617 Checker.TraverseStmt(CurMethod->getBody());
3618 if (Checker.AccessedIvar)
3621 // Do not issue this warning if backing ivar is used somewhere and accessor
3622 // implementation makes a self call. This is to prevent false positive in
3623 // cases where the ivar is accessed by another method that the accessor
3625 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
3626 Diag(Loc, DIAG) << IV;
3627 Diag(PDecl->getLocation(), diag::note_property_declare);